xref: /vim-8.2.3635/src/list.c (revision ef982575)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * list.c: List support and container (List, Dict, Blob) functions.
12  */
13 
14 #include "vim.h"
15 
16 #if defined(FEAT_EVAL) || defined(PROTO)
17 
18 static char *e_listblobarg = N_("E899: Argument of %s must be a List or Blob");
19 
20 // List heads for garbage collection.
21 static list_T		*first_list = NULL;	// list of all lists
22 
23 #define FOR_ALL_WATCHERS(l, lw) \
24     for ((lw) = (l)->lv_watch; (lw) != NULL; (lw) = (lw)->lw_next)
25 
26 static void list_free_item(list_T *l, listitem_T *item);
27 
28 /*
29  * Add a watcher to a list.
30  */
31     void
32 list_add_watch(list_T *l, listwatch_T *lw)
33 {
34     lw->lw_next = l->lv_watch;
35     l->lv_watch = lw;
36 }
37 
38 /*
39  * Remove a watcher from a list.
40  * No warning when it isn't found...
41  */
42     void
43 list_rem_watch(list_T *l, listwatch_T *lwrem)
44 {
45     listwatch_T	*lw, **lwp;
46 
47     lwp = &l->lv_watch;
48     FOR_ALL_WATCHERS(l, lw)
49     {
50 	if (lw == lwrem)
51 	{
52 	    *lwp = lw->lw_next;
53 	    break;
54 	}
55 	lwp = &lw->lw_next;
56     }
57 }
58 
59 /*
60  * Just before removing an item from a list: advance watchers to the next
61  * item.
62  */
63     static void
64 list_fix_watch(list_T *l, listitem_T *item)
65 {
66     listwatch_T	*lw;
67 
68     FOR_ALL_WATCHERS(l, lw)
69 	if (lw->lw_item == item)
70 	    lw->lw_item = item->li_next;
71 }
72 
73     static void
74 list_init(list_T *l)
75 {
76     // Prepend the list to the list of lists for garbage collection.
77     if (first_list != NULL)
78 	first_list->lv_used_prev = l;
79     l->lv_used_prev = NULL;
80     l->lv_used_next = first_list;
81     first_list = l;
82 }
83 
84 /*
85  * Allocate an empty header for a list.
86  * Caller should take care of the reference count.
87  */
88     list_T *
89 list_alloc(void)
90 {
91     list_T  *l;
92 
93     l = ALLOC_CLEAR_ONE(list_T);
94     if (l != NULL)
95 	list_init(l);
96     return l;
97 }
98 
99 /*
100  * list_alloc() with an ID for alloc_fail().
101  */
102     list_T *
103 list_alloc_id(alloc_id_T id UNUSED)
104 {
105 #ifdef FEAT_EVAL
106     if (alloc_fail_id == id && alloc_does_fail(sizeof(list_T)))
107 	return NULL;
108 #endif
109     return (list_alloc());
110 }
111 
112 /*
113  * Allocate space for a list, plus "count" items.
114  * Next list_set_item() must be called for each item.
115  */
116     list_T *
117 list_alloc_with_items(int count)
118 {
119     list_T	*l;
120 
121     l = (list_T *)alloc_clear(sizeof(list_T) + count * sizeof(listitem_T));
122     if (l != NULL)
123     {
124 	list_init(l);
125 
126 	if (count > 0)
127 	{
128 	    listitem_T	*li = (listitem_T *)(l + 1);
129 	    int		i;
130 
131 	    l->lv_len = count;
132 	    l->lv_with_items = count;
133 	    l->lv_first = li;
134 	    l->lv_u.mat.lv_last = li + count - 1;
135 	    for (i = 0; i < count; ++i)
136 	    {
137 		if (i == 0)
138 		    li->li_prev = NULL;
139 		else
140 		    li->li_prev = li - 1;
141 		if (i == count - 1)
142 		    li->li_next = NULL;
143 		else
144 		    li->li_next = li + 1;
145 		++li;
146 	    }
147 	}
148     }
149     return l;
150 }
151 
152 /*
153  * Set item "idx" for a list previously allocated with list_alloc_with_items().
154  * The contents of "tv" is moved into the list item.
155  * Each item must be set exactly once.
156  */
157     void
158 list_set_item(list_T *l, int idx, typval_T *tv)
159 {
160     listitem_T	*li = (listitem_T *)(l + 1) + idx;
161 
162     li->li_tv = *tv;
163 }
164 
165 /*
166  * Allocate an empty list for a return value, with reference count set.
167  * Returns OK or FAIL.
168  */
169     int
170 rettv_list_alloc(typval_T *rettv)
171 {
172     list_T	*l = list_alloc();
173 
174     if (l == NULL)
175 	return FAIL;
176 
177     rettv->v_lock = 0;
178     rettv_list_set(rettv, l);
179     return OK;
180 }
181 
182 /*
183  * Same as rettv_list_alloc() but uses an allocation id for testing.
184  */
185     int
186 rettv_list_alloc_id(typval_T *rettv, alloc_id_T id UNUSED)
187 {
188 #ifdef FEAT_EVAL
189     if (alloc_fail_id == id && alloc_does_fail(sizeof(list_T)))
190 	return FAIL;
191 #endif
192     return rettv_list_alloc(rettv);
193 }
194 
195 
196 /*
197  * Set a list as the return value.  Increments the reference count.
198  */
199     void
200 rettv_list_set(typval_T *rettv, list_T *l)
201 {
202     rettv->v_type = VAR_LIST;
203     rettv->vval.v_list = l;
204     if (l != NULL)
205 	++l->lv_refcount;
206 }
207 
208 /*
209  * Unreference a list: decrement the reference count and free it when it
210  * becomes zero.
211  */
212     void
213 list_unref(list_T *l)
214 {
215     if (l != NULL && --l->lv_refcount <= 0)
216 	list_free(l);
217 }
218 
219 /*
220  * Free a list, including all non-container items it points to.
221  * Ignores the reference count.
222  */
223     static void
224 list_free_contents(list_T *l)
225 {
226     listitem_T *item;
227 
228     if (l->lv_first != &range_list_item)
229 	for (item = l->lv_first; item != NULL; item = l->lv_first)
230 	{
231 	    // Remove the item before deleting it.
232 	    l->lv_first = item->li_next;
233 	    clear_tv(&item->li_tv);
234 	    list_free_item(l, item);
235 	}
236 }
237 
238 /*
239  * Go through the list of lists and free items without the copyID.
240  * But don't free a list that has a watcher (used in a for loop), these
241  * are not referenced anywhere.
242  */
243     int
244 list_free_nonref(int copyID)
245 {
246     list_T	*ll;
247     int		did_free = FALSE;
248 
249     for (ll = first_list; ll != NULL; ll = ll->lv_used_next)
250 	if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
251 						      && ll->lv_watch == NULL)
252 	{
253 	    // Free the List and ordinary items it contains, but don't recurse
254 	    // into Lists and Dictionaries, they will be in the list of dicts
255 	    // or list of lists.
256 	    list_free_contents(ll);
257 	    did_free = TRUE;
258 	}
259     return did_free;
260 }
261 
262     static void
263 list_free_list(list_T  *l)
264 {
265     // Remove the list from the list of lists for garbage collection.
266     if (l->lv_used_prev == NULL)
267 	first_list = l->lv_used_next;
268     else
269 	l->lv_used_prev->lv_used_next = l->lv_used_next;
270     if (l->lv_used_next != NULL)
271 	l->lv_used_next->lv_used_prev = l->lv_used_prev;
272 
273     free_type(l->lv_type);
274     vim_free(l);
275 }
276 
277     void
278 list_free_items(int copyID)
279 {
280     list_T	*ll, *ll_next;
281 
282     for (ll = first_list; ll != NULL; ll = ll_next)
283     {
284 	ll_next = ll->lv_used_next;
285 	if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
286 						      && ll->lv_watch == NULL)
287 	{
288 	    // Free the List and ordinary items it contains, but don't recurse
289 	    // into Lists and Dictionaries, they will be in the list of dicts
290 	    // or list of lists.
291 	    list_free_list(ll);
292 	}
293     }
294 }
295 
296     void
297 list_free(list_T *l)
298 {
299     if (!in_free_unref_items)
300     {
301 	list_free_contents(l);
302 	list_free_list(l);
303     }
304 }
305 
306 /*
307  * Allocate a list item.
308  * It is not initialized, don't forget to set v_lock.
309  */
310     listitem_T *
311 listitem_alloc(void)
312 {
313     return ALLOC_ONE(listitem_T);
314 }
315 
316 /*
317  * Free a list item, unless it was allocated together with the list itself.
318  * Does not clear the value.  Does not notify watchers.
319  */
320     static void
321 list_free_item(list_T *l, listitem_T *item)
322 {
323     if (l->lv_with_items == 0 || item < (listitem_T *)l
324 			   || item >= (listitem_T *)(l + 1) + l->lv_with_items)
325 	vim_free(item);
326 }
327 
328 /*
329  * Free a list item, unless it was allocated together with the list itself.
330  * Also clears the value.  Does not notify watchers.
331  */
332     void
333 listitem_free(list_T *l, listitem_T *item)
334 {
335     clear_tv(&item->li_tv);
336     list_free_item(l, item);
337 }
338 
339 /*
340  * Remove a list item from a List and free it.  Also clears the value.
341  */
342     void
343 listitem_remove(list_T *l, listitem_T *item)
344 {
345     vimlist_remove(l, item, item);
346     listitem_free(l, item);
347 }
348 
349 /*
350  * Get the number of items in a list.
351  */
352     long
353 list_len(list_T *l)
354 {
355     if (l == NULL)
356 	return 0L;
357     return l->lv_len;
358 }
359 
360 /*
361  * Return TRUE when two lists have exactly the same values.
362  */
363     int
364 list_equal(
365     list_T	*l1,
366     list_T	*l2,
367     int		ic,	// ignore case for strings
368     int		recursive)  // TRUE when used recursively
369 {
370     listitem_T	*item1, *item2;
371 
372     if (l1 == l2)
373 	return TRUE;
374     if (list_len(l1) != list_len(l2))
375 	return FALSE;
376     if (list_len(l1) == 0)
377 	// empty and NULL list are considered equal
378 	return TRUE;
379     if (l1 == NULL || l2 == NULL)
380 	return FALSE;
381 
382     CHECK_LIST_MATERIALIZE(l1);
383     CHECK_LIST_MATERIALIZE(l2);
384 
385     for (item1 = l1->lv_first, item2 = l2->lv_first;
386 	    item1 != NULL && item2 != NULL;
387 			       item1 = item1->li_next, item2 = item2->li_next)
388 	if (!tv_equal(&item1->li_tv, &item2->li_tv, ic, recursive))
389 	    return FALSE;
390     return item1 == NULL && item2 == NULL;
391 }
392 
393 /*
394  * Locate item with index "n" in list "l" and return it.
395  * A negative index is counted from the end; -1 is the last item.
396  * Returns NULL when "n" is out of range.
397  */
398     listitem_T *
399 list_find(list_T *l, long n)
400 {
401     listitem_T	*item;
402     long	idx;
403 
404     if (l == NULL)
405 	return NULL;
406 
407     // Negative index is relative to the end.
408     if (n < 0)
409 	n = l->lv_len + n;
410 
411     // Check for index out of range.
412     if (n < 0 || n >= l->lv_len)
413 	return NULL;
414 
415     CHECK_LIST_MATERIALIZE(l);
416 
417     // When there is a cached index may start search from there.
418     if (l->lv_u.mat.lv_idx_item != NULL)
419     {
420 	if (n < l->lv_u.mat.lv_idx / 2)
421 	{
422 	    // closest to the start of the list
423 	    item = l->lv_first;
424 	    idx = 0;
425 	}
426 	else if (n > (l->lv_u.mat.lv_idx + l->lv_len) / 2)
427 	{
428 	    // closest to the end of the list
429 	    item = l->lv_u.mat.lv_last;
430 	    idx = l->lv_len - 1;
431 	}
432 	else
433 	{
434 	    // closest to the cached index
435 	    item = l->lv_u.mat.lv_idx_item;
436 	    idx = l->lv_u.mat.lv_idx;
437 	}
438     }
439     else
440     {
441 	if (n < l->lv_len / 2)
442 	{
443 	    // closest to the start of the list
444 	    item = l->lv_first;
445 	    idx = 0;
446 	}
447 	else
448 	{
449 	    // closest to the end of the list
450 	    item = l->lv_u.mat.lv_last;
451 	    idx = l->lv_len - 1;
452 	}
453     }
454 
455     while (n > idx)
456     {
457 	// search forward
458 	item = item->li_next;
459 	++idx;
460     }
461     while (n < idx)
462     {
463 	// search backward
464 	item = item->li_prev;
465 	--idx;
466     }
467 
468     // cache the used index
469     l->lv_u.mat.lv_idx = idx;
470     l->lv_u.mat.lv_idx_item = item;
471 
472     return item;
473 }
474 
475 /*
476  * Get list item "l[idx]" as a number.
477  */
478     long
479 list_find_nr(
480     list_T	*l,
481     long	idx,
482     int		*errorp)	// set to TRUE when something wrong
483 {
484     listitem_T	*li;
485 
486     if (l != NULL && l->lv_first == &range_list_item)
487     {
488 	long	    n = idx;
489 
490 	// not materialized range() list: compute the value.
491 	// Negative index is relative to the end.
492 	if (n < 0)
493 	    n = l->lv_len + n;
494 
495 	// Check for index out of range.
496 	if (n < 0 || n >= l->lv_len)
497 	{
498 	    if (errorp != NULL)
499 		*errorp = TRUE;
500 	    return -1L;
501 	}
502 
503 	return l->lv_u.nonmat.lv_start + n * l->lv_u.nonmat.lv_stride;
504     }
505 
506     li = list_find(l, idx);
507     if (li == NULL)
508     {
509 	if (errorp != NULL)
510 	    *errorp = TRUE;
511 	return -1L;
512     }
513     return (long)tv_get_number_chk(&li->li_tv, errorp);
514 }
515 
516 /*
517  * Get list item "l[idx - 1]" as a string.  Returns NULL for failure.
518  */
519     char_u *
520 list_find_str(list_T *l, long idx)
521 {
522     listitem_T	*li;
523 
524     li = list_find(l, idx - 1);
525     if (li == NULL)
526     {
527 	semsg(_(e_listidx), idx);
528 	return NULL;
529     }
530     return tv_get_string(&li->li_tv);
531 }
532 
533 /*
534  * Like list_find() but when a negative index is used that is not found use
535  * zero and set "idx" to zero.  Used for first index of a range.
536  */
537     listitem_T *
538 list_find_index(list_T *l, long *idx)
539 {
540     listitem_T *li = list_find(l, *idx);
541 
542     if (li == NULL)
543     {
544 	if (*idx < 0)
545 	{
546 	    *idx = 0;
547 	    li = list_find(l, *idx);
548 	}
549     }
550     return li;
551 }
552 
553 /*
554  * Locate "item" list "l" and return its index.
555  * Returns -1 when "item" is not in the list.
556  */
557     long
558 list_idx_of_item(list_T *l, listitem_T *item)
559 {
560     long	idx = 0;
561     listitem_T	*li;
562 
563     if (l == NULL)
564 	return -1;
565     CHECK_LIST_MATERIALIZE(l);
566     idx = 0;
567     for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
568 	++idx;
569     if (li == NULL)
570 	return -1;
571     return idx;
572 }
573 
574 /*
575  * Append item "item" to the end of list "l".
576  */
577     void
578 list_append(list_T *l, listitem_T *item)
579 {
580     CHECK_LIST_MATERIALIZE(l);
581     if (l->lv_u.mat.lv_last == NULL)
582     {
583 	// empty list
584 	l->lv_first = item;
585 	l->lv_u.mat.lv_last = item;
586 	item->li_prev = NULL;
587     }
588     else
589     {
590 	l->lv_u.mat.lv_last->li_next = item;
591 	item->li_prev = l->lv_u.mat.lv_last;
592 	l->lv_u.mat.lv_last = item;
593     }
594     ++l->lv_len;
595     item->li_next = NULL;
596 }
597 
598 /*
599  * Append typval_T "tv" to the end of list "l".  "tv" is copied.
600  * Return FAIL when out of memory or the type is wrong.
601  */
602     int
603 list_append_tv(list_T *l, typval_T *tv)
604 {
605     listitem_T	*li;
606 
607     if (l->lv_type != NULL && l->lv_type->tt_member != NULL
608 		&& check_typval_arg_type(l->lv_type->tt_member, tv,
609 							      NULL, 0) == FAIL)
610 	return FAIL;
611     li = listitem_alloc();
612     if (li == NULL)
613 	return FAIL;
614     copy_tv(tv, &li->li_tv);
615     list_append(l, li);
616     return OK;
617 }
618 
619 /*
620  * As list_append_tv() but move the value instead of copying it.
621  * Return FAIL when out of memory.
622  */
623     static int
624 list_append_tv_move(list_T *l, typval_T *tv)
625 {
626     listitem_T	*li = listitem_alloc();
627 
628     if (li == NULL)
629 	return FAIL;
630     li->li_tv = *tv;
631     list_append(l, li);
632     return OK;
633 }
634 
635 /*
636  * Add a dictionary to a list.  Used by getqflist().
637  * Return FAIL when out of memory.
638  */
639     int
640 list_append_dict(list_T *list, dict_T *dict)
641 {
642     listitem_T	*li = listitem_alloc();
643 
644     if (li == NULL)
645 	return FAIL;
646     li->li_tv.v_type = VAR_DICT;
647     li->li_tv.v_lock = 0;
648     li->li_tv.vval.v_dict = dict;
649     list_append(list, li);
650     ++dict->dv_refcount;
651     return OK;
652 }
653 
654 /*
655  * Append list2 to list1.
656  * Return FAIL when out of memory.
657  */
658     int
659 list_append_list(list_T *list1, list_T *list2)
660 {
661     listitem_T	*li = listitem_alloc();
662 
663     if (li == NULL)
664 	return FAIL;
665     li->li_tv.v_type = VAR_LIST;
666     li->li_tv.v_lock = 0;
667     li->li_tv.vval.v_list = list2;
668     list_append(list1, li);
669     ++list2->lv_refcount;
670     return OK;
671 }
672 
673 /*
674  * Make a copy of "str" and append it as an item to list "l".
675  * When "len" >= 0 use "str[len]".
676  * Returns FAIL when out of memory.
677  */
678     int
679 list_append_string(list_T *l, char_u *str, int len)
680 {
681     listitem_T *li = listitem_alloc();
682 
683     if (li == NULL)
684 	return FAIL;
685     list_append(l, li);
686     li->li_tv.v_type = VAR_STRING;
687     li->li_tv.v_lock = 0;
688     if (str == NULL)
689 	li->li_tv.vval.v_string = NULL;
690     else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
691 						 : vim_strsave(str))) == NULL)
692 	return FAIL;
693     return OK;
694 }
695 
696 /*
697  * Append "n" to list "l".
698  * Returns FAIL when out of memory.
699  */
700     int
701 list_append_number(list_T *l, varnumber_T n)
702 {
703     listitem_T	*li;
704 
705     li = listitem_alloc();
706     if (li == NULL)
707 	return FAIL;
708     li->li_tv.v_type = VAR_NUMBER;
709     li->li_tv.v_lock = 0;
710     li->li_tv.vval.v_number = n;
711     list_append(l, li);
712     return OK;
713 }
714 
715 /*
716  * Insert typval_T "tv" in list "l" before "item".
717  * If "item" is NULL append at the end.
718  * Return FAIL when out of memory or the type is wrong.
719  */
720     int
721 list_insert_tv(list_T *l, typval_T *tv, listitem_T *item)
722 {
723     listitem_T	*ni;
724 
725     if (l->lv_type != NULL && l->lv_type->tt_member != NULL
726 		&& check_typval_arg_type(l->lv_type->tt_member, tv,
727 							      NULL, 0) == FAIL)
728 	return FAIL;
729     ni = listitem_alloc();
730     if (ni == NULL)
731 	return FAIL;
732     copy_tv(tv, &ni->li_tv);
733     list_insert(l, ni, item);
734     return OK;
735 }
736 
737     void
738 list_insert(list_T *l, listitem_T *ni, listitem_T *item)
739 {
740     CHECK_LIST_MATERIALIZE(l);
741     if (item == NULL)
742 	// Append new item at end of list.
743 	list_append(l, ni);
744     else
745     {
746 	// Insert new item before existing item.
747 	ni->li_prev = item->li_prev;
748 	ni->li_next = item;
749 	if (item->li_prev == NULL)
750 	{
751 	    l->lv_first = ni;
752 	    ++l->lv_u.mat.lv_idx;
753 	}
754 	else
755 	{
756 	    item->li_prev->li_next = ni;
757 	    l->lv_u.mat.lv_idx_item = NULL;
758 	}
759 	item->li_prev = ni;
760 	++l->lv_len;
761     }
762 }
763 
764 /*
765  * Get the list item in "l" with index "n1".  "n1" is adjusted if needed.
766  * In Vim9, it is at the end of the list, add an item.
767  * Return NULL if there is no such item.
768  */
769     listitem_T *
770 check_range_index_one(list_T *l, long *n1, int quiet)
771 {
772     listitem_T *li = list_find_index(l, n1);
773 
774     if (li == NULL)
775     {
776 	// Vim9: Allow for adding an item at the end.
777 	if (in_vim9script() && *n1 == l->lv_len && l->lv_lock == 0)
778 	{
779 	    list_append_number(l, 0);
780 	    li = list_find_index(l, n1);
781 	}
782 	if (li == NULL)
783 	{
784 	    if (!quiet)
785 		semsg(_(e_listidx), *n1);
786 	    return NULL;
787 	}
788     }
789     return li;
790 }
791 
792 /*
793  * Check that "n2" can be used as the second index in a range of list "l".
794  * If "n1" or "n2" is negative it is changed to the positive index.
795  * "li1" is the item for item "n1".
796  * Return OK or FAIL.
797  */
798     int
799 check_range_index_two(
800 	list_T	    *l,
801 	long	    *n1,
802 	listitem_T  *li1,
803 	long	    *n2,
804 	int	    quiet)
805 {
806     if (*n2 < 0)
807     {
808 	listitem_T	*ni = list_find(l, *n2);
809 
810 	if (ni == NULL)
811 	{
812 	    if (!quiet)
813 		semsg(_(e_listidx), *n2);
814 	    return FAIL;
815 	}
816 	*n2 = list_idx_of_item(l, ni);
817     }
818 
819     // Check that n2 isn't before n1.
820     if (*n1 < 0)
821 	*n1 = list_idx_of_item(l, li1);
822     if (*n2 < *n1)
823     {
824 	if (!quiet)
825 	    semsg(_(e_listidx), *n2);
826 	return FAIL;
827     }
828     return OK;
829 }
830 
831 /*
832  * Assign values from list "src" into a range of "dest".
833  * "idx1_arg" is the index of the first item in "dest" to be replaced.
834  * "idx2" is the index of last item to be replaced, but when "empty_idx2" is
835  * TRUE then replace all items after "idx1".
836  * "op" is the operator, normally "=" but can be "+=" and the like.
837  * "varname" is used for error messages.
838  * Returns OK or FAIL.
839  */
840     int
841 list_assign_range(
842 	list_T	    *dest,
843 	list_T	    *src,
844 	long	    idx1_arg,
845 	long	    idx2,
846 	int	    empty_idx2,
847 	char_u	    *op,
848 	char_u	    *varname)
849 {
850     listitem_T	*src_li;
851     listitem_T	*dest_li;
852     long	idx1 = idx1_arg;
853     listitem_T	*first_li = list_find_index(dest, &idx1);
854     long	idx;
855 
856     /*
857      * Check whether any of the list items is locked before making any changes.
858      */
859     idx = idx1;
860     dest_li = first_li;
861     for (src_li = src->lv_first; src_li != NULL && dest_li != NULL; )
862     {
863 	if (value_check_lock(dest_li->li_tv.v_lock, varname, FALSE))
864 	    return FAIL;
865 	src_li = src_li->li_next;
866 	if (src_li == NULL || (!empty_idx2 && idx2 == idx))
867 	    break;
868 	dest_li = dest_li->li_next;
869 	++idx;
870     }
871 
872     /*
873      * Assign the List values to the list items.
874      */
875     idx = idx1;
876     dest_li = first_li;
877     for (src_li = src->lv_first; src_li != NULL; )
878     {
879 	if (op != NULL && *op != '=')
880 	    tv_op(&dest_li->li_tv, &src_li->li_tv, op);
881 	else
882 	{
883 	    clear_tv(&dest_li->li_tv);
884 	    copy_tv(&src_li->li_tv, &dest_li->li_tv);
885 	}
886 	src_li = src_li->li_next;
887 	if (src_li == NULL || (!empty_idx2 && idx2 == idx))
888 	    break;
889 	if (dest_li->li_next == NULL)
890 	{
891 	    // Need to add an empty item.
892 	    if (list_append_number(dest, 0) == FAIL)
893 	    {
894 		src_li = NULL;
895 		break;
896 	    }
897 	}
898 	dest_li = dest_li->li_next;
899 	++idx;
900     }
901     if (src_li != NULL)
902     {
903 	emsg(_(e_list_value_has_more_items_than_targets));
904 	return FAIL;
905     }
906     if (empty_idx2
907 	    ? (dest_li != NULL && dest_li->li_next != NULL)
908 	    : idx != idx2)
909     {
910 	emsg(_(e_list_value_does_not_have_enough_items));
911 	return FAIL;
912     }
913     return OK;
914 }
915 
916 /*
917  * Flatten "list" to depth "maxdepth".
918  * It does nothing if "maxdepth" is 0.
919  * Returns FAIL when out of memory.
920  */
921     static void
922 list_flatten(list_T *list, long maxdepth)
923 {
924     listitem_T	*item;
925     listitem_T	*tofree;
926     int		n;
927 
928     if (maxdepth == 0)
929 	return;
930     CHECK_LIST_MATERIALIZE(list);
931 
932     n = 0;
933     item = list->lv_first;
934     while (item != NULL)
935     {
936 	fast_breakcheck();
937 	if (got_int)
938 	    return;
939 
940 	if (item->li_tv.v_type == VAR_LIST)
941 	{
942 	    listitem_T *next = item->li_next;
943 
944 	    vimlist_remove(list, item, item);
945 	    if (list_extend(list, item->li_tv.vval.v_list, next) == FAIL)
946 		return;
947 	    clear_tv(&item->li_tv);
948 	    tofree = item;
949 
950 	    if (item->li_prev == NULL)
951 		item = list->lv_first;
952 	    else
953 		item = item->li_prev->li_next;
954 	    list_free_item(list, tofree);
955 
956 	    if (++n >= maxdepth)
957 	    {
958 		n = 0;
959 		item = next;
960 	    }
961 	}
962 	else
963 	{
964 	    n = 0;
965 	    item = item->li_next;
966 	}
967     }
968 }
969 
970 /*
971  * "flatten()" and "flattennew()" functions
972  */
973     static void
974 flatten_common(typval_T *argvars, typval_T *rettv, int make_copy)
975 {
976     list_T  *l;
977     long    maxdepth;
978     int	    error = FALSE;
979 
980     if (in_vim9script()
981 	    && (check_for_list_arg(argvars, 0) == FAIL
982 		|| check_for_opt_number_arg(argvars, 1) == FAIL))
983 	return;
984 
985     if (argvars[0].v_type != VAR_LIST)
986     {
987 	semsg(_(e_listarg), "flatten()");
988 	return;
989     }
990 
991     if (argvars[1].v_type == VAR_UNKNOWN)
992 	maxdepth = 999999;
993     else
994     {
995 	maxdepth = (long)tv_get_number_chk(&argvars[1], &error);
996 	if (error)
997 	    return;
998 	if (maxdepth < 0)
999 	{
1000 	    emsg(_("E900: maxdepth must be non-negative number"));
1001 	    return;
1002 	}
1003     }
1004 
1005     l = argvars[0].vval.v_list;
1006     rettv->v_type = VAR_LIST;
1007     rettv->vval.v_list = l;
1008     if (l == NULL)
1009 	return;
1010 
1011     if (make_copy)
1012     {
1013 	l = list_copy(l, TRUE, get_copyID());
1014 	rettv->vval.v_list = l;
1015 	if (l == NULL)
1016 	    return;
1017     }
1018     else
1019     {
1020 	if (value_check_lock(l->lv_lock,
1021 				     (char_u *)N_("flatten() argument"), TRUE))
1022 	    return;
1023 	++l->lv_refcount;
1024     }
1025 
1026     list_flatten(l, maxdepth);
1027 }
1028 
1029 /*
1030  * "flatten(list[, {maxdepth}])" function
1031  */
1032     void
1033 f_flatten(typval_T *argvars, typval_T *rettv)
1034 {
1035     if (in_vim9script())
1036 	emsg(_(e_cannot_use_flatten_in_vim9_script));
1037     else
1038 	flatten_common(argvars, rettv, FALSE);
1039 }
1040 
1041 /*
1042  * "flattennew(list[, {maxdepth}])" function
1043  */
1044     void
1045 f_flattennew(typval_T *argvars, typval_T *rettv)
1046 {
1047     flatten_common(argvars, rettv, TRUE);
1048 }
1049 
1050 /*
1051  * Extend "l1" with "l2".  "l1" must not be NULL.
1052  * If "bef" is NULL append at the end, otherwise insert before this item.
1053  * Returns FAIL when out of memory.
1054  */
1055     int
1056 list_extend(list_T *l1, list_T *l2, listitem_T *bef)
1057 {
1058     listitem_T	*item;
1059     int		todo;
1060     listitem_T	*bef_prev;
1061 
1062     // NULL list is equivalent to an empty list: nothing to do.
1063     if (l2 == NULL || l2->lv_len == 0)
1064 	return OK;
1065 
1066     todo = l2->lv_len;
1067     CHECK_LIST_MATERIALIZE(l1);
1068     CHECK_LIST_MATERIALIZE(l2);
1069 
1070     // When exending a list with itself, at some point we run into the item
1071     // that was before "bef" and need to skip over the already inserted items
1072     // to "bef".
1073     bef_prev = bef == NULL ? NULL : bef->li_prev;
1074 
1075     // We also quit the loop when we have inserted the original item count of
1076     // the list, avoid a hang when we extend a list with itself.
1077     for (item = l2->lv_first; item != NULL && --todo >= 0;
1078 				 item = item == bef_prev ? bef : item->li_next)
1079 	if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
1080 	    return FAIL;
1081     return OK;
1082 }
1083 
1084 /*
1085  * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
1086  * Return FAIL when out of memory.
1087  */
1088     int
1089 list_concat(list_T *l1, list_T *l2, typval_T *tv)
1090 {
1091     list_T	*l;
1092 
1093     // make a copy of the first list.
1094     if (l1 == NULL)
1095 	l = list_alloc();
1096     else
1097 	l = list_copy(l1, FALSE, 0);
1098     if (l == NULL)
1099 	return FAIL;
1100     tv->v_type = VAR_LIST;
1101     tv->v_lock = 0;
1102     tv->vval.v_list = l;
1103     if (l1 == NULL)
1104 	++l->lv_refcount;
1105 
1106     // append all items from the second list
1107     return list_extend(l, l2, NULL);
1108 }
1109 
1110     list_T *
1111 list_slice(list_T *ol, long n1, long n2)
1112 {
1113     listitem_T	*item;
1114     list_T	*l = list_alloc();
1115 
1116     if (l == NULL)
1117 	return NULL;
1118     for (item = list_find(ol, n1); n1 <= n2; ++n1)
1119     {
1120 	if (list_append_tv(l, &item->li_tv) == FAIL)
1121 	{
1122 	    list_free(l);
1123 	    return NULL;
1124 	}
1125 	item = item->li_next;
1126     }
1127     return l;
1128 }
1129 
1130     int
1131 list_slice_or_index(
1132 	    list_T	*list,
1133 	    int		range,
1134 	    varnumber_T	n1_arg,
1135 	    varnumber_T	n2_arg,
1136 	    int		exclusive,
1137 	    typval_T	*rettv,
1138 	    int		verbose)
1139 {
1140     long	len = list_len(list);
1141     varnumber_T	n1 = n1_arg;
1142     varnumber_T	n2 = n2_arg;
1143     typval_T	var1;
1144 
1145     if (n1 < 0)
1146 	n1 = len + n1;
1147     if (n1 < 0 || n1 >= len)
1148     {
1149 	// For a range we allow invalid values and return an empty
1150 	// list.  A list index out of range is an error.
1151 	if (!range)
1152 	{
1153 	    if (verbose)
1154 		semsg(_(e_listidx), (long)n1_arg);
1155 	    return FAIL;
1156 	}
1157 	n1 = n1 < 0 ? 0 : len;
1158     }
1159     if (range)
1160     {
1161 	list_T	*l;
1162 
1163 	if (n2 < 0)
1164 	    n2 = len + n2;
1165 	else if (n2 >= len)
1166 	    n2 = len - (exclusive ? 0 : 1);
1167 	if (exclusive)
1168 	    --n2;
1169 	if (n2 < 0 || n2 + 1 < n1)
1170 	    n2 = -1;
1171 	l = list_slice(list, n1, n2);
1172 	if (l == NULL)
1173 	    return FAIL;
1174 	clear_tv(rettv);
1175 	rettv_list_set(rettv, l);
1176     }
1177     else
1178     {
1179 	// copy the item to "var1" to avoid that freeing the list makes it
1180 	// invalid.
1181 	copy_tv(&list_find(list, n1)->li_tv, &var1);
1182 	clear_tv(rettv);
1183 	*rettv = var1;
1184     }
1185     return OK;
1186 }
1187 
1188 /*
1189  * Make a copy of list "orig".  Shallow if "deep" is FALSE.
1190  * The refcount of the new list is set to 1.
1191  * See item_copy() for "copyID".
1192  * Returns NULL when out of memory.
1193  */
1194     list_T *
1195 list_copy(list_T *orig, int deep, int copyID)
1196 {
1197     list_T	*copy;
1198     listitem_T	*item;
1199     listitem_T	*ni;
1200 
1201     if (orig == NULL)
1202 	return NULL;
1203 
1204     copy = list_alloc();
1205     if (copy != NULL)
1206     {
1207 	if (copyID != 0)
1208 	{
1209 	    // Do this before adding the items, because one of the items may
1210 	    // refer back to this list.
1211 	    orig->lv_copyID = copyID;
1212 	    orig->lv_copylist = copy;
1213 	}
1214 	CHECK_LIST_MATERIALIZE(orig);
1215 	for (item = orig->lv_first; item != NULL && !got_int;
1216 							 item = item->li_next)
1217 	{
1218 	    ni = listitem_alloc();
1219 	    if (ni == NULL)
1220 		break;
1221 	    if (deep)
1222 	    {
1223 		if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
1224 		{
1225 		    vim_free(ni);
1226 		    break;
1227 		}
1228 	    }
1229 	    else
1230 		copy_tv(&item->li_tv, &ni->li_tv);
1231 	    list_append(copy, ni);
1232 	}
1233 	++copy->lv_refcount;
1234 	if (item != NULL)
1235 	{
1236 	    list_unref(copy);
1237 	    copy = NULL;
1238 	}
1239     }
1240 
1241     return copy;
1242 }
1243 
1244 /*
1245  * Remove items "item" to "item2" from list "l".
1246  * Does not free the listitem or the value!
1247  * This used to be called list_remove, but that conflicts with a Sun header
1248  * file.
1249  */
1250     void
1251 vimlist_remove(list_T *l, listitem_T *item, listitem_T *item2)
1252 {
1253     listitem_T	*ip;
1254 
1255     CHECK_LIST_MATERIALIZE(l);
1256 
1257     // notify watchers
1258     for (ip = item; ip != NULL; ip = ip->li_next)
1259     {
1260 	--l->lv_len;
1261 	list_fix_watch(l, ip);
1262 	if (ip == item2)
1263 	    break;
1264     }
1265 
1266     if (item2->li_next == NULL)
1267 	l->lv_u.mat.lv_last = item->li_prev;
1268     else
1269 	item2->li_next->li_prev = item->li_prev;
1270     if (item->li_prev == NULL)
1271 	l->lv_first = item2->li_next;
1272     else
1273 	item->li_prev->li_next = item2->li_next;
1274     l->lv_u.mat.lv_idx_item = NULL;
1275 }
1276 
1277 /*
1278  * Return an allocated string with the string representation of a list.
1279  * May return NULL.
1280  */
1281     char_u *
1282 list2string(typval_T *tv, int copyID, int restore_copyID)
1283 {
1284     garray_T	ga;
1285 
1286     if (tv->vval.v_list == NULL)
1287 	return NULL;
1288     ga_init2(&ga, (int)sizeof(char), 80);
1289     ga_append(&ga, '[');
1290     CHECK_LIST_MATERIALIZE(tv->vval.v_list);
1291     if (list_join(&ga, tv->vval.v_list, (char_u *)", ",
1292 				       FALSE, restore_copyID, copyID) == FAIL)
1293     {
1294 	vim_free(ga.ga_data);
1295 	return NULL;
1296     }
1297     ga_append(&ga, ']');
1298     ga_append(&ga, NUL);
1299     return (char_u *)ga.ga_data;
1300 }
1301 
1302 typedef struct join_S {
1303     char_u	*s;
1304     char_u	*tofree;
1305 } join_T;
1306 
1307     static int
1308 list_join_inner(
1309     garray_T	*gap,		// to store the result in
1310     list_T	*l,
1311     char_u	*sep,
1312     int		echo_style,
1313     int		restore_copyID,
1314     int		copyID,
1315     garray_T	*join_gap)	// to keep each list item string
1316 {
1317     int		i;
1318     join_T	*p;
1319     int		len;
1320     int		sumlen = 0;
1321     int		first = TRUE;
1322     char_u	*tofree;
1323     char_u	numbuf[NUMBUFLEN];
1324     listitem_T	*item;
1325     char_u	*s;
1326 
1327     // Stringify each item in the list.
1328     CHECK_LIST_MATERIALIZE(l);
1329     for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
1330     {
1331 	s = echo_string_core(&item->li_tv, &tofree, numbuf, copyID,
1332 				      echo_style, restore_copyID, !echo_style);
1333 	if (s == NULL)
1334 	    return FAIL;
1335 
1336 	len = (int)STRLEN(s);
1337 	sumlen += len;
1338 
1339 	(void)ga_grow(join_gap, 1);
1340 	p = ((join_T *)join_gap->ga_data) + (join_gap->ga_len++);
1341 	if (tofree != NULL || s != numbuf)
1342 	{
1343 	    p->s = s;
1344 	    p->tofree = tofree;
1345 	}
1346 	else
1347 	{
1348 	    p->s = vim_strnsave(s, len);
1349 	    p->tofree = p->s;
1350 	}
1351 
1352 	line_breakcheck();
1353 	if (did_echo_string_emsg)  // recursion error, bail out
1354 	    break;
1355     }
1356 
1357     // Allocate result buffer with its total size, avoid re-allocation and
1358     // multiple copy operations.  Add 2 for a tailing ']' and NUL.
1359     if (join_gap->ga_len >= 2)
1360 	sumlen += (int)STRLEN(sep) * (join_gap->ga_len - 1);
1361     if (ga_grow(gap, sumlen + 2) == FAIL)
1362 	return FAIL;
1363 
1364     for (i = 0; i < join_gap->ga_len && !got_int; ++i)
1365     {
1366 	if (first)
1367 	    first = FALSE;
1368 	else
1369 	    ga_concat(gap, sep);
1370 	p = ((join_T *)join_gap->ga_data) + i;
1371 
1372 	if (p->s != NULL)
1373 	    ga_concat(gap, p->s);
1374 	line_breakcheck();
1375     }
1376 
1377     return OK;
1378 }
1379 
1380 /*
1381  * Join list "l" into a string in "*gap", using separator "sep".
1382  * When "echo_style" is TRUE use String as echoed, otherwise as inside a List.
1383  * Return FAIL or OK.
1384  */
1385     int
1386 list_join(
1387     garray_T	*gap,
1388     list_T	*l,
1389     char_u	*sep,
1390     int		echo_style,
1391     int		restore_copyID,
1392     int		copyID)
1393 {
1394     garray_T	join_ga;
1395     int		retval;
1396     join_T	*p;
1397     int		i;
1398 
1399     if (l->lv_len < 1)
1400 	return OK; // nothing to do
1401     ga_init2(&join_ga, (int)sizeof(join_T), l->lv_len);
1402     retval = list_join_inner(gap, l, sep, echo_style, restore_copyID,
1403 							    copyID, &join_ga);
1404 
1405     // Dispose each item in join_ga.
1406     if (join_ga.ga_data != NULL)
1407     {
1408 	p = (join_T *)join_ga.ga_data;
1409 	for (i = 0; i < join_ga.ga_len; ++i)
1410 	{
1411 	    vim_free(p->tofree);
1412 	    ++p;
1413 	}
1414 	ga_clear(&join_ga);
1415     }
1416 
1417     return retval;
1418 }
1419 
1420 /*
1421  * "join()" function
1422  */
1423     void
1424 f_join(typval_T *argvars, typval_T *rettv)
1425 {
1426     garray_T	ga;
1427     char_u	*sep;
1428 
1429     if (in_vim9script()
1430 	    && (check_for_list_arg(argvars, 0) == FAIL
1431 		|| check_for_opt_string_arg(argvars, 1) == FAIL))
1432 	return;
1433 
1434     if (argvars[0].v_type != VAR_LIST)
1435     {
1436 	emsg(_(e_listreq));
1437 	return;
1438     }
1439     rettv->v_type = VAR_STRING;
1440     if (argvars[0].vval.v_list == NULL)
1441 	return;
1442 
1443     if (argvars[1].v_type == VAR_UNKNOWN)
1444 	sep = (char_u *)" ";
1445     else
1446 	sep = tv_get_string_chk(&argvars[1]);
1447 
1448     if (sep != NULL)
1449     {
1450 	ga_init2(&ga, (int)sizeof(char), 80);
1451 	list_join(&ga, argvars[0].vval.v_list, sep, TRUE, FALSE, 0);
1452 	ga_append(&ga, NUL);
1453 	rettv->vval.v_string = (char_u *)ga.ga_data;
1454     }
1455     else
1456 	rettv->vval.v_string = NULL;
1457 }
1458 
1459 /*
1460  * Allocate a variable for a List and fill it from "*arg".
1461  * "*arg" points to the "[".
1462  * Return OK or FAIL.
1463  */
1464     int
1465 eval_list(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int do_error)
1466 {
1467     int		evaluate = evalarg == NULL ? FALSE
1468 					 : evalarg->eval_flags & EVAL_EVALUATE;
1469     list_T	*l = NULL;
1470     typval_T	tv;
1471     listitem_T	*item;
1472     int		vim9script = in_vim9script();
1473     int		had_comma;
1474 
1475     if (evaluate)
1476     {
1477 	l = list_alloc();
1478 	if (l == NULL)
1479 	    return FAIL;
1480     }
1481 
1482     *arg = skipwhite_and_linebreak(*arg + 1, evalarg);
1483     while (**arg != ']' && **arg != NUL)
1484     {
1485 	if (eval1(arg, &tv, evalarg) == FAIL)	// recursive!
1486 	    goto failret;
1487 	if (evaluate)
1488 	{
1489 	    item = listitem_alloc();
1490 	    if (item != NULL)
1491 	    {
1492 		item->li_tv = tv;
1493 		item->li_tv.v_lock = 0;
1494 		list_append(l, item);
1495 	    }
1496 	    else
1497 		clear_tv(&tv);
1498 	}
1499 	// Legacy Vim script allowed a space before the comma.
1500 	if (!vim9script)
1501 	    *arg = skipwhite(*arg);
1502 
1503 	// the comma must come after the value
1504 	had_comma = **arg == ',';
1505 	if (had_comma)
1506 	{
1507 	    if (vim9script && !IS_WHITE_OR_NUL((*arg)[1]) && (*arg)[1] != ']')
1508 	    {
1509 		semsg(_(e_white_space_required_after_str_str), ",", *arg);
1510 		goto failret;
1511 	    }
1512 	    *arg = skipwhite(*arg + 1);
1513 	}
1514 
1515 	// The "]" can be on the next line.  But a double quoted string may
1516 	// follow, not a comment.
1517 	*arg = skipwhite_and_linebreak(*arg, evalarg);
1518 	if (**arg == ']')
1519 	    break;
1520 
1521 	if (!had_comma)
1522 	{
1523 	    if (do_error)
1524 	    {
1525 		if (**arg == ',')
1526 		    semsg(_(e_no_white_space_allowed_before_str_str),
1527 								    ",", *arg);
1528 		else
1529 		    semsg(_("E696: Missing comma in List: %s"), *arg);
1530 	    }
1531 	    goto failret;
1532 	}
1533     }
1534 
1535     if (**arg != ']')
1536     {
1537 	if (do_error)
1538 	    semsg(_(e_list_end), *arg);
1539 failret:
1540 	if (evaluate)
1541 	    list_free(l);
1542 	return FAIL;
1543     }
1544 
1545     *arg += 1;
1546     if (evaluate)
1547 	rettv_list_set(rettv, l);
1548 
1549     return OK;
1550 }
1551 
1552 /*
1553  * Write "list" of strings to file "fd".
1554  */
1555     int
1556 write_list(FILE *fd, list_T *list, int binary)
1557 {
1558     listitem_T	*li;
1559     int		c;
1560     int		ret = OK;
1561     char_u	*s;
1562 
1563     CHECK_LIST_MATERIALIZE(list);
1564     FOR_ALL_LIST_ITEMS(list, li)
1565     {
1566 	for (s = tv_get_string(&li->li_tv); *s != NUL; ++s)
1567 	{
1568 	    if (*s == '\n')
1569 		c = putc(NUL, fd);
1570 	    else
1571 		c = putc(*s, fd);
1572 	    if (c == EOF)
1573 	    {
1574 		ret = FAIL;
1575 		break;
1576 	    }
1577 	}
1578 	if (!binary || li->li_next != NULL)
1579 	    if (putc('\n', fd) == EOF)
1580 	    {
1581 		ret = FAIL;
1582 		break;
1583 	    }
1584 	if (ret == FAIL)
1585 	{
1586 	    emsg(_(e_write));
1587 	    break;
1588 	}
1589     }
1590     return ret;
1591 }
1592 
1593 /*
1594  * Initialize a static list with 10 items.
1595  */
1596     void
1597 init_static_list(staticList10_T *sl)
1598 {
1599     list_T  *l = &sl->sl_list;
1600     int	    i;
1601 
1602     memset(sl, 0, sizeof(staticList10_T));
1603     l->lv_first = &sl->sl_items[0];
1604     l->lv_u.mat.lv_last = &sl->sl_items[9];
1605     l->lv_refcount = DO_NOT_FREE_CNT;
1606     l->lv_lock = VAR_FIXED;
1607     sl->sl_list.lv_len = 10;
1608 
1609     for (i = 0; i < 10; ++i)
1610     {
1611 	listitem_T *li = &sl->sl_items[i];
1612 
1613 	if (i == 0)
1614 	    li->li_prev = NULL;
1615 	else
1616 	    li->li_prev = li - 1;
1617 	if (i == 9)
1618 	    li->li_next = NULL;
1619 	else
1620 	    li->li_next = li + 1;
1621     }
1622 }
1623 
1624 /*
1625  * "list2str()" function
1626  */
1627     void
1628 f_list2str(typval_T *argvars, typval_T *rettv)
1629 {
1630     list_T	*l;
1631     listitem_T	*li;
1632     garray_T	ga;
1633     int		utf8 = FALSE;
1634 
1635     rettv->v_type = VAR_STRING;
1636     rettv->vval.v_string = NULL;
1637 
1638     if (in_vim9script()
1639 	    && (check_for_list_arg(argvars, 0) == FAIL
1640 		|| check_for_opt_bool_arg(argvars, 1) == FAIL))
1641 	return;
1642 
1643     if (argvars[0].v_type != VAR_LIST)
1644     {
1645 	emsg(_(e_invarg));
1646 	return;
1647     }
1648 
1649     l = argvars[0].vval.v_list;
1650     if (l == NULL)
1651 	return;  // empty list results in empty string
1652 
1653     if (argvars[1].v_type != VAR_UNKNOWN)
1654 	utf8 = (int)tv_get_bool_chk(&argvars[1], NULL);
1655 
1656     CHECK_LIST_MATERIALIZE(l);
1657     ga_init2(&ga, 1, 80);
1658     if (has_mbyte || utf8)
1659     {
1660 	char_u	buf[MB_MAXBYTES + 1];
1661 	int	(*char2bytes)(int, char_u *);
1662 
1663 	if (utf8 || enc_utf8)
1664 	    char2bytes = utf_char2bytes;
1665 	else
1666 	    char2bytes = mb_char2bytes;
1667 
1668 	FOR_ALL_LIST_ITEMS(l, li)
1669 	{
1670 	    buf[(*char2bytes)(tv_get_number(&li->li_tv), buf)] = NUL;
1671 	    ga_concat(&ga, buf);
1672 	}
1673 	ga_append(&ga, NUL);
1674     }
1675     else if (ga_grow(&ga, list_len(l) + 1) == OK)
1676     {
1677 	FOR_ALL_LIST_ITEMS(l, li)
1678 	    ga_append(&ga, tv_get_number(&li->li_tv));
1679 	ga_append(&ga, NUL);
1680     }
1681 
1682     rettv->v_type = VAR_STRING;
1683     rettv->vval.v_string = ga.ga_data;
1684 }
1685 
1686     static void
1687 list_remove(typval_T *argvars, typval_T *rettv, char_u *arg_errmsg)
1688 {
1689     list_T	*l;
1690     listitem_T	*item, *item2;
1691     listitem_T	*li;
1692     int		error = FALSE;
1693     long	idx;
1694 
1695     if ((l = argvars[0].vval.v_list) == NULL
1696 			     || value_check_lock(l->lv_lock, arg_errmsg, TRUE))
1697 	return;
1698 
1699     idx = (long)tv_get_number_chk(&argvars[1], &error);
1700     if (error)
1701 	;		// type error: do nothing, errmsg already given
1702     else if ((item = list_find(l, idx)) == NULL)
1703 	semsg(_(e_listidx), idx);
1704     else
1705     {
1706 	if (argvars[2].v_type == VAR_UNKNOWN)
1707 	{
1708 	    // Remove one item, return its value.
1709 	    vimlist_remove(l, item, item);
1710 	    *rettv = item->li_tv;
1711 	    list_free_item(l, item);
1712 	}
1713 	else
1714 	{
1715 	    // Remove range of items, return list with values.
1716 	    long end = (long)tv_get_number_chk(&argvars[2], &error);
1717 
1718 	    if (error)
1719 		;		// type error: do nothing
1720 	    else if ((item2 = list_find(l, end)) == NULL)
1721 		semsg(_(e_listidx), end);
1722 	    else
1723 	    {
1724 		int	    cnt = 0;
1725 
1726 		for (li = item; li != NULL; li = li->li_next)
1727 		{
1728 		    ++cnt;
1729 		    if (li == item2)
1730 			break;
1731 		}
1732 		if (li == NULL)  // didn't find "item2" after "item"
1733 		    emsg(_(e_invalid_range));
1734 		else
1735 		{
1736 		    vimlist_remove(l, item, item2);
1737 		    if (rettv_list_alloc(rettv) == OK)
1738 		    {
1739 			list_T *rl = rettv->vval.v_list;
1740 
1741 			if (l->lv_with_items > 0)
1742 			{
1743 			    // need to copy the list items and move the value
1744 			    while (item != NULL)
1745 			    {
1746 				li = listitem_alloc();
1747 				if (li == NULL)
1748 				    return;
1749 				li->li_tv = item->li_tv;
1750 				init_tv(&item->li_tv);
1751 				list_append(rl, li);
1752 				if (item == item2)
1753 				    break;
1754 				item = item->li_next;
1755 			    }
1756 			}
1757 			else
1758 			{
1759 			    rl->lv_first = item;
1760 			    rl->lv_u.mat.lv_last = item2;
1761 			    item->li_prev = NULL;
1762 			    item2->li_next = NULL;
1763 			    rl->lv_len = cnt;
1764 			}
1765 		    }
1766 		}
1767 	    }
1768 	}
1769     }
1770 }
1771 
1772 static int item_compare(const void *s1, const void *s2);
1773 static int item_compare2(const void *s1, const void *s2);
1774 
1775 // struct used in the array that's given to qsort()
1776 typedef struct
1777 {
1778     listitem_T	*item;
1779     int		idx;
1780 } sortItem_T;
1781 
1782 // struct storing information about current sort
1783 typedef struct
1784 {
1785     int		item_compare_ic;
1786     int		item_compare_lc;
1787     int		item_compare_numeric;
1788     int		item_compare_numbers;
1789 #ifdef FEAT_FLOAT
1790     int		item_compare_float;
1791 #endif
1792     char_u	*item_compare_func;
1793     partial_T	*item_compare_partial;
1794     dict_T	*item_compare_selfdict;
1795     int		item_compare_func_err;
1796     int		item_compare_keep_zero;
1797 } sortinfo_T;
1798 static sortinfo_T	*sortinfo = NULL;
1799 #define ITEM_COMPARE_FAIL 999
1800 
1801 /*
1802  * Compare functions for f_sort() and f_uniq() below.
1803  */
1804     static int
1805 item_compare(const void *s1, const void *s2)
1806 {
1807     sortItem_T  *si1, *si2;
1808     typval_T	*tv1, *tv2;
1809     char_u	*p1, *p2;
1810     char_u	*tofree1 = NULL, *tofree2 = NULL;
1811     int		res;
1812     char_u	numbuf1[NUMBUFLEN];
1813     char_u	numbuf2[NUMBUFLEN];
1814 
1815     si1 = (sortItem_T *)s1;
1816     si2 = (sortItem_T *)s2;
1817     tv1 = &si1->item->li_tv;
1818     tv2 = &si2->item->li_tv;
1819 
1820     if (sortinfo->item_compare_numbers)
1821     {
1822 	varnumber_T	v1 = tv_get_number(tv1);
1823 	varnumber_T	v2 = tv_get_number(tv2);
1824 
1825 	return v1 == v2 ? 0 : v1 > v2 ? 1 : -1;
1826     }
1827 
1828 #ifdef FEAT_FLOAT
1829     if (sortinfo->item_compare_float)
1830     {
1831 	float_T	v1 = tv_get_float(tv1);
1832 	float_T	v2 = tv_get_float(tv2);
1833 
1834 	return v1 == v2 ? 0 : v1 > v2 ? 1 : -1;
1835     }
1836 #endif
1837 
1838     // tv2string() puts quotes around a string and allocates memory.  Don't do
1839     // that for string variables. Use a single quote when comparing with a
1840     // non-string to do what the docs promise.
1841     if (tv1->v_type == VAR_STRING)
1842     {
1843 	if (tv2->v_type != VAR_STRING || sortinfo->item_compare_numeric)
1844 	    p1 = (char_u *)"'";
1845 	else
1846 	    p1 = tv1->vval.v_string;
1847     }
1848     else
1849 	p1 = tv2string(tv1, &tofree1, numbuf1, 0);
1850     if (tv2->v_type == VAR_STRING)
1851     {
1852 	if (tv1->v_type != VAR_STRING || sortinfo->item_compare_numeric)
1853 	    p2 = (char_u *)"'";
1854 	else
1855 	    p2 = tv2->vval.v_string;
1856     }
1857     else
1858 	p2 = tv2string(tv2, &tofree2, numbuf2, 0);
1859     if (p1 == NULL)
1860 	p1 = (char_u *)"";
1861     if (p2 == NULL)
1862 	p2 = (char_u *)"";
1863     if (!sortinfo->item_compare_numeric)
1864     {
1865 	if (sortinfo->item_compare_lc)
1866 	    res = strcoll((char *)p1, (char *)p2);
1867 	else
1868 	    res = sortinfo->item_compare_ic ? STRICMP(p1, p2): STRCMP(p1, p2);
1869     }
1870     else
1871     {
1872 	double n1, n2;
1873 	n1 = strtod((char *)p1, (char **)&p1);
1874 	n2 = strtod((char *)p2, (char **)&p2);
1875 	res = n1 == n2 ? 0 : n1 > n2 ? 1 : -1;
1876     }
1877 
1878     // When the result would be zero, compare the item indexes.  Makes the
1879     // sort stable.
1880     if (res == 0 && !sortinfo->item_compare_keep_zero)
1881 	res = si1->idx > si2->idx ? 1 : -1;
1882 
1883     vim_free(tofree1);
1884     vim_free(tofree2);
1885     return res;
1886 }
1887 
1888     static int
1889 item_compare2(const void *s1, const void *s2)
1890 {
1891     sortItem_T  *si1, *si2;
1892     int		res;
1893     typval_T	rettv;
1894     typval_T	argv[3];
1895     char_u	*func_name;
1896     partial_T	*partial = sortinfo->item_compare_partial;
1897     funcexe_T	funcexe;
1898 
1899     // shortcut after failure in previous call; compare all items equal
1900     if (sortinfo->item_compare_func_err)
1901 	return 0;
1902 
1903     si1 = (sortItem_T *)s1;
1904     si2 = (sortItem_T *)s2;
1905 
1906     if (partial == NULL)
1907 	func_name = sortinfo->item_compare_func;
1908     else
1909 	func_name = partial_name(partial);
1910 
1911     // Copy the values.  This is needed to be able to set v_lock to VAR_FIXED
1912     // in the copy without changing the original list items.
1913     copy_tv(&si1->item->li_tv, &argv[0]);
1914     copy_tv(&si2->item->li_tv, &argv[1]);
1915 
1916     rettv.v_type = VAR_UNKNOWN;		// clear_tv() uses this
1917     CLEAR_FIELD(funcexe);
1918     funcexe.evaluate = TRUE;
1919     funcexe.partial = partial;
1920     funcexe.selfdict = sortinfo->item_compare_selfdict;
1921     res = call_func(func_name, -1, &rettv, 2, argv, &funcexe);
1922     clear_tv(&argv[0]);
1923     clear_tv(&argv[1]);
1924 
1925     if (res == FAIL)
1926 	res = ITEM_COMPARE_FAIL;
1927     else
1928 	res = (int)tv_get_number_chk(&rettv, &sortinfo->item_compare_func_err);
1929     if (sortinfo->item_compare_func_err)
1930 	res = ITEM_COMPARE_FAIL;  // return value has wrong type
1931     clear_tv(&rettv);
1932 
1933     // When the result would be zero, compare the pointers themselves.  Makes
1934     // the sort stable.
1935     if (res == 0 && !sortinfo->item_compare_keep_zero)
1936 	res = si1->idx > si2->idx ? 1 : -1;
1937 
1938     return res;
1939 }
1940 
1941 /*
1942  * "sort()" or "uniq()" function
1943  */
1944     static void
1945 do_sort_uniq(typval_T *argvars, typval_T *rettv, int sort)
1946 {
1947     list_T	*l;
1948     listitem_T	*li;
1949     sortItem_T	*ptrs;
1950     sortinfo_T	*old_sortinfo;
1951     sortinfo_T	info;
1952     long	len;
1953     long	i;
1954 
1955     if (in_vim9script()
1956 	    && (check_for_list_arg(argvars, 0) == FAIL
1957 		|| (argvars[1].v_type != VAR_UNKNOWN
1958 		    && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1959 	return;
1960 
1961     // Pointer to current info struct used in compare function. Save and
1962     // restore the current one for nested calls.
1963     old_sortinfo = sortinfo;
1964     sortinfo = &info;
1965 
1966     if (argvars[0].v_type != VAR_LIST)
1967 	semsg(_(e_listarg), sort ? "sort()" : "uniq()");
1968     else
1969     {
1970 	l = argvars[0].vval.v_list;
1971 	if (l != NULL && value_check_lock(l->lv_lock,
1972 	     (char_u *)(sort ? N_("sort() argument") : N_("uniq() argument")),
1973 									TRUE))
1974 	    goto theend;
1975 	rettv_list_set(rettv, l);
1976 	if (l == NULL)
1977 	    goto theend;
1978 	CHECK_LIST_MATERIALIZE(l);
1979 
1980 	len = list_len(l);
1981 	if (len <= 1)
1982 	    goto theend;	// short list sorts pretty quickly
1983 
1984 	info.item_compare_ic = FALSE;
1985 	info.item_compare_lc = FALSE;
1986 	info.item_compare_numeric = FALSE;
1987 	info.item_compare_numbers = FALSE;
1988 #ifdef FEAT_FLOAT
1989 	info.item_compare_float = FALSE;
1990 #endif
1991 	info.item_compare_func = NULL;
1992 	info.item_compare_partial = NULL;
1993 	info.item_compare_selfdict = NULL;
1994 	if (argvars[1].v_type != VAR_UNKNOWN)
1995 	{
1996 	    // optional second argument: {func}
1997 	    if (argvars[1].v_type == VAR_FUNC)
1998 		info.item_compare_func = argvars[1].vval.v_string;
1999 	    else if (argvars[1].v_type == VAR_PARTIAL)
2000 		info.item_compare_partial = argvars[1].vval.v_partial;
2001 	    else
2002 	    {
2003 		int	    error = FALSE;
2004 		int	    nr = 0;
2005 
2006 		if (argvars[1].v_type == VAR_NUMBER)
2007 		{
2008 		    nr = tv_get_number_chk(&argvars[1], &error);
2009 		    if (error)
2010 			goto theend;	// type error; errmsg already given
2011 		    if (nr == 1)
2012 			info.item_compare_ic = TRUE;
2013 		}
2014 		if (nr != 1)
2015 		{
2016 		    if (argvars[1].v_type != VAR_NUMBER)
2017 			info.item_compare_func = tv_get_string(&argvars[1]);
2018 		    else if (nr != 0)
2019 		    {
2020 			emsg(_(e_invarg));
2021 			goto theend;
2022 		    }
2023 		}
2024 		if (info.item_compare_func != NULL)
2025 		{
2026 		    if (*info.item_compare_func == NUL)
2027 		    {
2028 			// empty string means default sort
2029 			info.item_compare_func = NULL;
2030 		    }
2031 		    else if (STRCMP(info.item_compare_func, "n") == 0)
2032 		    {
2033 			info.item_compare_func = NULL;
2034 			info.item_compare_numeric = TRUE;
2035 		    }
2036 		    else if (STRCMP(info.item_compare_func, "N") == 0)
2037 		    {
2038 			info.item_compare_func = NULL;
2039 			info.item_compare_numbers = TRUE;
2040 		    }
2041 #ifdef FEAT_FLOAT
2042 		    else if (STRCMP(info.item_compare_func, "f") == 0)
2043 		    {
2044 			info.item_compare_func = NULL;
2045 			info.item_compare_float = TRUE;
2046 		    }
2047 #endif
2048 		    else if (STRCMP(info.item_compare_func, "i") == 0)
2049 		    {
2050 			info.item_compare_func = NULL;
2051 			info.item_compare_ic = TRUE;
2052 		    }
2053 		    else if (STRCMP(info.item_compare_func, "l") == 0)
2054 		    {
2055 			info.item_compare_func = NULL;
2056 			info.item_compare_lc = TRUE;
2057 		    }
2058 		}
2059 	    }
2060 
2061 	    if (argvars[2].v_type != VAR_UNKNOWN)
2062 	    {
2063 		// optional third argument: {dict}
2064 		if (argvars[2].v_type != VAR_DICT)
2065 		{
2066 		    emsg(_(e_dictreq));
2067 		    goto theend;
2068 		}
2069 		info.item_compare_selfdict = argvars[2].vval.v_dict;
2070 	    }
2071 	}
2072 
2073 	// Make an array with each entry pointing to an item in the List.
2074 	ptrs = ALLOC_MULT(sortItem_T, len);
2075 	if (ptrs == NULL)
2076 	    goto theend;
2077 
2078 	i = 0;
2079 	if (sort)
2080 	{
2081 	    // sort(): ptrs will be the list to sort
2082 	    FOR_ALL_LIST_ITEMS(l, li)
2083 	    {
2084 		ptrs[i].item = li;
2085 		ptrs[i].idx = i;
2086 		++i;
2087 	    }
2088 
2089 	    info.item_compare_func_err = FALSE;
2090 	    info.item_compare_keep_zero = FALSE;
2091 	    // test the compare function
2092 	    if ((info.item_compare_func != NULL
2093 					 || info.item_compare_partial != NULL)
2094 		    && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
2095 							 == ITEM_COMPARE_FAIL)
2096 		emsg(_("E702: Sort compare function failed"));
2097 	    else
2098 	    {
2099 		// Sort the array with item pointers.
2100 		qsort((void *)ptrs, (size_t)len, sizeof(sortItem_T),
2101 		    info.item_compare_func == NULL
2102 					  && info.item_compare_partial == NULL
2103 					       ? item_compare : item_compare2);
2104 
2105 		if (!info.item_compare_func_err)
2106 		{
2107 		    // Clear the List and append the items in sorted order.
2108 		    l->lv_first = l->lv_u.mat.lv_last
2109 					      = l->lv_u.mat.lv_idx_item = NULL;
2110 		    l->lv_len = 0;
2111 		    for (i = 0; i < len; ++i)
2112 			list_append(l, ptrs[i].item);
2113 		}
2114 	    }
2115 	}
2116 	else
2117 	{
2118 	    int	(*item_compare_func_ptr)(const void *, const void *);
2119 
2120 	    // f_uniq(): ptrs will be a stack of items to remove
2121 	    info.item_compare_func_err = FALSE;
2122 	    info.item_compare_keep_zero = TRUE;
2123 	    item_compare_func_ptr = info.item_compare_func != NULL
2124 					  || info.item_compare_partial != NULL
2125 					       ? item_compare2 : item_compare;
2126 
2127 	    for (li = l->lv_first; li != NULL && li->li_next != NULL;
2128 							     li = li->li_next)
2129 	    {
2130 		if (item_compare_func_ptr((void *)&li, (void *)&li->li_next)
2131 									 == 0)
2132 		    ptrs[i++].item = li;
2133 		if (info.item_compare_func_err)
2134 		{
2135 		    emsg(_("E882: Uniq compare function failed"));
2136 		    break;
2137 		}
2138 	    }
2139 
2140 	    if (!info.item_compare_func_err)
2141 	    {
2142 		while (--i >= 0)
2143 		{
2144 		    li = ptrs[i].item->li_next;
2145 		    ptrs[i].item->li_next = li->li_next;
2146 		    if (li->li_next != NULL)
2147 			li->li_next->li_prev = ptrs[i].item;
2148 		    else
2149 			l->lv_u.mat.lv_last = ptrs[i].item;
2150 		    list_fix_watch(l, li);
2151 		    listitem_free(l, li);
2152 		    l->lv_len--;
2153 		}
2154 	    }
2155 	}
2156 
2157 	vim_free(ptrs);
2158     }
2159 theend:
2160     sortinfo = old_sortinfo;
2161 }
2162 
2163 /*
2164  * "sort({list})" function
2165  */
2166     void
2167 f_sort(typval_T *argvars, typval_T *rettv)
2168 {
2169     do_sort_uniq(argvars, rettv, TRUE);
2170 }
2171 
2172 /*
2173  * "uniq({list})" function
2174  */
2175     void
2176 f_uniq(typval_T *argvars, typval_T *rettv)
2177 {
2178     do_sort_uniq(argvars, rettv, FALSE);
2179 }
2180 
2181 typedef enum {
2182     FILTERMAP_FILTER,
2183     FILTERMAP_MAP,
2184     FILTERMAP_MAPNEW
2185 } filtermap_T;
2186 
2187 /*
2188  * Handle one item for map() and filter().
2189  * Sets v:val to "tv".  Caller must set v:key.
2190  */
2191     static int
2192 filter_map_one(
2193 	typval_T	*tv,	    // original value
2194 	typval_T	*expr,	    // callback
2195 	filtermap_T	filtermap,
2196 	typval_T	*newtv,	    // for map() and mapnew(): new value
2197 	int		*remp)	    // for filter(): remove flag
2198 {
2199     typval_T	argv[3];
2200     int		retval = FAIL;
2201 
2202     copy_tv(tv, get_vim_var_tv(VV_VAL));
2203     argv[0] = *get_vim_var_tv(VV_KEY);
2204     argv[1] = *get_vim_var_tv(VV_VAL);
2205     if (eval_expr_typval(expr, argv, 2, newtv) == FAIL)
2206 	goto theend;
2207     if (filtermap == FILTERMAP_FILTER)
2208     {
2209 	int	    error = FALSE;
2210 
2211 	// filter(): when expr is zero remove the item
2212 	if (in_vim9script())
2213 	    *remp = !tv2bool(newtv);
2214 	else
2215 	    *remp = (tv_get_number_chk(newtv, &error) == 0);
2216 	clear_tv(newtv);
2217 	// On type error, nothing has been removed; return FAIL to stop the
2218 	// loop.  The error message was given by tv_get_number_chk().
2219 	if (error)
2220 	    goto theend;
2221     }
2222     retval = OK;
2223 theend:
2224     clear_tv(get_vim_var_tv(VV_VAL));
2225     return retval;
2226 }
2227 
2228 /*
2229  * Implementation of map() and filter().
2230  */
2231     static void
2232 filter_map(typval_T *argvars, typval_T *rettv, filtermap_T filtermap)
2233 {
2234     typval_T	*expr;
2235     listitem_T	*li, *nli;
2236     list_T	*l = NULL;
2237     dictitem_T	*di;
2238     hashtab_T	*ht;
2239     hashitem_T	*hi;
2240     dict_T	*d = NULL;
2241     blob_T	*b = NULL;
2242     int		rem;
2243     int		todo;
2244     char	*func_name = filtermap == FILTERMAP_MAP ? "map()"
2245 				  : filtermap == FILTERMAP_MAPNEW ? "mapnew()"
2246 				  : "filter()";
2247     char_u	*arg_errmsg = (char_u *)(filtermap == FILTERMAP_MAP
2248 							 ? N_("map() argument")
2249 				       : filtermap == FILTERMAP_MAPNEW
2250 						      ? N_("mapnew() argument")
2251 						    : N_("filter() argument"));
2252     int		save_did_emsg;
2253     int		idx = 0;
2254     type_T	*type = NULL;
2255     garray_T	type_list;
2256 
2257     // map() and filter() return the first argument, also on failure.
2258     if (filtermap != FILTERMAP_MAPNEW)
2259 	copy_tv(&argvars[0], rettv);
2260 
2261     if (in_vim9script()
2262 	    && (check_for_list_or_dict_or_blob_arg(argvars, 0) == FAIL))
2263 	return;
2264 
2265     if (filtermap == FILTERMAP_MAP && in_vim9script())
2266     {
2267 	// Check that map() does not change the type of the dict.
2268 	ga_init2(&type_list, sizeof(type_T *), 10);
2269 	type = typval2type(argvars, get_copyID(), &type_list, TRUE);
2270     }
2271 
2272     if (argvars[0].v_type == VAR_BLOB)
2273     {
2274 	if (filtermap == FILTERMAP_MAPNEW)
2275 	{
2276 	    rettv->v_type = VAR_BLOB;
2277 	    rettv->vval.v_blob = NULL;
2278 	}
2279 	if ((b = argvars[0].vval.v_blob) == NULL)
2280 	    goto theend;
2281     }
2282     else if (argvars[0].v_type == VAR_LIST)
2283     {
2284 	if (filtermap == FILTERMAP_MAPNEW)
2285 	{
2286 	    rettv->v_type = VAR_LIST;
2287 	    rettv->vval.v_list = NULL;
2288 	}
2289 	if ((l = argvars[0].vval.v_list) == NULL
2290 	      || (filtermap == FILTERMAP_FILTER
2291 			    && value_check_lock(l->lv_lock, arg_errmsg, TRUE)))
2292 	    goto theend;
2293     }
2294     else if (argvars[0].v_type == VAR_DICT)
2295     {
2296 	if (filtermap == FILTERMAP_MAPNEW)
2297 	{
2298 	    rettv->v_type = VAR_DICT;
2299 	    rettv->vval.v_dict = NULL;
2300 	}
2301 	if ((d = argvars[0].vval.v_dict) == NULL
2302 	      || (filtermap == FILTERMAP_FILTER
2303 			    && value_check_lock(d->dv_lock, arg_errmsg, TRUE)))
2304 	    goto theend;
2305     }
2306     else
2307     {
2308 	semsg(_(e_listdictblobarg), func_name);
2309 	goto theend;
2310     }
2311 
2312     expr = &argvars[1];
2313     // On type errors, the preceding call has already displayed an error
2314     // message.  Avoid a misleading error message for an empty string that
2315     // was not passed as argument.
2316     if (expr->v_type != VAR_UNKNOWN)
2317     {
2318 	typval_T	save_val;
2319 	typval_T	save_key;
2320 
2321 	prepare_vimvar(VV_VAL, &save_val);
2322 	prepare_vimvar(VV_KEY, &save_key);
2323 
2324 	// We reset "did_emsg" to be able to detect whether an error
2325 	// occurred during evaluation of the expression.
2326 	save_did_emsg = did_emsg;
2327 	did_emsg = FALSE;
2328 
2329 	if (argvars[0].v_type == VAR_DICT)
2330 	{
2331 	    int	    prev_lock = d->dv_lock;
2332 	    dict_T  *d_ret = NULL;
2333 
2334 	    if (filtermap == FILTERMAP_MAPNEW)
2335 	    {
2336 		if (rettv_dict_alloc(rettv) == FAIL)
2337 		    goto theend;
2338 		d_ret = rettv->vval.v_dict;
2339 	    }
2340 
2341 	    if (filtermap != FILTERMAP_FILTER && d->dv_lock == 0)
2342 		d->dv_lock = VAR_LOCKED;
2343 	    ht = &d->dv_hashtab;
2344 	    hash_lock(ht);
2345 	    todo = (int)ht->ht_used;
2346 	    for (hi = ht->ht_array; todo > 0; ++hi)
2347 	    {
2348 		if (!HASHITEM_EMPTY(hi))
2349 		{
2350 		    int		r;
2351 		    typval_T	newtv;
2352 
2353 		    --todo;
2354 		    di = HI2DI(hi);
2355 		    if (filtermap == FILTERMAP_MAP
2356 					 && (value_check_lock(di->di_tv.v_lock,
2357 							   arg_errmsg, TRUE)
2358 				|| var_check_ro(di->di_flags,
2359 							   arg_errmsg, TRUE)))
2360 			break;
2361 		    set_vim_var_string(VV_KEY, di->di_key, -1);
2362 		    newtv.v_type = VAR_UNKNOWN;
2363 		    r = filter_map_one(&di->di_tv, expr, filtermap,
2364 								 &newtv, &rem);
2365 		    clear_tv(get_vim_var_tv(VV_KEY));
2366 		    if (r == FAIL || did_emsg)
2367 		    {
2368 			clear_tv(&newtv);
2369 			break;
2370 		    }
2371 		    if (filtermap == FILTERMAP_MAP)
2372 		    {
2373 			if (type != NULL && check_typval_arg_type(
2374 				     type->tt_member, &newtv,
2375 							 func_name, 0) == FAIL)
2376 			{
2377 			    clear_tv(&newtv);
2378 			    break;
2379 			}
2380 			// map(): replace the dict item value
2381 			clear_tv(&di->di_tv);
2382 			newtv.v_lock = 0;
2383 			di->di_tv = newtv;
2384 		    }
2385 		    else if (filtermap == FILTERMAP_MAPNEW)
2386 		    {
2387 			// mapnew(): add the item value to the new dict
2388 			r = dict_add_tv(d_ret, (char *)di->di_key, &newtv);
2389 			clear_tv(&newtv);
2390 			if (r == FAIL)
2391 			    break;
2392 		    }
2393 		    else if (filtermap == FILTERMAP_FILTER && rem)
2394 		    {
2395 			// filter(false): remove the item from the dict
2396 			if (var_check_fixed(di->di_flags, arg_errmsg, TRUE)
2397 			    || var_check_ro(di->di_flags, arg_errmsg, TRUE))
2398 			    break;
2399 			dictitem_remove(d, di);
2400 		    }
2401 		}
2402 	    }
2403 	    hash_unlock(ht);
2404 	    d->dv_lock = prev_lock;
2405 	}
2406 	else if (argvars[0].v_type == VAR_BLOB)
2407 	{
2408 	    int		i;
2409 	    typval_T	tv;
2410 	    varnumber_T	val;
2411 	    blob_T	*b_ret = b;
2412 
2413 	    if (filtermap == FILTERMAP_MAPNEW)
2414 	    {
2415 		if (blob_copy(b, rettv) == FAIL)
2416 		    goto theend;
2417 		b_ret = rettv->vval.v_blob;
2418 	    }
2419 
2420 	    // set_vim_var_nr() doesn't set the type
2421 	    set_vim_var_type(VV_KEY, VAR_NUMBER);
2422 
2423 	    for (i = 0; i < b->bv_ga.ga_len; i++)
2424 	    {
2425 		typval_T newtv;
2426 
2427 		tv.v_type = VAR_NUMBER;
2428 		val = blob_get(b, i);
2429 		tv.vval.v_number = val;
2430 		set_vim_var_nr(VV_KEY, idx);
2431 		if (filter_map_one(&tv, expr, filtermap, &newtv, &rem) == FAIL
2432 								   || did_emsg)
2433 		    break;
2434 		if (newtv.v_type != VAR_NUMBER && newtv.v_type != VAR_BOOL)
2435 		{
2436 		    clear_tv(&newtv);
2437 		    emsg(_(e_invalblob));
2438 		    break;
2439 		}
2440 		if (filtermap != FILTERMAP_FILTER)
2441 		{
2442 		    if (newtv.vval.v_number != val)
2443 			blob_set(b_ret, i, newtv.vval.v_number);
2444 		}
2445 		else if (rem)
2446 		{
2447 		    char_u *p = (char_u *)argvars[0].vval.v_blob->bv_ga.ga_data;
2448 
2449 		    mch_memmove(p + i, p + i + 1,
2450 					      (size_t)b->bv_ga.ga_len - i - 1);
2451 		    --b->bv_ga.ga_len;
2452 		    --i;
2453 		}
2454 		++idx;
2455 	    }
2456 	}
2457 	else // argvars[0].v_type == VAR_LIST
2458 	{
2459 	    int	    prev_lock = l->lv_lock;
2460 	    list_T  *l_ret = NULL;
2461 
2462 	    if (filtermap == FILTERMAP_MAPNEW)
2463 	    {
2464 		if (rettv_list_alloc(rettv) == FAIL)
2465 		    goto theend;
2466 		l_ret = rettv->vval.v_list;
2467 	    }
2468 	    // set_vim_var_nr() doesn't set the type
2469 	    set_vim_var_type(VV_KEY, VAR_NUMBER);
2470 
2471 	    if (filtermap != FILTERMAP_FILTER && l->lv_lock == 0)
2472 		l->lv_lock = VAR_LOCKED;
2473 
2474 	    if (l->lv_first == &range_list_item)
2475 	    {
2476 		varnumber_T	val = l->lv_u.nonmat.lv_start;
2477 		int		len = l->lv_len;
2478 		int		stride = l->lv_u.nonmat.lv_stride;
2479 
2480 		// List from range(): loop over the numbers
2481 		if (filtermap != FILTERMAP_MAPNEW)
2482 		{
2483 		    l->lv_first = NULL;
2484 		    l->lv_u.mat.lv_last = NULL;
2485 		    l->lv_len = 0;
2486 		    l->lv_u.mat.lv_idx_item = NULL;
2487 		}
2488 
2489 		for (idx = 0; idx < len; ++idx)
2490 		{
2491 		    typval_T tv;
2492 		    typval_T newtv;
2493 
2494 		    tv.v_type = VAR_NUMBER;
2495 		    tv.v_lock = 0;
2496 		    tv.vval.v_number = val;
2497 		    set_vim_var_nr(VV_KEY, idx);
2498 		    if (filter_map_one(&tv, expr, filtermap, &newtv, &rem)
2499 								       == FAIL)
2500 			break;
2501 		    if (did_emsg)
2502 		    {
2503 			clear_tv(&newtv);
2504 			break;
2505 		    }
2506 		    if (filtermap != FILTERMAP_FILTER)
2507 		    {
2508 			if (filtermap == FILTERMAP_MAP && type != NULL
2509 				      && check_typval_arg_type(
2510 				     type->tt_member, &newtv,
2511 							 func_name, 0) == FAIL)
2512 			{
2513 			    clear_tv(&newtv);
2514 			    break;
2515 			}
2516 			// map(), mapnew(): always append the new value to the
2517 			// list
2518 			if (list_append_tv_move(filtermap == FILTERMAP_MAP
2519 						  ? l : l_ret, &newtv) == FAIL)
2520 			    break;
2521 		    }
2522 		    else if (!rem)
2523 		    {
2524 			// filter(): append the list item value when not rem
2525 			if (list_append_tv_move(l, &tv) == FAIL)
2526 			    break;
2527 		    }
2528 
2529 		    val += stride;
2530 		}
2531 	    }
2532 	    else
2533 	    {
2534 		// Materialized list: loop over the items
2535 		for (li = l->lv_first; li != NULL; li = nli)
2536 		{
2537 		    typval_T newtv;
2538 
2539 		    if (filtermap == FILTERMAP_MAP && value_check_lock(
2540 					   li->li_tv.v_lock, arg_errmsg, TRUE))
2541 			break;
2542 		    nli = li->li_next;
2543 		    set_vim_var_nr(VV_KEY, idx);
2544 		    if (filter_map_one(&li->li_tv, expr, filtermap,
2545 				&newtv, &rem) == FAIL)
2546 			break;
2547 		    if (did_emsg)
2548 		    {
2549 			clear_tv(&newtv);
2550 			break;
2551 		    }
2552 		    if (filtermap == FILTERMAP_MAP)
2553 		    {
2554 			if (type != NULL && check_typval_arg_type(
2555 				type->tt_member, &newtv, func_name, 0) == FAIL)
2556 			{
2557 			    clear_tv(&newtv);
2558 			    break;
2559 			}
2560 			// map(): replace the list item value
2561 			clear_tv(&li->li_tv);
2562 			newtv.v_lock = 0;
2563 			li->li_tv = newtv;
2564 		    }
2565 		    else if (filtermap == FILTERMAP_MAPNEW)
2566 		    {
2567 			// mapnew(): append the list item value
2568 			if (list_append_tv_move(l_ret, &newtv) == FAIL)
2569 			    break;
2570 		    }
2571 		    else if (filtermap == FILTERMAP_FILTER && rem)
2572 			listitem_remove(l, li);
2573 		    ++idx;
2574 		}
2575 	    }
2576 
2577 	    l->lv_lock = prev_lock;
2578 	}
2579 
2580 	restore_vimvar(VV_KEY, &save_key);
2581 	restore_vimvar(VV_VAL, &save_val);
2582 
2583 	did_emsg |= save_did_emsg;
2584     }
2585 
2586 theend:
2587     if (type != NULL)
2588 	clear_type_list(&type_list);
2589 }
2590 
2591 /*
2592  * "filter()" function
2593  */
2594     void
2595 f_filter(typval_T *argvars, typval_T *rettv)
2596 {
2597     filter_map(argvars, rettv, FILTERMAP_FILTER);
2598 }
2599 
2600 /*
2601  * "map()" function
2602  */
2603     void
2604 f_map(typval_T *argvars, typval_T *rettv)
2605 {
2606     filter_map(argvars, rettv, FILTERMAP_MAP);
2607 }
2608 
2609 /*
2610  * "mapnew()" function
2611  */
2612     void
2613 f_mapnew(typval_T *argvars, typval_T *rettv)
2614 {
2615     filter_map(argvars, rettv, FILTERMAP_MAPNEW);
2616 }
2617 
2618 /*
2619  * "add(list, item)" function
2620  */
2621     void
2622 f_add(typval_T *argvars, typval_T *rettv)
2623 {
2624     rettv->vval.v_number = 1; // Default: Failed
2625 
2626     if (in_vim9script()
2627 	    && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2628 		|| (argvars[0].v_type == VAR_BLOB
2629 		    && check_for_number_arg(argvars, 1) == FAIL)))
2630 	return;
2631 
2632     if (argvars[0].v_type == VAR_LIST)
2633     {
2634 	list_T	*l = argvars[0].vval.v_list;
2635 
2636 	if (l == NULL)
2637 	{
2638 	    if (in_vim9script())
2639 		emsg(_(e_cannot_add_to_null_list));
2640 	}
2641 	else if (!value_check_lock(l->lv_lock,
2642 					  (char_u *)N_("add() argument"), TRUE)
2643 		&& list_append_tv(l, &argvars[1]) == OK)
2644 	{
2645 	    copy_tv(&argvars[0], rettv);
2646 	}
2647     }
2648     else if (argvars[0].v_type == VAR_BLOB)
2649     {
2650 	blob_T	*b = argvars[0].vval.v_blob;
2651 
2652 	if (b == NULL)
2653 	{
2654 	    if (in_vim9script())
2655 		emsg(_(e_cannot_add_to_null_blob));
2656 	}
2657 	else if (!value_check_lock(b->bv_lock,
2658 					 (char_u *)N_("add() argument"), TRUE))
2659 	{
2660 	    int		error = FALSE;
2661 	    varnumber_T n = tv_get_number_chk(&argvars[1], &error);
2662 
2663 	    if (!error)
2664 	    {
2665 		ga_append(&b->bv_ga, (int)n);
2666 		copy_tv(&argvars[0], rettv);
2667 	    }
2668 	}
2669     }
2670     else
2671 	emsg(_(e_listblobreq));
2672 }
2673 
2674 /*
2675  * "count()" function
2676  */
2677     void
2678 f_count(typval_T *argvars, typval_T *rettv)
2679 {
2680     long	n = 0;
2681     int		ic = FALSE;
2682     int		error = FALSE;
2683 
2684     if (in_vim9script()
2685 	    && (check_for_string_or_list_or_dict_arg(argvars, 0) == FAIL
2686 		|| check_for_opt_bool_arg(argvars, 2) == FAIL
2687 		|| (argvars[2].v_type != VAR_UNKNOWN
2688 		    && check_for_opt_number_arg(argvars, 3) == FAIL)))
2689 	return;
2690 
2691     if (argvars[2].v_type != VAR_UNKNOWN)
2692 	ic = (int)tv_get_bool_chk(&argvars[2], &error);
2693 
2694     if (argvars[0].v_type == VAR_STRING)
2695     {
2696 	char_u *expr = tv_get_string_chk(&argvars[1]);
2697 	char_u *p = argvars[0].vval.v_string;
2698 	char_u *next;
2699 
2700 	if (!error && expr != NULL && *expr != NUL && p != NULL)
2701 	{
2702 	    if (ic)
2703 	    {
2704 		size_t len = STRLEN(expr);
2705 
2706 		while (*p != NUL)
2707 		{
2708 		    if (MB_STRNICMP(p, expr, len) == 0)
2709 		    {
2710 			++n;
2711 			p += len;
2712 		    }
2713 		    else
2714 			MB_PTR_ADV(p);
2715 		}
2716 	    }
2717 	    else
2718 		while ((next = (char_u *)strstr((char *)p, (char *)expr))
2719 								       != NULL)
2720 		{
2721 		    ++n;
2722 		    p = next + STRLEN(expr);
2723 		}
2724 	}
2725 
2726     }
2727     else if (argvars[0].v_type == VAR_LIST)
2728     {
2729 	listitem_T	*li;
2730 	list_T		*l;
2731 	long		idx;
2732 
2733 	if ((l = argvars[0].vval.v_list) != NULL)
2734 	{
2735 	    CHECK_LIST_MATERIALIZE(l);
2736 	    li = l->lv_first;
2737 	    if (argvars[2].v_type != VAR_UNKNOWN)
2738 	    {
2739 		if (argvars[3].v_type != VAR_UNKNOWN)
2740 		{
2741 		    idx = (long)tv_get_number_chk(&argvars[3], &error);
2742 		    if (!error)
2743 		    {
2744 			li = list_find(l, idx);
2745 			if (li == NULL)
2746 			    semsg(_(e_listidx), idx);
2747 		    }
2748 		}
2749 		if (error)
2750 		    li = NULL;
2751 	    }
2752 
2753 	    for ( ; li != NULL; li = li->li_next)
2754 		if (tv_equal(&li->li_tv, &argvars[1], ic, FALSE))
2755 		    ++n;
2756 	}
2757     }
2758     else if (argvars[0].v_type == VAR_DICT)
2759     {
2760 	int		todo;
2761 	dict_T		*d;
2762 	hashitem_T	*hi;
2763 
2764 	if ((d = argvars[0].vval.v_dict) != NULL)
2765 	{
2766 	    if (argvars[2].v_type != VAR_UNKNOWN)
2767 	    {
2768 		if (argvars[3].v_type != VAR_UNKNOWN)
2769 		    emsg(_(e_invarg));
2770 	    }
2771 
2772 	    todo = error ? 0 : (int)d->dv_hashtab.ht_used;
2773 	    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
2774 	    {
2775 		if (!HASHITEM_EMPTY(hi))
2776 		{
2777 		    --todo;
2778 		    if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic, FALSE))
2779 			++n;
2780 		}
2781 	    }
2782 	}
2783     }
2784     else
2785 	semsg(_(e_listdictarg), "count()");
2786     rettv->vval.v_number = n;
2787 }
2788 
2789 /*
2790  * "extend()" or "extendnew()" function.  "is_new" is TRUE for extendnew().
2791  */
2792     static void
2793 extend(typval_T *argvars, typval_T *rettv, char_u *arg_errmsg, int is_new)
2794 {
2795     type_T	*type = NULL;
2796     garray_T	type_list;
2797     char	*func_name = is_new ? "extendnew()" : "extend()";
2798 
2799     if (!is_new && in_vim9script())
2800     {
2801 	// Check that map() does not change the type of the dict.
2802 	ga_init2(&type_list, sizeof(type_T *), 10);
2803 	type = typval2type(argvars, get_copyID(), &type_list, TRUE);
2804     }
2805 
2806     if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
2807     {
2808 	list_T		*l1, *l2;
2809 	listitem_T	*item;
2810 	long		before;
2811 	int		error = FALSE;
2812 
2813 	l1 = argvars[0].vval.v_list;
2814 	if (l1 == NULL)
2815 	{
2816 	    emsg(_(e_cannot_extend_null_list));
2817 	    goto theend;
2818 	}
2819 	l2 = argvars[1].vval.v_list;
2820 	if ((is_new || !value_check_lock(l1->lv_lock, arg_errmsg, TRUE))
2821 								 && l2 != NULL)
2822 	{
2823 	    if (is_new)
2824 	    {
2825 		l1 = list_copy(l1, FALSE, get_copyID());
2826 		if (l1 == NULL)
2827 		    goto theend;
2828 	    }
2829 
2830 	    if (argvars[2].v_type != VAR_UNKNOWN)
2831 	    {
2832 		before = (long)tv_get_number_chk(&argvars[2], &error);
2833 		if (error)
2834 		    goto theend;	// type error; errmsg already given
2835 
2836 		if (before == l1->lv_len)
2837 		    item = NULL;
2838 		else
2839 		{
2840 		    item = list_find(l1, before);
2841 		    if (item == NULL)
2842 		    {
2843 			semsg(_(e_listidx), before);
2844 			goto theend;
2845 		    }
2846 		}
2847 	    }
2848 	    else
2849 		item = NULL;
2850 	    if (type != NULL && check_typval_arg_type(
2851 				      type, &argvars[1], func_name, 2) == FAIL)
2852 		goto theend;
2853 	    list_extend(l1, l2, item);
2854 
2855 	    if (is_new)
2856 	    {
2857 		rettv->v_type = VAR_LIST;
2858 		rettv->vval.v_list = l1;
2859 		rettv->v_lock = FALSE;
2860 	    }
2861 	    else
2862 		copy_tv(&argvars[0], rettv);
2863 	}
2864     }
2865     else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
2866     {
2867 	dict_T	*d1, *d2;
2868 	char_u	*action;
2869 	int	i;
2870 
2871 	d1 = argvars[0].vval.v_dict;
2872 	if (d1 == NULL)
2873 	{
2874 	    emsg(_(e_cannot_extend_null_dict));
2875 	    goto theend;
2876 	}
2877 	d2 = argvars[1].vval.v_dict;
2878 	if ((is_new || !value_check_lock(d1->dv_lock, arg_errmsg, TRUE))
2879 								 && d2 != NULL)
2880 	{
2881 	    if (is_new)
2882 	    {
2883 		d1 = dict_copy(d1, FALSE, get_copyID());
2884 		if (d1 == NULL)
2885 		    goto theend;
2886 	    }
2887 
2888 	    // Check the third argument.
2889 	    if (argvars[2].v_type != VAR_UNKNOWN)
2890 	    {
2891 		static char *(av[]) = {"keep", "force", "error"};
2892 
2893 		action = tv_get_string_chk(&argvars[2]);
2894 		if (action == NULL)
2895 		    goto theend;	// type error; errmsg already given
2896 		for (i = 0; i < 3; ++i)
2897 		    if (STRCMP(action, av[i]) == 0)
2898 			break;
2899 		if (i == 3)
2900 		{
2901 		    semsg(_(e_invarg2), action);
2902 		    goto theend;
2903 		}
2904 	    }
2905 	    else
2906 		action = (char_u *)"force";
2907 
2908 	    if (type != NULL && check_typval_arg_type(type, &argvars[1],
2909 							 func_name, 2) == FAIL)
2910 		goto theend;
2911 	    dict_extend(d1, d2, action, func_name);
2912 
2913 	    if (is_new)
2914 	    {
2915 		rettv->v_type = VAR_DICT;
2916 		rettv->vval.v_dict = d1;
2917 		rettv->v_lock = FALSE;
2918 	    }
2919 	    else
2920 		copy_tv(&argvars[0], rettv);
2921 	}
2922     }
2923     else
2924 	semsg(_(e_listdictarg), func_name);
2925 
2926 theend:
2927     if (type != NULL)
2928 	clear_type_list(&type_list);
2929 }
2930 
2931 /*
2932  * "extend(list, list [, idx])" function
2933  * "extend(dict, dict [, action])" function
2934  */
2935     void
2936 f_extend(typval_T *argvars, typval_T *rettv)
2937 {
2938     char_u      *errmsg = (char_u *)N_("extend() argument");
2939 
2940     extend(argvars, rettv, errmsg, FALSE);
2941 }
2942 
2943 /*
2944  * "extendnew(list, list [, idx])" function
2945  * "extendnew(dict, dict [, action])" function
2946  */
2947     void
2948 f_extendnew(typval_T *argvars, typval_T *rettv)
2949 {
2950     char_u      *errmsg = (char_u *)N_("extendnew() argument");
2951 
2952     extend(argvars, rettv, errmsg, TRUE);
2953 }
2954 
2955 /*
2956  * "insert()" function
2957  */
2958     void
2959 f_insert(typval_T *argvars, typval_T *rettv)
2960 {
2961     long	before = 0;
2962     listitem_T	*item;
2963     int		error = FALSE;
2964 
2965     if (in_vim9script()
2966 	    && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2967 		|| (argvars[0].v_type == VAR_BLOB
2968 		    && check_for_number_arg(argvars, 1) == FAIL)
2969 		|| check_for_opt_number_arg(argvars, 2) == FAIL))
2970 	return;
2971 
2972     if (argvars[0].v_type == VAR_BLOB)
2973     {
2974 	blob_T	*b = argvars[0].vval.v_blob;
2975 
2976 	if (b == NULL)
2977 	{
2978 	    if (in_vim9script())
2979 		emsg(_(e_cannot_add_to_null_blob));
2980 	}
2981 	else if (!value_check_lock(b->bv_lock,
2982 				     (char_u *)N_("insert() argument"), TRUE))
2983 	{
2984 	    int		val, len;
2985 	    char_u	*p;
2986 
2987 	    len = blob_len(b);
2988 	    if (argvars[2].v_type != VAR_UNKNOWN)
2989 	    {
2990 		before = (long)tv_get_number_chk(&argvars[2], &error);
2991 		if (error)
2992 		    return;		// type error; errmsg already given
2993 		if (before < 0 || before > len)
2994 		{
2995 		    semsg(_(e_invarg2), tv_get_string(&argvars[2]));
2996 		    return;
2997 		}
2998 	    }
2999 	    val = tv_get_number_chk(&argvars[1], &error);
3000 	    if (error)
3001 		return;
3002 	    if (val < 0 || val > 255)
3003 	    {
3004 		semsg(_(e_invarg2), tv_get_string(&argvars[1]));
3005 		return;
3006 	    }
3007 
3008 	    if (ga_grow(&b->bv_ga, 1) == FAIL)
3009 		return;
3010 	    p = (char_u *)b->bv_ga.ga_data;
3011 	    mch_memmove(p + before + 1, p + before, (size_t)len - before);
3012 	    *(p + before) = val;
3013 	    ++b->bv_ga.ga_len;
3014 
3015 	    copy_tv(&argvars[0], rettv);
3016 	}
3017     }
3018     else if (argvars[0].v_type != VAR_LIST)
3019 	semsg(_(e_listblobarg), "insert()");
3020     else
3021     {
3022 	list_T	*l = argvars[0].vval.v_list;
3023 
3024 	if (l == NULL)
3025 	{
3026 	    if (in_vim9script())
3027 		emsg(_(e_cannot_add_to_null_list));
3028 	}
3029 	else if (!value_check_lock(l->lv_lock,
3030 				     (char_u *)N_("insert() argument"), TRUE))
3031 	{
3032 	    if (argvars[2].v_type != VAR_UNKNOWN)
3033 		before = (long)tv_get_number_chk(&argvars[2], &error);
3034 	    if (error)
3035 		return;		// type error; errmsg already given
3036 
3037 	    if (before == l->lv_len)
3038 		item = NULL;
3039 	    else
3040 	    {
3041 		item = list_find(l, before);
3042 		if (item == NULL)
3043 		{
3044 		    semsg(_(e_listidx), before);
3045 		    l = NULL;
3046 		}
3047 	    }
3048 	    if (l != NULL)
3049 	    {
3050 		(void)list_insert_tv(l, &argvars[1], item);
3051 		copy_tv(&argvars[0], rettv);
3052 	    }
3053 	}
3054     }
3055 }
3056 
3057 /*
3058  * "remove()" function
3059  */
3060     void
3061 f_remove(typval_T *argvars, typval_T *rettv)
3062 {
3063     char_u	*arg_errmsg = (char_u *)N_("remove() argument");
3064 
3065     if (in_vim9script()
3066 	    && (check_for_list_or_dict_or_blob_arg(argvars, 0) == FAIL
3067 		|| ((argvars[0].v_type == VAR_LIST
3068 			|| argvars[0].v_type == VAR_BLOB)
3069 		    && (check_for_number_arg(argvars, 1) == FAIL
3070 			|| check_for_opt_number_arg(argvars, 2) == FAIL))
3071 		|| (argvars[0].v_type == VAR_DICT
3072 		    && check_for_string_or_number_arg(argvars, 1) == FAIL)))
3073 	return;
3074 
3075     if (argvars[0].v_type == VAR_DICT)
3076 	dict_remove(argvars, rettv, arg_errmsg);
3077     else if (argvars[0].v_type == VAR_BLOB)
3078 	blob_remove(argvars, rettv, arg_errmsg);
3079     else if (argvars[0].v_type == VAR_LIST)
3080 	list_remove(argvars, rettv, arg_errmsg);
3081     else
3082 	semsg(_(e_listdictblobarg), "remove()");
3083 }
3084 
3085 /*
3086  * "reverse({list})" function
3087  */
3088     void
3089 f_reverse(typval_T *argvars, typval_T *rettv)
3090 {
3091     list_T	*l;
3092     listitem_T	*li, *ni;
3093 
3094     if (in_vim9script() && check_for_list_or_blob_arg(argvars, 0) == FAIL)
3095 	return;
3096 
3097     if (argvars[0].v_type == VAR_BLOB)
3098     {
3099 	blob_T	*b = argvars[0].vval.v_blob;
3100 	int	i, len = blob_len(b);
3101 
3102 	for (i = 0; i < len / 2; i++)
3103 	{
3104 	    int tmp = blob_get(b, i);
3105 
3106 	    blob_set(b, i, blob_get(b, len - i - 1));
3107 	    blob_set(b, len - i - 1, tmp);
3108 	}
3109 	rettv_blob_set(rettv, b);
3110 	return;
3111     }
3112 
3113     if (argvars[0].v_type != VAR_LIST)
3114 	semsg(_(e_listblobarg), "reverse()");
3115     else
3116     {
3117 	l = argvars[0].vval.v_list;
3118 	rettv_list_set(rettv, l);
3119 	if (l != NULL
3120 	    && !value_check_lock(l->lv_lock,
3121 				    (char_u *)N_("reverse() argument"), TRUE))
3122 	{
3123 	    if (l->lv_first == &range_list_item)
3124 	    {
3125 		varnumber_T new_start = l->lv_u.nonmat.lv_start
3126 				  + (l->lv_len - 1) * l->lv_u.nonmat.lv_stride;
3127 		l->lv_u.nonmat.lv_end = new_start
3128 			   - (l->lv_u.nonmat.lv_end - l->lv_u.nonmat.lv_start);
3129 		l->lv_u.nonmat.lv_start = new_start;
3130 		l->lv_u.nonmat.lv_stride = -l->lv_u.nonmat.lv_stride;
3131 		return;
3132 	    }
3133 	    li = l->lv_u.mat.lv_last;
3134 	    l->lv_first = l->lv_u.mat.lv_last = NULL;
3135 	    l->lv_len = 0;
3136 	    while (li != NULL)
3137 	    {
3138 		ni = li->li_prev;
3139 		list_append(l, li);
3140 		li = ni;
3141 	    }
3142 	    l->lv_u.mat.lv_idx = l->lv_len - l->lv_u.mat.lv_idx - 1;
3143 	}
3144     }
3145 }
3146 
3147 /*
3148  * "reduce(list, { accumulator, element -> value } [, initial])" function
3149  */
3150     void
3151 f_reduce(typval_T *argvars, typval_T *rettv)
3152 {
3153     typval_T	initial;
3154     char_u	*func_name;
3155     partial_T   *partial = NULL;
3156     funcexe_T	funcexe;
3157     typval_T	argv[3];
3158 
3159     if (argvars[0].v_type != VAR_LIST && argvars[0].v_type != VAR_BLOB)
3160     {
3161 	emsg(_(e_listblobreq));
3162 	return;
3163     }
3164 
3165     if (argvars[1].v_type == VAR_FUNC)
3166 	func_name = argvars[1].vval.v_string;
3167     else if (argvars[1].v_type == VAR_PARTIAL)
3168     {
3169 	partial = argvars[1].vval.v_partial;
3170 	func_name = partial_name(partial);
3171     }
3172     else
3173 	func_name = tv_get_string(&argvars[1]);
3174     if (func_name == NULL || *func_name == NUL)
3175     {
3176 	emsg(_(e_missing_function_argument));
3177 	return;
3178     }
3179 
3180     vim_memset(&funcexe, 0, sizeof(funcexe));
3181     funcexe.evaluate = TRUE;
3182     funcexe.partial = partial;
3183 
3184     if (argvars[0].v_type == VAR_LIST)
3185     {
3186 	list_T	    *l = argvars[0].vval.v_list;
3187 	listitem_T  *li = NULL;
3188 	int	    r;
3189 	int	    called_emsg_start = called_emsg;
3190 
3191 	if (l != NULL)
3192 	    CHECK_LIST_MATERIALIZE(l);
3193 	if (argvars[2].v_type == VAR_UNKNOWN)
3194 	{
3195 	    if (l == NULL || l->lv_first == NULL)
3196 	    {
3197 		semsg(_(e_reduceempty), "List");
3198 		return;
3199 	    }
3200 	    initial = l->lv_first->li_tv;
3201 	    li = l->lv_first->li_next;
3202 	}
3203 	else
3204 	{
3205 	    initial = argvars[2];
3206 	    if (l != NULL)
3207 		li = l->lv_first;
3208 	}
3209 	copy_tv(&initial, rettv);
3210 
3211 	if (l != NULL)
3212 	{
3213 	    int	    prev_locked = l->lv_lock;
3214 
3215 	    l->lv_lock = VAR_FIXED;  // disallow the list changing here
3216 	    for ( ; li != NULL; li = li->li_next)
3217 	    {
3218 		argv[0] = *rettv;
3219 		argv[1] = li->li_tv;
3220 		rettv->v_type = VAR_UNKNOWN;
3221 		r = call_func(func_name, -1, rettv, 2, argv, &funcexe);
3222 		clear_tv(&argv[0]);
3223 		if (r == FAIL || called_emsg != called_emsg_start)
3224 		    break;
3225 	    }
3226 	    l->lv_lock = prev_locked;
3227 	}
3228     }
3229     else
3230     {
3231 	blob_T	*b = argvars[0].vval.v_blob;
3232 	int	i;
3233 
3234 	if (argvars[2].v_type == VAR_UNKNOWN)
3235 	{
3236 	    if (b == NULL || b->bv_ga.ga_len == 0)
3237 	    {
3238 		semsg(_(e_reduceempty), "Blob");
3239 		return;
3240 	    }
3241 	    initial.v_type = VAR_NUMBER;
3242 	    initial.vval.v_number = blob_get(b, 0);
3243 	    i = 1;
3244 	}
3245 	else if (argvars[2].v_type != VAR_NUMBER)
3246 	{
3247 	    emsg(_(e_number_expected));
3248 	    return;
3249 	}
3250 	else
3251 	{
3252 	    initial = argvars[2];
3253 	    i = 0;
3254 	}
3255 
3256 	copy_tv(&initial, rettv);
3257 	if (b != NULL)
3258 	{
3259 	    for ( ; i < b->bv_ga.ga_len; i++)
3260 	    {
3261 		argv[0] = *rettv;
3262 		argv[1].v_type = VAR_NUMBER;
3263 		argv[1].vval.v_number = blob_get(b, i);
3264 		if (call_func(func_name, -1, rettv, 2, argv, &funcexe) == FAIL)
3265 		    return;
3266 	    }
3267 	}
3268     }
3269 }
3270 
3271 #endif // defined(FEAT_EVAL)
3272