xref: /vim-8.2.3635/src/register.c (revision ed37d9b3)
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  * register.c: functions for managing registers
12  */
13 
14 #include "vim.h"
15 
16 /*
17  * Registers:
18  *	0 = unnamed register, for normal yanks and puts
19  *   1..9 = registers '1' to '9', for deletes
20  * 10..35 = registers 'a' to 'z' ('A' to 'Z' for appending)
21  *     36 = delete register '-'
22  *     37 = Selection register '*'. Only if FEAT_CLIPBOARD defined
23  *     38 = Clipboard register '+'. Only if FEAT_CLIPBOARD and FEAT_X11 defined
24  */
25 static yankreg_T	y_regs[NUM_REGISTERS];
26 
27 static yankreg_T	*y_current;	    // ptr to current yankreg
28 static int		y_append;	    // TRUE when appending
29 static yankreg_T	*y_previous = NULL; // ptr to last written yankreg
30 
31 static int	stuff_yank(int, char_u *);
32 static void	put_reedit_in_typebuf(int silent);
33 static int	put_in_typebuf(char_u *s, int esc, int colon,
34 								 int silent);
35 static int	yank_copy_line(struct block_def *bd, long y_idx);
36 #ifdef FEAT_CLIPBOARD
37 static void	copy_yank_reg(yankreg_T *reg);
38 #endif
39 static void	dis_msg(char_u *p, int skip_esc);
40 
41     yankreg_T *
42 get_y_regs(void)
43 {
44     return y_regs;
45 }
46 
47     yankreg_T *
48 get_y_register(int reg)
49 {
50     return &y_regs[reg];
51 }
52 
53     yankreg_T *
54 get_y_current(void)
55 {
56     return y_current;
57 }
58 
59     yankreg_T *
60 get_y_previous(void)
61 {
62     return y_previous;
63 }
64 
65     void
66 set_y_current(yankreg_T *yreg)
67 {
68     y_current = yreg;
69 }
70 
71     void
72 set_y_previous(yankreg_T *yreg)
73 {
74     y_previous = yreg;
75 }
76 
77 #if defined(FEAT_EVAL) || defined(PROTO)
78 /*
79  * Keep the last expression line here, for repeating.
80  */
81 static char_u	*expr_line = NULL;
82 
83 /*
84  * Get an expression for the "\"=expr1" or "CTRL-R =expr1"
85  * Returns '=' when OK, NUL otherwise.
86  */
87     int
88 get_expr_register(void)
89 {
90     char_u	*new_line;
91 
92     new_line = getcmdline('=', 0L, 0, TRUE);
93     if (new_line == NULL)
94 	return NUL;
95     if (*new_line == NUL)	// use previous line
96 	vim_free(new_line);
97     else
98 	set_expr_line(new_line);
99     return '=';
100 }
101 
102 /*
103  * Set the expression for the '=' register.
104  * Argument must be an allocated string.
105  */
106     void
107 set_expr_line(char_u *new_line)
108 {
109     vim_free(expr_line);
110     expr_line = new_line;
111 }
112 
113 /*
114  * Get the result of the '=' register expression.
115  * Returns a pointer to allocated memory, or NULL for failure.
116  */
117     char_u *
118 get_expr_line(void)
119 {
120     char_u	*expr_copy;
121     char_u	*rv;
122     static int	nested = 0;
123 
124     if (expr_line == NULL)
125 	return NULL;
126 
127     // Make a copy of the expression, because evaluating it may cause it to be
128     // changed.
129     expr_copy = vim_strsave(expr_line);
130     if (expr_copy == NULL)
131 	return NULL;
132 
133     // When we are invoked recursively limit the evaluation to 10 levels.
134     // Then return the string as-is.
135     if (nested >= 10)
136 	return expr_copy;
137 
138     ++nested;
139     rv = eval_to_string(expr_copy, NULL, TRUE);
140     --nested;
141     vim_free(expr_copy);
142     return rv;
143 }
144 
145 /*
146  * Get the '=' register expression itself, without evaluating it.
147  */
148     static char_u *
149 get_expr_line_src(void)
150 {
151     if (expr_line == NULL)
152 	return NULL;
153     return vim_strsave(expr_line);
154 }
155 #endif // FEAT_EVAL
156 
157 /*
158  * Check if 'regname' is a valid name of a yank register.
159  * Note: There is no check for 0 (default register), caller should do this
160  */
161     int
162 valid_yank_reg(
163     int	    regname,
164     int	    writing)	    // if TRUE check for writable registers
165 {
166     if (       (regname > 0 && ASCII_ISALNUM(regname))
167 	    || (!writing && vim_strchr((char_u *)
168 #ifdef FEAT_EVAL
169 				    "/.%:="
170 #else
171 				    "/.%:"
172 #endif
173 					, regname) != NULL)
174 	    || regname == '#'
175 	    || regname == '"'
176 	    || regname == '-'
177 	    || regname == '_'
178 #ifdef FEAT_CLIPBOARD
179 	    || regname == '*'
180 	    || regname == '+'
181 #endif
182 #ifdef FEAT_DND
183 	    || (!writing && regname == '~')
184 #endif
185 							)
186 	return TRUE;
187     return FALSE;
188 }
189 
190 /*
191  * Set y_current and y_append, according to the value of "regname".
192  * Cannot handle the '_' register.
193  * Must only be called with a valid register name!
194  *
195  * If regname is 0 and writing, use register 0
196  * If regname is 0 and reading, use previous register
197  *
198  * Return TRUE when the register should be inserted literally (selection or
199  * clipboard).
200  */
201     int
202 get_yank_register(int regname, int writing)
203 {
204     int	    i;
205     int	    ret = FALSE;
206 
207     y_append = FALSE;
208     if ((regname == 0 || regname == '"') && !writing && y_previous != NULL)
209     {
210 	y_current = y_previous;
211 	return ret;
212     }
213     i = regname;
214     if (VIM_ISDIGIT(i))
215 	i -= '0';
216     else if (ASCII_ISLOWER(i))
217 	i = CharOrdLow(i) + 10;
218     else if (ASCII_ISUPPER(i))
219     {
220 	i = CharOrdUp(i) + 10;
221 	y_append = TRUE;
222     }
223     else if (regname == '-')
224 	i = DELETION_REGISTER;
225 #ifdef FEAT_CLIPBOARD
226     // When selection is not available, use register 0 instead of '*'
227     else if (clip_star.available && regname == '*')
228     {
229 	i = STAR_REGISTER;
230 	ret = TRUE;
231     }
232     // When clipboard is not available, use register 0 instead of '+'
233     else if (clip_plus.available && regname == '+')
234     {
235 	i = PLUS_REGISTER;
236 	ret = TRUE;
237     }
238 #endif
239 #ifdef FEAT_DND
240     else if (!writing && regname == '~')
241 	i = TILDE_REGISTER;
242 #endif
243     else		// not 0-9, a-z, A-Z or '-': use register 0
244 	i = 0;
245     y_current = &(y_regs[i]);
246     if (writing)	// remember the register we write into for do_put()
247 	y_previous = y_current;
248     return ret;
249 }
250 
251 /*
252  * Obtain the contents of a "normal" register. The register is made empty.
253  * The returned pointer has allocated memory, use put_register() later.
254  */
255     void *
256 get_register(
257     int		name,
258     int		copy)	// make a copy, if FALSE make register empty.
259 {
260     yankreg_T	*reg;
261     int		i;
262 
263 #ifdef FEAT_CLIPBOARD
264     // When Visual area changed, may have to update selection.  Obtain the
265     // selection too.
266     if (name == '*' && clip_star.available)
267     {
268 	if (clip_isautosel_star())
269 	    clip_update_selection(&clip_star);
270 	may_get_selection(name);
271     }
272     if (name == '+' && clip_plus.available)
273     {
274 	if (clip_isautosel_plus())
275 	    clip_update_selection(&clip_plus);
276 	may_get_selection(name);
277     }
278 #endif
279 
280     get_yank_register(name, 0);
281     reg = ALLOC_ONE(yankreg_T);
282     if (reg != NULL)
283     {
284 	*reg = *y_current;
285 	if (copy)
286 	{
287 	    // If we run out of memory some or all of the lines are empty.
288 	    if (reg->y_size == 0)
289 		reg->y_array = NULL;
290 	    else
291 		reg->y_array = ALLOC_MULT(char_u *, reg->y_size);
292 	    if (reg->y_array != NULL)
293 	    {
294 		for (i = 0; i < reg->y_size; ++i)
295 		    reg->y_array[i] = vim_strsave(y_current->y_array[i]);
296 	    }
297 	}
298 	else
299 	    y_current->y_array = NULL;
300     }
301     return (void *)reg;
302 }
303 
304 /*
305  * Put "reg" into register "name".  Free any previous contents and "reg".
306  */
307     void
308 put_register(int name, void *reg)
309 {
310     get_yank_register(name, 0);
311     free_yank_all();
312     *y_current = *(yankreg_T *)reg;
313     vim_free(reg);
314 
315 #ifdef FEAT_CLIPBOARD
316     // Send text written to clipboard register to the clipboard.
317     may_set_selection();
318 #endif
319 }
320 
321 #if (defined(FEAT_CLIPBOARD) && defined(FEAT_X11) && defined(USE_SYSTEM)) \
322 	|| defined(PROTO)
323     void
324 free_register(void *reg)
325 {
326     yankreg_T tmp;
327 
328     tmp = *y_current;
329     *y_current = *(yankreg_T *)reg;
330     free_yank_all();
331     vim_free(reg);
332     *y_current = tmp;
333 }
334 #endif
335 
336 /*
337  * return TRUE if the current yank register has type MLINE
338  */
339     int
340 yank_register_mline(int regname)
341 {
342     if (regname != 0 && !valid_yank_reg(regname, FALSE))
343 	return FALSE;
344     if (regname == '_')		// black hole is always empty
345 	return FALSE;
346     get_yank_register(regname, FALSE);
347     return (y_current->y_type == MLINE);
348 }
349 
350 /*
351  * Start or stop recording into a yank register.
352  *
353  * Return FAIL for failure, OK otherwise.
354  */
355     int
356 do_record(int c)
357 {
358     char_u	    *p;
359     static int	    regname;
360     yankreg_T	    *old_y_previous, *old_y_current;
361     int		    retval;
362 
363     if (reg_recording == 0)	    // start recording
364     {
365 	// registers 0-9, a-z and " are allowed
366 	if (c < 0 || (!ASCII_ISALNUM(c) && c != '"'))
367 	    retval = FAIL;
368 	else
369 	{
370 	    reg_recording = c;
371 	    showmode();
372 	    regname = c;
373 	    retval = OK;
374 	}
375     }
376     else			    // stop recording
377     {
378 	// Get the recorded key hits.  K_SPECIAL and CSI will be escaped, this
379 	// needs to be removed again to put it in a register.  exec_reg then
380 	// adds the escaping back later.
381 	reg_recording = 0;
382 	msg("");
383 	p = get_recorded();
384 	if (p == NULL)
385 	    retval = FAIL;
386 	else
387 	{
388 	    // Remove escaping for CSI and K_SPECIAL in multi-byte chars.
389 	    vim_unescape_csi(p);
390 
391 	    // We don't want to change the default register here, so save and
392 	    // restore the current register name.
393 	    old_y_previous = y_previous;
394 	    old_y_current = y_current;
395 
396 	    retval = stuff_yank(regname, p);
397 
398 	    y_previous = old_y_previous;
399 	    y_current = old_y_current;
400 	}
401     }
402     return retval;
403 }
404 
405 /*
406  * Stuff string "p" into yank register "regname" as a single line (append if
407  * uppercase).	"p" must have been alloced.
408  *
409  * return FAIL for failure, OK otherwise
410  */
411     static int
412 stuff_yank(int regname, char_u *p)
413 {
414     char_u	*lp;
415     char_u	**pp;
416 
417     // check for read-only register
418     if (regname != 0 && !valid_yank_reg(regname, TRUE))
419     {
420 	vim_free(p);
421 	return FAIL;
422     }
423     if (regname == '_')		    // black hole: don't do anything
424     {
425 	vim_free(p);
426 	return OK;
427     }
428     get_yank_register(regname, TRUE);
429     if (y_append && y_current->y_array != NULL)
430     {
431 	pp = &(y_current->y_array[y_current->y_size - 1]);
432 	lp = alloc(STRLEN(*pp) + STRLEN(p) + 1);
433 	if (lp == NULL)
434 	{
435 	    vim_free(p);
436 	    return FAIL;
437 	}
438 	STRCPY(lp, *pp);
439 	STRCAT(lp, p);
440 	vim_free(p);
441 	vim_free(*pp);
442 	*pp = lp;
443     }
444     else
445     {
446 	free_yank_all();
447 	if ((y_current->y_array = ALLOC_ONE(char_u *)) == NULL)
448 	{
449 	    vim_free(p);
450 	    return FAIL;
451 	}
452 	y_current->y_array[0] = p;
453 	y_current->y_size = 1;
454 	y_current->y_type = MCHAR;  // used to be MLINE, why?
455 #ifdef FEAT_VIMINFO
456 	y_current->y_time_set = vim_time();
457 #endif
458     }
459     return OK;
460 }
461 
462 static int execreg_lastc = NUL;
463 
464     int
465 get_execreg_lastc(void)
466 {
467     return execreg_lastc;
468 }
469 
470     void
471 set_execreg_lastc(int lastc)
472 {
473     execreg_lastc = lastc;
474 }
475 
476 /*
477  * Execute a yank register: copy it into the stuff buffer.
478  *
479  * Return FAIL for failure, OK otherwise.
480  */
481     int
482 do_execreg(
483     int	    regname,
484     int	    colon,		// insert ':' before each line
485     int	    addcr,		// always add '\n' to end of line
486     int	    silent)		// set "silent" flag in typeahead buffer
487 {
488     long	i;
489     char_u	*p;
490     int		retval = OK;
491     int		remap;
492 
493     // repeat previous one
494     if (regname == '@')
495     {
496 	if (execreg_lastc == NUL)
497 	{
498 	    emsg(_("E748: No previously used register"));
499 	    return FAIL;
500 	}
501 	regname = execreg_lastc;
502     }
503     // check for valid regname
504     if (regname == '%' || regname == '#' || !valid_yank_reg(regname, FALSE))
505     {
506 	emsg_invreg(regname);
507 	return FAIL;
508     }
509     execreg_lastc = regname;
510 
511 #ifdef FEAT_CLIPBOARD
512     regname = may_get_selection(regname);
513 #endif
514 
515     // black hole: don't stuff anything
516     if (regname == '_')
517 	return OK;
518 
519     // use last command line
520     if (regname == ':')
521     {
522 	if (last_cmdline == NULL)
523 	{
524 	    emsg(_(e_nolastcmd));
525 	    return FAIL;
526 	}
527 	// don't keep the cmdline containing @:
528 	VIM_CLEAR(new_last_cmdline);
529 	// Escape all control characters with a CTRL-V
530 	p = vim_strsave_escaped_ext(last_cmdline,
531 		    (char_u *)"\001\002\003\004\005\006\007"
532 			  "\010\011\012\013\014\015\016\017"
533 			  "\020\021\022\023\024\025\026\027"
534 			  "\030\031\032\033\034\035\036\037",
535 		    Ctrl_V, FALSE);
536 	if (p != NULL)
537 	{
538 	    // When in Visual mode "'<,'>" will be prepended to the command.
539 	    // Remove it when it's already there.
540 	    if (VIsual_active && STRNCMP(p, "'<,'>", 5) == 0)
541 		retval = put_in_typebuf(p + 5, TRUE, TRUE, silent);
542 	    else
543 		retval = put_in_typebuf(p, TRUE, TRUE, silent);
544 	}
545 	vim_free(p);
546     }
547 #ifdef FEAT_EVAL
548     else if (regname == '=')
549     {
550 	p = get_expr_line();
551 	if (p == NULL)
552 	    return FAIL;
553 	retval = put_in_typebuf(p, TRUE, colon, silent);
554 	vim_free(p);
555     }
556 #endif
557     else if (regname == '.')		// use last inserted text
558     {
559 	p = get_last_insert_save();
560 	if (p == NULL)
561 	{
562 	    emsg(_(e_noinstext));
563 	    return FAIL;
564 	}
565 	retval = put_in_typebuf(p, FALSE, colon, silent);
566 	vim_free(p);
567     }
568     else
569     {
570 	get_yank_register(regname, FALSE);
571 	if (y_current->y_array == NULL)
572 	    return FAIL;
573 
574 	// Disallow remapping for ":@r".
575 	remap = colon ? REMAP_NONE : REMAP_YES;
576 
577 	// Insert lines into typeahead buffer, from last one to first one.
578 	put_reedit_in_typebuf(silent);
579 	for (i = y_current->y_size; --i >= 0; )
580 	{
581 	    char_u *escaped;
582 
583 	    // insert NL between lines and after last line if type is MLINE
584 	    if (y_current->y_type == MLINE || i < y_current->y_size - 1
585 								     || addcr)
586 	    {
587 		if (ins_typebuf((char_u *)"\n", remap, 0, TRUE, silent) == FAIL)
588 		    return FAIL;
589 	    }
590 	    escaped = vim_strsave_escape_csi(y_current->y_array[i]);
591 	    if (escaped == NULL)
592 		return FAIL;
593 	    retval = ins_typebuf(escaped, remap, 0, TRUE, silent);
594 	    vim_free(escaped);
595 	    if (retval == FAIL)
596 		return FAIL;
597 	    if (colon && ins_typebuf((char_u *)":", remap, 0, TRUE, silent)
598 								      == FAIL)
599 		return FAIL;
600 	}
601 	reg_executing = regname == 0 ? '"' : regname; // disable "q" command
602     }
603     return retval;
604 }
605 
606 /*
607  * If "restart_edit" is not zero, put it in the typeahead buffer, so that it's
608  * used only after other typeahead has been processed.
609  */
610     static void
611 put_reedit_in_typebuf(int silent)
612 {
613     char_u	buf[3];
614 
615     if (restart_edit != NUL)
616     {
617 	if (restart_edit == 'V')
618 	{
619 	    buf[0] = 'g';
620 	    buf[1] = 'R';
621 	    buf[2] = NUL;
622 	}
623 	else
624 	{
625 	    buf[0] = restart_edit == 'I' ? 'i' : restart_edit;
626 	    buf[1] = NUL;
627 	}
628 	if (ins_typebuf(buf, REMAP_NONE, 0, TRUE, silent) == OK)
629 	    restart_edit = NUL;
630     }
631 }
632 
633 /*
634  * Insert register contents "s" into the typeahead buffer, so that it will be
635  * executed again.
636  * When "esc" is TRUE it is to be taken literally: Escape CSI characters and
637  * no remapping.
638  */
639     static int
640 put_in_typebuf(
641     char_u	*s,
642     int		esc,
643     int		colon,	    // add ':' before the line
644     int		silent)
645 {
646     int		retval = OK;
647 
648     put_reedit_in_typebuf(silent);
649     if (colon)
650 	retval = ins_typebuf((char_u *)"\n", REMAP_NONE, 0, TRUE, silent);
651     if (retval == OK)
652     {
653 	char_u	*p;
654 
655 	if (esc)
656 	    p = vim_strsave_escape_csi(s);
657 	else
658 	    p = s;
659 	if (p == NULL)
660 	    retval = FAIL;
661 	else
662 	    retval = ins_typebuf(p, esc ? REMAP_NONE : REMAP_YES,
663 							     0, TRUE, silent);
664 	if (esc)
665 	    vim_free(p);
666     }
667     if (colon && retval == OK)
668 	retval = ins_typebuf((char_u *)":", REMAP_NONE, 0, TRUE, silent);
669     return retval;
670 }
671 
672 /*
673  * Insert a yank register: copy it into the Read buffer.
674  * Used by CTRL-R command and middle mouse button in insert mode.
675  *
676  * return FAIL for failure, OK otherwise
677  */
678     int
679 insert_reg(
680     int		regname,
681     int		literally_arg)	// insert literally, not as if typed
682 {
683     long	i;
684     int		retval = OK;
685     char_u	*arg;
686     int		allocated;
687     int		literally = literally_arg;
688 
689     // It is possible to get into an endless loop by having CTRL-R a in
690     // register a and then, in insert mode, doing CTRL-R a.
691     // If you hit CTRL-C, the loop will be broken here.
692     ui_breakcheck();
693     if (got_int)
694 	return FAIL;
695 
696     // check for valid regname
697     if (regname != NUL && !valid_yank_reg(regname, FALSE))
698 	return FAIL;
699 
700 #ifdef FEAT_CLIPBOARD
701     regname = may_get_selection(regname);
702 #endif
703 
704     if (regname == '.')			// insert last inserted text
705 	retval = stuff_inserted(NUL, 1L, TRUE);
706     else if (get_spec_reg(regname, &arg, &allocated, TRUE))
707     {
708 	if (arg == NULL)
709 	    return FAIL;
710 	stuffescaped(arg, literally);
711 	if (allocated)
712 	    vim_free(arg);
713     }
714     else				// name or number register
715     {
716 	if (get_yank_register(regname, FALSE))
717 	    literally = TRUE;
718 	if (y_current->y_array == NULL)
719 	    retval = FAIL;
720 	else
721 	{
722 	    for (i = 0; i < y_current->y_size; ++i)
723 	    {
724 		stuffescaped(y_current->y_array[i], literally);
725 		// Insert a newline between lines and after last line if
726 		// y_type is MLINE.
727 		if (y_current->y_type == MLINE || i < y_current->y_size - 1)
728 		    stuffcharReadbuff('\n');
729 	    }
730 	}
731     }
732 
733     return retval;
734 }
735 
736 /*
737  * If "regname" is a special register, return TRUE and store a pointer to its
738  * value in "argp".
739  */
740     int
741 get_spec_reg(
742     int		regname,
743     char_u	**argp,
744     int		*allocated,	// return: TRUE when value was allocated
745     int		errmsg)		// give error message when failing
746 {
747     int		cnt;
748 
749     *argp = NULL;
750     *allocated = FALSE;
751     switch (regname)
752     {
753 	case '%':		// file name
754 	    if (errmsg)
755 		check_fname();	// will give emsg if not set
756 	    *argp = curbuf->b_fname;
757 	    return TRUE;
758 
759 	case '#':		// alternate file name
760 	    *argp = getaltfname(errmsg);	// may give emsg if not set
761 	    return TRUE;
762 
763 #ifdef FEAT_EVAL
764 	case '=':		// result of expression
765 	    *argp = get_expr_line();
766 	    *allocated = TRUE;
767 	    return TRUE;
768 #endif
769 
770 	case ':':		// last command line
771 	    if (last_cmdline == NULL && errmsg)
772 		emsg(_(e_nolastcmd));
773 	    *argp = last_cmdline;
774 	    return TRUE;
775 
776 	case '/':		// last search-pattern
777 	    if (last_search_pat() == NULL && errmsg)
778 		emsg(_(e_noprevre));
779 	    *argp = last_search_pat();
780 	    return TRUE;
781 
782 	case '.':		// last inserted text
783 	    *argp = get_last_insert_save();
784 	    *allocated = TRUE;
785 	    if (*argp == NULL && errmsg)
786 		emsg(_(e_noinstext));
787 	    return TRUE;
788 
789 #ifdef FEAT_SEARCHPATH
790 	case Ctrl_F:		// Filename under cursor
791 	case Ctrl_P:		// Path under cursor, expand via "path"
792 	    if (!errmsg)
793 		return FALSE;
794 	    *argp = file_name_at_cursor(FNAME_MESS | FNAME_HYP
795 			    | (regname == Ctrl_P ? FNAME_EXP : 0), 1L, NULL);
796 	    *allocated = TRUE;
797 	    return TRUE;
798 #endif
799 
800 	case Ctrl_W:		// word under cursor
801 	case Ctrl_A:		// WORD (mnemonic All) under cursor
802 	    if (!errmsg)
803 		return FALSE;
804 	    cnt = find_ident_under_cursor(argp, regname == Ctrl_W
805 				   ?  (FIND_IDENT|FIND_STRING) : FIND_STRING);
806 	    *argp = cnt ? vim_strnsave(*argp, cnt) : NULL;
807 	    *allocated = TRUE;
808 	    return TRUE;
809 
810 	case Ctrl_L:		// Line under cursor
811 	    if (!errmsg)
812 		return FALSE;
813 
814 	    *argp = ml_get_buf(curwin->w_buffer,
815 			curwin->w_cursor.lnum, FALSE);
816 	    return TRUE;
817 
818 	case '_':		// black hole: always empty
819 	    *argp = (char_u *)"";
820 	    return TRUE;
821     }
822 
823     return FALSE;
824 }
825 
826 /*
827  * Paste a yank register into the command line.
828  * Only for non-special registers.
829  * Used by CTRL-R command in command-line mode
830  * insert_reg() can't be used here, because special characters from the
831  * register contents will be interpreted as commands.
832  *
833  * return FAIL for failure, OK otherwise
834  */
835     int
836 cmdline_paste_reg(
837     int regname,
838     int literally_arg,	// Insert text literally instead of "as typed"
839     int remcr)		// don't add CR characters
840 {
841     long	i;
842     int		literally = literally_arg;
843 
844     if (get_yank_register(regname, FALSE))
845 	literally = TRUE;
846     if (y_current->y_array == NULL)
847 	return FAIL;
848 
849     for (i = 0; i < y_current->y_size; ++i)
850     {
851 	cmdline_paste_str(y_current->y_array[i], literally);
852 
853 	// Insert ^M between lines and after last line if type is MLINE.
854 	// Don't do this when "remcr" is TRUE.
855 	if ((y_current->y_type == MLINE || i < y_current->y_size - 1) && !remcr)
856 	    cmdline_paste_str((char_u *)"\r", literally);
857 
858 	// Check for CTRL-C, in case someone tries to paste a few thousand
859 	// lines and gets bored.
860 	ui_breakcheck();
861 	if (got_int)
862 	    return FAIL;
863     }
864     return OK;
865 }
866 
867 /*
868  * Shift the delete registers: "9 is cleared, "8 becomes "9, etc.
869  */
870     void
871 shift_delete_registers()
872 {
873     int		n;
874 
875     y_current = &y_regs[9];
876     free_yank_all();			// free register nine
877     for (n = 9; n > 1; --n)
878 	y_regs[n] = y_regs[n - 1];
879     y_current = &y_regs[1];
880     if (!y_append)
881 	y_previous = y_current;
882     y_regs[1].y_array = NULL;		// set register one to empty
883 }
884 
885 #if defined(FEAT_EVAL)
886     void
887 yank_do_autocmd(oparg_T *oap, yankreg_T *reg)
888 {
889     static int	recursive = FALSE;
890     dict_T	*v_event;
891     list_T	*list;
892     int		n;
893     char_u	buf[NUMBUFLEN + 2];
894     long	reglen = 0;
895 
896     if (recursive)
897 	return;
898 
899     v_event = get_vim_var_dict(VV_EVENT);
900 
901     list = list_alloc();
902     if (list == NULL)
903 	return;
904     for (n = 0; n < reg->y_size; n++)
905 	list_append_string(list, reg->y_array[n], -1);
906     list->lv_lock = VAR_FIXED;
907     dict_add_list(v_event, "regcontents", list);
908 
909     buf[0] = (char_u)oap->regname;
910     buf[1] = NUL;
911     dict_add_string(v_event, "regname", buf);
912 
913     buf[0] = get_op_char(oap->op_type);
914     buf[1] = get_extra_op_char(oap->op_type);
915     buf[2] = NUL;
916     dict_add_string(v_event, "operator", buf);
917 
918     buf[0] = NUL;
919     buf[1] = NUL;
920     switch (get_reg_type(oap->regname, &reglen))
921     {
922 	case MLINE: buf[0] = 'V'; break;
923 	case MCHAR: buf[0] = 'v'; break;
924 	case MBLOCK:
925 		vim_snprintf((char *)buf, sizeof(buf), "%c%ld", Ctrl_V,
926 			     reglen + 1);
927 		break;
928     }
929     dict_add_string(v_event, "regtype", buf);
930 
931     // Lock the dictionary and its keys
932     dict_set_items_ro(v_event);
933 
934     recursive = TRUE;
935     textwinlock++;
936     apply_autocmds(EVENT_TEXTYANKPOST, NULL, NULL, FALSE, curbuf);
937     textwinlock--;
938     recursive = FALSE;
939 
940     // Empty the dictionary, v:event is still valid
941     dict_free_contents(v_event);
942     hash_init(&v_event->dv_hashtab);
943 }
944 #endif
945 
946 /*
947  * set all the yank registers to empty (called from main())
948  */
949     void
950 init_yank(void)
951 {
952     int		i;
953 
954     for (i = 0; i < NUM_REGISTERS; ++i)
955 	y_regs[i].y_array = NULL;
956 }
957 
958 #if defined(EXITFREE) || defined(PROTO)
959     void
960 clear_registers(void)
961 {
962     int		i;
963 
964     for (i = 0; i < NUM_REGISTERS; ++i)
965     {
966 	y_current = &y_regs[i];
967 	if (y_current->y_array != NULL)
968 	    free_yank_all();
969     }
970 }
971 #endif
972 
973 /*
974  * Free "n" lines from the current yank register.
975  * Called for normal freeing and in case of error.
976  */
977     static void
978 free_yank(long n)
979 {
980     if (y_current->y_array != NULL)
981     {
982 	long	    i;
983 
984 	for (i = n; --i >= 0; )
985 	{
986 #ifdef AMIGA	    // only for very slow machines
987 	    if ((i & 1023) == 1023)  // this may take a while
988 	    {
989 		// This message should never cause a hit-return message.
990 		// Overwrite this message with any next message.
991 		++no_wait_return;
992 		smsg(_("freeing %ld lines"), i + 1);
993 		--no_wait_return;
994 		msg_didout = FALSE;
995 		msg_col = 0;
996 	    }
997 #endif
998 	    vim_free(y_current->y_array[i]);
999 	}
1000 	VIM_CLEAR(y_current->y_array);
1001 #ifdef AMIGA
1002 	if (n >= 1000)
1003 	    msg("");
1004 #endif
1005     }
1006 }
1007 
1008     void
1009 free_yank_all(void)
1010 {
1011     free_yank(y_current->y_size);
1012 }
1013 
1014 /*
1015  * Yank the text between "oap->start" and "oap->end" into a yank register.
1016  * If we are to append (uppercase register), we first yank into a new yank
1017  * register and then concatenate the old and the new one (so we keep the old
1018  * one in case of out-of-memory).
1019  *
1020  * Return FAIL for failure, OK otherwise.
1021  */
1022     int
1023 op_yank(oparg_T *oap, int deleting, int mess)
1024 {
1025     long		y_idx;		// index in y_array[]
1026     yankreg_T		*curr;		// copy of y_current
1027     yankreg_T		newreg;		// new yank register when appending
1028     char_u		**new_ptr;
1029     linenr_T		lnum;		// current line number
1030     long		j;
1031     int			yanktype = oap->motion_type;
1032     long		yanklines = oap->line_count;
1033     linenr_T		yankendlnum = oap->end.lnum;
1034     char_u		*p;
1035     char_u		*pnew;
1036     struct block_def	bd;
1037 #if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1038     int			did_star = FALSE;
1039 #endif
1040 
1041 				    // check for read-only register
1042     if (oap->regname != 0 && !valid_yank_reg(oap->regname, TRUE))
1043     {
1044 	beep_flush();
1045 	return FAIL;
1046     }
1047     if (oap->regname == '_')	    // black hole: nothing to do
1048 	return OK;
1049 
1050 #ifdef FEAT_CLIPBOARD
1051     if (!clip_star.available && oap->regname == '*')
1052 	oap->regname = 0;
1053     else if (!clip_plus.available && oap->regname == '+')
1054 	oap->regname = 0;
1055 #endif
1056 
1057     if (!deleting)		    // op_delete() already set y_current
1058 	get_yank_register(oap->regname, TRUE);
1059 
1060     curr = y_current;
1061 				    // append to existing contents
1062     if (y_append && y_current->y_array != NULL)
1063 	y_current = &newreg;
1064     else
1065 	free_yank_all();	    // free previously yanked lines
1066 
1067     // If the cursor was in column 1 before and after the movement, and the
1068     // operator is not inclusive, the yank is always linewise.
1069     if (       oap->motion_type == MCHAR
1070 	    && oap->start.col == 0
1071 	    && !oap->inclusive
1072 	    && (!oap->is_VIsual || *p_sel == 'o')
1073 	    && !oap->block_mode
1074 	    && oap->end.col == 0
1075 	    && yanklines > 1)
1076     {
1077 	yanktype = MLINE;
1078 	--yankendlnum;
1079 	--yanklines;
1080     }
1081 
1082     y_current->y_size = yanklines;
1083     y_current->y_type = yanktype;   // set the yank register type
1084     y_current->y_width = 0;
1085     y_current->y_array = lalloc_clear(sizeof(char_u *) * yanklines, TRUE);
1086     if (y_current->y_array == NULL)
1087     {
1088 	y_current = curr;
1089 	return FAIL;
1090     }
1091 #ifdef FEAT_VIMINFO
1092     y_current->y_time_set = vim_time();
1093 #endif
1094 
1095     y_idx = 0;
1096     lnum = oap->start.lnum;
1097 
1098     if (oap->block_mode)
1099     {
1100 	// Visual block mode
1101 	y_current->y_type = MBLOCK;	    // set the yank register type
1102 	y_current->y_width = oap->end_vcol - oap->start_vcol;
1103 
1104 	if (curwin->w_curswant == MAXCOL && y_current->y_width > 0)
1105 	    y_current->y_width--;
1106     }
1107 
1108     for ( ; lnum <= yankendlnum; lnum++, y_idx++)
1109     {
1110 	switch (y_current->y_type)
1111 	{
1112 	    case MBLOCK:
1113 		block_prep(oap, &bd, lnum, FALSE);
1114 		if (yank_copy_line(&bd, y_idx) == FAIL)
1115 		    goto fail;
1116 		break;
1117 
1118 	    case MLINE:
1119 		if ((y_current->y_array[y_idx] =
1120 			    vim_strsave(ml_get(lnum))) == NULL)
1121 		    goto fail;
1122 		break;
1123 
1124 	    case MCHAR:
1125 		{
1126 		    colnr_T startcol = 0, endcol = MAXCOL;
1127 		    int is_oneChar = FALSE;
1128 		    colnr_T cs, ce;
1129 
1130 		    p = ml_get(lnum);
1131 		    bd.startspaces = 0;
1132 		    bd.endspaces = 0;
1133 
1134 		    if (lnum == oap->start.lnum)
1135 		    {
1136 			startcol = oap->start.col;
1137 			if (virtual_op)
1138 			{
1139 			    getvcol(curwin, &oap->start, &cs, NULL, &ce);
1140 			    if (ce != cs && oap->start.coladd > 0)
1141 			    {
1142 				// Part of a tab selected -- but don't
1143 				// double-count it.
1144 				bd.startspaces = (ce - cs + 1)
1145 							  - oap->start.coladd;
1146 				startcol++;
1147 			    }
1148 			}
1149 		    }
1150 
1151 		    if (lnum == oap->end.lnum)
1152 		    {
1153 			endcol = oap->end.col;
1154 			if (virtual_op)
1155 			{
1156 			    getvcol(curwin, &oap->end, &cs, NULL, &ce);
1157 			    if (p[endcol] == NUL || (cs + oap->end.coladd < ce
1158 					// Don't add space for double-wide
1159 					// char; endcol will be on last byte
1160 					// of multi-byte char.
1161 					&& (*mb_head_off)(p, p + endcol) == 0))
1162 			    {
1163 				if (oap->start.lnum == oap->end.lnum
1164 					    && oap->start.col == oap->end.col)
1165 				{
1166 				    // Special case: inside a single char
1167 				    is_oneChar = TRUE;
1168 				    bd.startspaces = oap->end.coladd
1169 					 - oap->start.coladd + oap->inclusive;
1170 				    endcol = startcol;
1171 				}
1172 				else
1173 				{
1174 				    bd.endspaces = oap->end.coladd
1175 							     + oap->inclusive;
1176 				    endcol -= oap->inclusive;
1177 				}
1178 			    }
1179 			}
1180 		    }
1181 		    if (endcol == MAXCOL)
1182 			endcol = (colnr_T)STRLEN(p);
1183 		    if (startcol > endcol || is_oneChar)
1184 			bd.textlen = 0;
1185 		    else
1186 			bd.textlen = endcol - startcol + oap->inclusive;
1187 		    bd.textstart = p + startcol;
1188 		    if (yank_copy_line(&bd, y_idx) == FAIL)
1189 			goto fail;
1190 		    break;
1191 		}
1192 		// NOTREACHED
1193 	}
1194     }
1195 
1196     if (curr != y_current)	// append the new block to the old block
1197     {
1198 	new_ptr = ALLOC_MULT(char_u *, curr->y_size + y_current->y_size);
1199 	if (new_ptr == NULL)
1200 	    goto fail;
1201 	for (j = 0; j < curr->y_size; ++j)
1202 	    new_ptr[j] = curr->y_array[j];
1203 	vim_free(curr->y_array);
1204 	curr->y_array = new_ptr;
1205 #ifdef FEAT_VIMINFO
1206 	curr->y_time_set = vim_time();
1207 #endif
1208 
1209 	if (yanktype == MLINE)	// MLINE overrides MCHAR and MBLOCK
1210 	    curr->y_type = MLINE;
1211 
1212 	// Concatenate the last line of the old block with the first line of
1213 	// the new block, unless being Vi compatible.
1214 	if (curr->y_type == MCHAR && vim_strchr(p_cpo, CPO_REGAPPEND) == NULL)
1215 	{
1216 	    pnew = alloc(STRLEN(curr->y_array[curr->y_size - 1])
1217 					  + STRLEN(y_current->y_array[0]) + 1);
1218 	    if (pnew == NULL)
1219 	    {
1220 		y_idx = y_current->y_size - 1;
1221 		goto fail;
1222 	    }
1223 	    STRCPY(pnew, curr->y_array[--j]);
1224 	    STRCAT(pnew, y_current->y_array[0]);
1225 	    vim_free(curr->y_array[j]);
1226 	    vim_free(y_current->y_array[0]);
1227 	    curr->y_array[j++] = pnew;
1228 	    y_idx = 1;
1229 	}
1230 	else
1231 	    y_idx = 0;
1232 	while (y_idx < y_current->y_size)
1233 	    curr->y_array[j++] = y_current->y_array[y_idx++];
1234 	curr->y_size = j;
1235 	vim_free(y_current->y_array);
1236 	y_current = curr;
1237     }
1238     if (curwin->w_p_rnu)
1239 	redraw_later(SOME_VALID);	// cursor moved to start
1240     if (mess)			// Display message about yank?
1241     {
1242 	if (yanktype == MCHAR
1243 		&& !oap->block_mode
1244 		&& yanklines == 1)
1245 	    yanklines = 0;
1246 	// Some versions of Vi use ">=" here, some don't...
1247 	if (yanklines > p_report)
1248 	{
1249 	    char namebuf[100];
1250 
1251 	    if (oap->regname == NUL)
1252 		*namebuf = NUL;
1253 	    else
1254 		vim_snprintf(namebuf, sizeof(namebuf),
1255 						_(" into \"%c"), oap->regname);
1256 
1257 	    // redisplay now, so message is not deleted
1258 	    update_topline_redraw();
1259 	    if (oap->block_mode)
1260 	    {
1261 		smsg(NGETTEXT("block of %ld line yanked%s",
1262 				     "block of %ld lines yanked%s", yanklines),
1263 			yanklines, namebuf);
1264 	    }
1265 	    else
1266 	    {
1267 		smsg(NGETTEXT("%ld line yanked%s",
1268 					      "%ld lines yanked%s", yanklines),
1269 			yanklines, namebuf);
1270 	    }
1271 	}
1272     }
1273 
1274     if (!cmdmod.lockmarks)
1275     {
1276 	// Set "'[" and "']" marks.
1277 	curbuf->b_op_start = oap->start;
1278 	curbuf->b_op_end = oap->end;
1279 	if (yanktype == MLINE && !oap->block_mode)
1280 	{
1281 	    curbuf->b_op_start.col = 0;
1282 	    curbuf->b_op_end.col = MAXCOL;
1283 	}
1284     }
1285 
1286 #ifdef FEAT_CLIPBOARD
1287     // If we were yanking to the '*' register, send result to clipboard.
1288     // If no register was specified, and "unnamed" in 'clipboard', make a copy
1289     // to the '*' register.
1290     if (clip_star.available
1291 	    && (curr == &(y_regs[STAR_REGISTER])
1292 		|| (!deleting && oap->regname == 0
1293 		   && ((clip_unnamed | clip_unnamed_saved) & CLIP_UNNAMED))))
1294     {
1295 	if (curr != &(y_regs[STAR_REGISTER]))
1296 	    // Copy the text from register 0 to the clipboard register.
1297 	    copy_yank_reg(&(y_regs[STAR_REGISTER]));
1298 
1299 	clip_own_selection(&clip_star);
1300 	clip_gen_set_selection(&clip_star);
1301 # ifdef FEAT_X11
1302 	did_star = TRUE;
1303 # endif
1304     }
1305 
1306 # ifdef FEAT_X11
1307     // If we were yanking to the '+' register, send result to selection.
1308     // Also copy to the '*' register, in case auto-select is off.
1309     if (clip_plus.available
1310 	    && (curr == &(y_regs[PLUS_REGISTER])
1311 		|| (!deleting && oap->regname == 0
1312 		  && ((clip_unnamed | clip_unnamed_saved) &
1313 		      CLIP_UNNAMED_PLUS))))
1314     {
1315 	if (curr != &(y_regs[PLUS_REGISTER]))
1316 	    // Copy the text from register 0 to the clipboard register.
1317 	    copy_yank_reg(&(y_regs[PLUS_REGISTER]));
1318 
1319 	clip_own_selection(&clip_plus);
1320 	clip_gen_set_selection(&clip_plus);
1321 	if (!clip_isautosel_star() && !clip_isautosel_plus()
1322 		&& !did_star && curr == &(y_regs[PLUS_REGISTER]))
1323 	{
1324 	    copy_yank_reg(&(y_regs[STAR_REGISTER]));
1325 	    clip_own_selection(&clip_star);
1326 	    clip_gen_set_selection(&clip_star);
1327 	}
1328     }
1329 # endif
1330 #endif
1331 
1332 #if defined(FEAT_EVAL)
1333     if (!deleting && has_textyankpost())
1334 	yank_do_autocmd(oap, y_current);
1335 #endif
1336 
1337     return OK;
1338 
1339 fail:		// free the allocated lines
1340     free_yank(y_idx + 1);
1341     y_current = curr;
1342     return FAIL;
1343 }
1344 
1345     static int
1346 yank_copy_line(struct block_def *bd, long y_idx)
1347 {
1348     char_u	*pnew;
1349 
1350     if ((pnew = alloc(bd->startspaces + bd->endspaces + bd->textlen + 1))
1351 								      == NULL)
1352 	return FAIL;
1353     y_current->y_array[y_idx] = pnew;
1354     vim_memset(pnew, ' ', (size_t)bd->startspaces);
1355     pnew += bd->startspaces;
1356     mch_memmove(pnew, bd->textstart, (size_t)bd->textlen);
1357     pnew += bd->textlen;
1358     vim_memset(pnew, ' ', (size_t)bd->endspaces);
1359     pnew += bd->endspaces;
1360     *pnew = NUL;
1361     return OK;
1362 }
1363 
1364 #ifdef FEAT_CLIPBOARD
1365 /*
1366  * Make a copy of the y_current register to register "reg".
1367  */
1368     static void
1369 copy_yank_reg(yankreg_T *reg)
1370 {
1371     yankreg_T	*curr = y_current;
1372     long	j;
1373 
1374     y_current = reg;
1375     free_yank_all();
1376     *y_current = *curr;
1377     y_current->y_array = lalloc_clear(
1378 				    sizeof(char_u *) * y_current->y_size, TRUE);
1379     if (y_current->y_array == NULL)
1380 	y_current->y_size = 0;
1381     else
1382 	for (j = 0; j < y_current->y_size; ++j)
1383 	    if ((y_current->y_array[j] = vim_strsave(curr->y_array[j])) == NULL)
1384 	    {
1385 		free_yank(j);
1386 		y_current->y_size = 0;
1387 		break;
1388 	    }
1389     y_current = curr;
1390 }
1391 #endif
1392 
1393 /*
1394  * Put contents of register "regname" into the text.
1395  * Caller must check "regname" to be valid!
1396  * "flags": PUT_FIXINDENT	make indent look nice
1397  *	    PUT_CURSEND		leave cursor after end of new text
1398  *	    PUT_LINE		force linewise put (":put")
1399  */
1400     void
1401 do_put(
1402     int		regname,
1403     int		dir,		// BACKWARD for 'P', FORWARD for 'p'
1404     long	count,
1405     int		flags)
1406 {
1407     char_u	*ptr;
1408     char_u	*newp, *oldp;
1409     int		yanklen;
1410     int		totlen = 0;		// init for gcc
1411     linenr_T	lnum;
1412     colnr_T	col;
1413     long	i;			// index in y_array[]
1414     int		y_type;
1415     long	y_size;
1416     int		oldlen;
1417     long	y_width = 0;
1418     colnr_T	vcol;
1419     int		delcount;
1420     int		incr = 0;
1421     long	j;
1422     struct block_def bd;
1423     char_u	**y_array = NULL;
1424     long	nr_lines = 0;
1425     pos_T	new_cursor;
1426     int		indent;
1427     int		orig_indent = 0;	// init for gcc
1428     int		indent_diff = 0;	// init for gcc
1429     int		first_indent = TRUE;
1430     int		lendiff = 0;
1431     pos_T	old_pos;
1432     char_u	*insert_string = NULL;
1433     int		allocated = FALSE;
1434     long	cnt;
1435     pos_T	orig_start = curbuf->b_op_start;
1436     pos_T	orig_end = curbuf->b_op_end;
1437 
1438 #ifdef FEAT_CLIPBOARD
1439     // Adjust register name for "unnamed" in 'clipboard'.
1440     adjust_clip_reg(&regname);
1441     (void)may_get_selection(regname);
1442 #endif
1443 
1444     if (flags & PUT_FIXINDENT)
1445 	orig_indent = get_indent();
1446 
1447     curbuf->b_op_start = curwin->w_cursor;	// default for '[ mark
1448     curbuf->b_op_end = curwin->w_cursor;	// default for '] mark
1449 
1450     // Using inserted text works differently, because the register includes
1451     // special characters (newlines, etc.).
1452     if (regname == '.')
1453     {
1454 	if (VIsual_active)
1455 	    stuffcharReadbuff(VIsual_mode);
1456 	(void)stuff_inserted((dir == FORWARD ? (count == -1 ? 'o' : 'a') :
1457 				    (count == -1 ? 'O' : 'i')), count, FALSE);
1458 	// Putting the text is done later, so can't really move the cursor to
1459 	// the next character.  Use "l" to simulate it.
1460 	if ((flags & PUT_CURSEND) && gchar_cursor() != NUL)
1461 	    stuffcharReadbuff('l');
1462 	return;
1463     }
1464 
1465     // For special registers '%' (file name), '#' (alternate file name) and
1466     // ':' (last command line), etc. we have to create a fake yank register.
1467     if (get_spec_reg(regname, &insert_string, &allocated, TRUE))
1468     {
1469 	if (insert_string == NULL)
1470 	    return;
1471     }
1472 
1473     // Autocommands may be executed when saving lines for undo.  This might
1474     // make "y_array" invalid, so we start undo now to avoid that.
1475     if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL)
1476 	goto end;
1477 
1478     if (insert_string != NULL)
1479     {
1480 	y_type = MCHAR;
1481 #ifdef FEAT_EVAL
1482 	if (regname == '=')
1483 	{
1484 	    // For the = register we need to split the string at NL
1485 	    // characters.
1486 	    // Loop twice: count the number of lines and save them.
1487 	    for (;;)
1488 	    {
1489 		y_size = 0;
1490 		ptr = insert_string;
1491 		while (ptr != NULL)
1492 		{
1493 		    if (y_array != NULL)
1494 			y_array[y_size] = ptr;
1495 		    ++y_size;
1496 		    ptr = vim_strchr(ptr, '\n');
1497 		    if (ptr != NULL)
1498 		    {
1499 			if (y_array != NULL)
1500 			    *ptr = NUL;
1501 			++ptr;
1502 			// A trailing '\n' makes the register linewise.
1503 			if (*ptr == NUL)
1504 			{
1505 			    y_type = MLINE;
1506 			    break;
1507 			}
1508 		    }
1509 		}
1510 		if (y_array != NULL)
1511 		    break;
1512 		y_array = ALLOC_MULT(char_u *, y_size);
1513 		if (y_array == NULL)
1514 		    goto end;
1515 	    }
1516 	}
1517 	else
1518 #endif
1519 	{
1520 	    y_size = 1;		// use fake one-line yank register
1521 	    y_array = &insert_string;
1522 	}
1523     }
1524     else
1525     {
1526 	get_yank_register(regname, FALSE);
1527 
1528 	y_type = y_current->y_type;
1529 	y_width = y_current->y_width;
1530 	y_size = y_current->y_size;
1531 	y_array = y_current->y_array;
1532     }
1533 
1534     if (y_type == MLINE)
1535     {
1536 	if (flags & PUT_LINE_SPLIT)
1537 	{
1538 	    char_u *p;
1539 
1540 	    // "p" or "P" in Visual mode: split the lines to put the text in
1541 	    // between.
1542 	    if (u_save_cursor() == FAIL)
1543 		goto end;
1544 	    p = ml_get_cursor();
1545 	    if (dir == FORWARD && *p != NUL)
1546 		MB_PTR_ADV(p);
1547 	    ptr = vim_strsave(p);
1548 	    if (ptr == NULL)
1549 		goto end;
1550 	    ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, FALSE);
1551 	    vim_free(ptr);
1552 
1553 	    oldp = ml_get_curline();
1554 	    p = oldp + curwin->w_cursor.col;
1555 	    if (dir == FORWARD && *p != NUL)
1556 		MB_PTR_ADV(p);
1557 	    ptr = vim_strnsave(oldp, p - oldp);
1558 	    if (ptr == NULL)
1559 		goto end;
1560 	    ml_replace(curwin->w_cursor.lnum, ptr, FALSE);
1561 	    ++nr_lines;
1562 	    dir = FORWARD;
1563 	}
1564 	if (flags & PUT_LINE_FORWARD)
1565 	{
1566 	    // Must be "p" for a Visual block, put lines below the block.
1567 	    curwin->w_cursor = curbuf->b_visual.vi_end;
1568 	    dir = FORWARD;
1569 	}
1570 	curbuf->b_op_start = curwin->w_cursor;	// default for '[ mark
1571 	curbuf->b_op_end = curwin->w_cursor;	// default for '] mark
1572     }
1573 
1574     if (flags & PUT_LINE)	// :put command or "p" in Visual line mode.
1575 	y_type = MLINE;
1576 
1577     if (y_size == 0 || y_array == NULL)
1578     {
1579 	semsg(_("E353: Nothing in register %s"),
1580 		  regname == 0 ? (char_u *)"\"" : transchar(regname));
1581 	goto end;
1582     }
1583 
1584     if (y_type == MBLOCK)
1585     {
1586 	lnum = curwin->w_cursor.lnum + y_size + 1;
1587 	if (lnum > curbuf->b_ml.ml_line_count)
1588 	    lnum = curbuf->b_ml.ml_line_count + 1;
1589 	if (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL)
1590 	    goto end;
1591     }
1592     else if (y_type == MLINE)
1593     {
1594 	lnum = curwin->w_cursor.lnum;
1595 #ifdef FEAT_FOLDING
1596 	// Correct line number for closed fold.  Don't move the cursor yet,
1597 	// u_save() uses it.
1598 	if (dir == BACKWARD)
1599 	    (void)hasFolding(lnum, &lnum, NULL);
1600 	else
1601 	    (void)hasFolding(lnum, NULL, &lnum);
1602 #endif
1603 	if (dir == FORWARD)
1604 	    ++lnum;
1605 	// In an empty buffer the empty line is going to be replaced, include
1606 	// it in the saved lines.
1607 	if ((BUFEMPTY() ? u_save(0, 2) : u_save(lnum - 1, lnum)) == FAIL)
1608 	    goto end;
1609 #ifdef FEAT_FOLDING
1610 	if (dir == FORWARD)
1611 	    curwin->w_cursor.lnum = lnum - 1;
1612 	else
1613 	    curwin->w_cursor.lnum = lnum;
1614 	curbuf->b_op_start = curwin->w_cursor;	// for mark_adjust()
1615 #endif
1616     }
1617     else if (u_save_cursor() == FAIL)
1618 	goto end;
1619 
1620     yanklen = (int)STRLEN(y_array[0]);
1621 
1622     if (ve_flags == VE_ALL && y_type == MCHAR)
1623     {
1624 	if (gchar_cursor() == TAB)
1625 	{
1626 	    int viscol = getviscol();
1627 	    int ts = curbuf->b_p_ts;
1628 
1629 	    // Don't need to insert spaces when "p" on the last position of a
1630 	    // tab or "P" on the first position.
1631 	    if (dir == FORWARD ?
1632 #ifdef FEAT_VARTABS
1633 		    tabstop_padding(viscol, ts, curbuf->b_p_vts_array) != 1
1634 #else
1635 		    ts - (viscol % ts) != 1
1636 #endif
1637 		    : curwin->w_cursor.coladd > 0)
1638 		coladvance_force(viscol);
1639 	    else
1640 		curwin->w_cursor.coladd = 0;
1641 	}
1642 	else if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)
1643 	    coladvance_force(getviscol() + (dir == FORWARD));
1644     }
1645 
1646     lnum = curwin->w_cursor.lnum;
1647     col = curwin->w_cursor.col;
1648 
1649     // Block mode
1650     if (y_type == MBLOCK)
1651     {
1652 	int	c = gchar_cursor();
1653 	colnr_T	endcol2 = 0;
1654 
1655 	if (dir == FORWARD && c != NUL)
1656 	{
1657 	    if (ve_flags == VE_ALL)
1658 		getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
1659 	    else
1660 		getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);
1661 
1662 	    if (has_mbyte)
1663 		// move to start of next multi-byte character
1664 		curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
1665 	    else
1666 	    if (c != TAB || ve_flags != VE_ALL)
1667 		++curwin->w_cursor.col;
1668 	    ++col;
1669 	}
1670 	else
1671 	    getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
1672 
1673 	col += curwin->w_cursor.coladd;
1674 	if (ve_flags == VE_ALL
1675 		&& (curwin->w_cursor.coladd > 0
1676 		    || endcol2 == curwin->w_cursor.col))
1677 	{
1678 	    if (dir == FORWARD && c == NUL)
1679 		++col;
1680 	    if (dir != FORWARD && c != NUL)
1681 		++curwin->w_cursor.col;
1682 	    if (c == TAB)
1683 	    {
1684 		if (dir == BACKWARD && curwin->w_cursor.col)
1685 		    curwin->w_cursor.col--;
1686 		if (dir == FORWARD && col - 1 == endcol2)
1687 		    curwin->w_cursor.col++;
1688 	    }
1689 	}
1690 	curwin->w_cursor.coladd = 0;
1691 	bd.textcol = 0;
1692 	for (i = 0; i < y_size; ++i)
1693 	{
1694 	    int spaces;
1695 	    char shortline;
1696 
1697 	    bd.startspaces = 0;
1698 	    bd.endspaces = 0;
1699 	    vcol = 0;
1700 	    delcount = 0;
1701 
1702 	    // add a new line
1703 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
1704 	    {
1705 		if (ml_append(curbuf->b_ml.ml_line_count, (char_u *)"",
1706 						   (colnr_T)1, FALSE) == FAIL)
1707 		    break;
1708 		++nr_lines;
1709 	    }
1710 	    // get the old line and advance to the position to insert at
1711 	    oldp = ml_get_curline();
1712 	    oldlen = (int)STRLEN(oldp);
1713 	    for (ptr = oldp; vcol < col && *ptr; )
1714 	    {
1715 		// Count a tab for what it's worth (if list mode not on)
1716 		incr = lbr_chartabsize_adv(oldp, &ptr, (colnr_T)vcol);
1717 		vcol += incr;
1718 	    }
1719 	    bd.textcol = (colnr_T)(ptr - oldp);
1720 
1721 	    shortline = (vcol < col) || (vcol == col && !*ptr) ;
1722 
1723 	    if (vcol < col) // line too short, padd with spaces
1724 		bd.startspaces = col - vcol;
1725 	    else if (vcol > col)
1726 	    {
1727 		bd.endspaces = vcol - col;
1728 		bd.startspaces = incr - bd.endspaces;
1729 		--bd.textcol;
1730 		delcount = 1;
1731 		if (has_mbyte)
1732 		    bd.textcol -= (*mb_head_off)(oldp, oldp + bd.textcol);
1733 		if (oldp[bd.textcol] != TAB)
1734 		{
1735 		    // Only a Tab can be split into spaces.  Other
1736 		    // characters will have to be moved to after the
1737 		    // block, causing misalignment.
1738 		    delcount = 0;
1739 		    bd.endspaces = 0;
1740 		}
1741 	    }
1742 
1743 	    yanklen = (int)STRLEN(y_array[i]);
1744 
1745 	    // calculate number of spaces required to fill right side of block
1746 	    spaces = y_width + 1;
1747 	    for (j = 0; j < yanklen; j++)
1748 		spaces -= lbr_chartabsize(NULL, &y_array[i][j], 0);
1749 	    if (spaces < 0)
1750 		spaces = 0;
1751 
1752 	    // insert the new text
1753 	    totlen = count * (yanklen + spaces) + bd.startspaces + bd.endspaces;
1754 	    newp = alloc(totlen + oldlen + 1);
1755 	    if (newp == NULL)
1756 		break;
1757 	    // copy part up to cursor to new line
1758 	    ptr = newp;
1759 	    mch_memmove(ptr, oldp, (size_t)bd.textcol);
1760 	    ptr += bd.textcol;
1761 	    // may insert some spaces before the new text
1762 	    vim_memset(ptr, ' ', (size_t)bd.startspaces);
1763 	    ptr += bd.startspaces;
1764 	    // insert the new text
1765 	    for (j = 0; j < count; ++j)
1766 	    {
1767 		mch_memmove(ptr, y_array[i], (size_t)yanklen);
1768 		ptr += yanklen;
1769 
1770 		// insert block's trailing spaces only if there's text behind
1771 		if ((j < count - 1 || !shortline) && spaces)
1772 		{
1773 		    vim_memset(ptr, ' ', (size_t)spaces);
1774 		    ptr += spaces;
1775 		}
1776 	    }
1777 	    // may insert some spaces after the new text
1778 	    vim_memset(ptr, ' ', (size_t)bd.endspaces);
1779 	    ptr += bd.endspaces;
1780 	    // move the text after the cursor to the end of the line.
1781 	    mch_memmove(ptr, oldp + bd.textcol + delcount,
1782 				(size_t)(oldlen - bd.textcol - delcount + 1));
1783 	    ml_replace(curwin->w_cursor.lnum, newp, FALSE);
1784 
1785 	    ++curwin->w_cursor.lnum;
1786 	    if (i == 0)
1787 		curwin->w_cursor.col += bd.startspaces;
1788 	}
1789 
1790 	changed_lines(lnum, 0, curwin->w_cursor.lnum, nr_lines);
1791 
1792 	// Set '[ mark.
1793 	curbuf->b_op_start = curwin->w_cursor;
1794 	curbuf->b_op_start.lnum = lnum;
1795 
1796 	// adjust '] mark
1797 	curbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;
1798 	curbuf->b_op_end.col = bd.textcol + totlen - 1;
1799 	curbuf->b_op_end.coladd = 0;
1800 	if (flags & PUT_CURSEND)
1801 	{
1802 	    colnr_T len;
1803 
1804 	    curwin->w_cursor = curbuf->b_op_end;
1805 	    curwin->w_cursor.col++;
1806 
1807 	    // in Insert mode we might be after the NUL, correct for that
1808 	    len = (colnr_T)STRLEN(ml_get_curline());
1809 	    if (curwin->w_cursor.col > len)
1810 		curwin->w_cursor.col = len;
1811 	}
1812 	else
1813 	    curwin->w_cursor.lnum = lnum;
1814     }
1815     else
1816     {
1817 	// Character or Line mode
1818 	if (y_type == MCHAR)
1819 	{
1820 	    // if type is MCHAR, FORWARD is the same as BACKWARD on the next
1821 	    // char
1822 	    if (dir == FORWARD && gchar_cursor() != NUL)
1823 	    {
1824 		if (has_mbyte)
1825 		{
1826 		    int bytelen = (*mb_ptr2len)(ml_get_cursor());
1827 
1828 		    // put it on the next of the multi-byte character.
1829 		    col += bytelen;
1830 		    if (yanklen)
1831 		    {
1832 			curwin->w_cursor.col += bytelen;
1833 			curbuf->b_op_end.col += bytelen;
1834 		    }
1835 		}
1836 		else
1837 		{
1838 		    ++col;
1839 		    if (yanklen)
1840 		    {
1841 			++curwin->w_cursor.col;
1842 			++curbuf->b_op_end.col;
1843 		    }
1844 		}
1845 	    }
1846 	    curbuf->b_op_start = curwin->w_cursor;
1847 	}
1848 	// Line mode: BACKWARD is the same as FORWARD on the previous line
1849 	else if (dir == BACKWARD)
1850 	    --lnum;
1851 	new_cursor = curwin->w_cursor;
1852 
1853 	// simple case: insert into current line
1854 	if (y_type == MCHAR && y_size == 1)
1855 	{
1856 	    linenr_T end_lnum = 0; // init for gcc
1857 
1858 	    if (VIsual_active)
1859 	    {
1860 		end_lnum = curbuf->b_visual.vi_end.lnum;
1861 		if (end_lnum < curbuf->b_visual.vi_start.lnum)
1862 		    end_lnum = curbuf->b_visual.vi_start.lnum;
1863 	    }
1864 
1865 	    do {
1866 		totlen = count * yanklen;
1867 		if (totlen > 0)
1868 		{
1869 		    oldp = ml_get(lnum);
1870 		    if (VIsual_active && col > (int)STRLEN(oldp))
1871 		    {
1872 			lnum++;
1873 			continue;
1874 		    }
1875 		    newp = alloc(STRLEN(oldp) + totlen + 1);
1876 		    if (newp == NULL)
1877 			goto end;	// alloc() gave an error message
1878 		    mch_memmove(newp, oldp, (size_t)col);
1879 		    ptr = newp + col;
1880 		    for (i = 0; i < count; ++i)
1881 		    {
1882 			mch_memmove(ptr, y_array[0], (size_t)yanklen);
1883 			ptr += yanklen;
1884 		    }
1885 		    STRMOVE(ptr, oldp + col);
1886 		    ml_replace(lnum, newp, FALSE);
1887 		    // Place cursor on last putted char.
1888 		    if (lnum == curwin->w_cursor.lnum)
1889 		    {
1890 			// make sure curwin->w_virtcol is updated
1891 			changed_cline_bef_curs();
1892 			curwin->w_cursor.col += (colnr_T)(totlen - 1);
1893 		    }
1894 		}
1895 		if (VIsual_active)
1896 		    lnum++;
1897 	    } while (VIsual_active && lnum <= end_lnum);
1898 
1899 	    if (VIsual_active) // reset lnum to the last visual line
1900 		lnum--;
1901 
1902 	    curbuf->b_op_end = curwin->w_cursor;
1903 	    // For "CTRL-O p" in Insert mode, put cursor after last char
1904 	    if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND)))
1905 		++curwin->w_cursor.col;
1906 	    changed_bytes(lnum, col);
1907 	}
1908 	else
1909 	{
1910 	    // Insert at least one line.  When y_type is MCHAR, break the first
1911 	    // line in two.
1912 	    for (cnt = 1; cnt <= count; ++cnt)
1913 	    {
1914 		i = 0;
1915 		if (y_type == MCHAR)
1916 		{
1917 		    // Split the current line in two at the insert position.
1918 		    // First insert y_array[size - 1] in front of second line.
1919 		    // Then append y_array[0] to first line.
1920 		    lnum = new_cursor.lnum;
1921 		    ptr = ml_get(lnum) + col;
1922 		    totlen = (int)STRLEN(y_array[y_size - 1]);
1923 		    newp = alloc(STRLEN(ptr) + totlen + 1);
1924 		    if (newp == NULL)
1925 			goto error;
1926 		    STRCPY(newp, y_array[y_size - 1]);
1927 		    STRCAT(newp, ptr);
1928 		    // insert second line
1929 		    ml_append(lnum, newp, (colnr_T)0, FALSE);
1930 		    vim_free(newp);
1931 
1932 		    oldp = ml_get(lnum);
1933 		    newp = alloc(col + yanklen + 1);
1934 		    if (newp == NULL)
1935 			goto error;
1936 					    // copy first part of line
1937 		    mch_memmove(newp, oldp, (size_t)col);
1938 					    // append to first line
1939 		    mch_memmove(newp + col, y_array[0], (size_t)(yanklen + 1));
1940 		    ml_replace(lnum, newp, FALSE);
1941 
1942 		    curwin->w_cursor.lnum = lnum;
1943 		    i = 1;
1944 		}
1945 
1946 		for (; i < y_size; ++i)
1947 		{
1948 		    if ((y_type != MCHAR || i < y_size - 1)
1949 			    && ml_append(lnum, y_array[i], (colnr_T)0, FALSE)
1950 								      == FAIL)
1951 			    goto error;
1952 		    lnum++;
1953 		    ++nr_lines;
1954 		    if (flags & PUT_FIXINDENT)
1955 		    {
1956 			old_pos = curwin->w_cursor;
1957 			curwin->w_cursor.lnum = lnum;
1958 			ptr = ml_get(lnum);
1959 			if (cnt == count && i == y_size - 1)
1960 			    lendiff = (int)STRLEN(ptr);
1961 #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
1962 			if (*ptr == '#' && preprocs_left())
1963 			    indent = 0;     // Leave # lines at start
1964 			else
1965 #endif
1966 			     if (*ptr == NUL)
1967 			    indent = 0;     // Ignore empty lines
1968 			else if (first_indent)
1969 			{
1970 			    indent_diff = orig_indent - get_indent();
1971 			    indent = orig_indent;
1972 			    first_indent = FALSE;
1973 			}
1974 			else if ((indent = get_indent() + indent_diff) < 0)
1975 			    indent = 0;
1976 			(void)set_indent(indent, 0);
1977 			curwin->w_cursor = old_pos;
1978 			// remember how many chars were removed
1979 			if (cnt == count && i == y_size - 1)
1980 			    lendiff -= (int)STRLEN(ml_get(lnum));
1981 		    }
1982 		}
1983 	    }
1984 
1985 error:
1986 	    // Adjust marks.
1987 	    if (y_type == MLINE)
1988 	    {
1989 		curbuf->b_op_start.col = 0;
1990 		if (dir == FORWARD)
1991 		    curbuf->b_op_start.lnum++;
1992 	    }
1993 	    // Skip mark_adjust when adding lines after the last one, there
1994 	    // can't be marks there. But still needed in diff mode.
1995 	    if (curbuf->b_op_start.lnum + (y_type == MCHAR) - 1 + nr_lines
1996 						 < curbuf->b_ml.ml_line_count
1997 #ifdef FEAT_DIFF
1998 						 || curwin->w_p_diff
1999 #endif
2000 						 )
2001 		mark_adjust(curbuf->b_op_start.lnum + (y_type == MCHAR),
2002 					     (linenr_T)MAXLNUM, nr_lines, 0L);
2003 
2004 	    // note changed text for displaying and folding
2005 	    if (y_type == MCHAR)
2006 		changed_lines(curwin->w_cursor.lnum, col,
2007 					 curwin->w_cursor.lnum + 1, nr_lines);
2008 	    else
2009 		changed_lines(curbuf->b_op_start.lnum, 0,
2010 					   curbuf->b_op_start.lnum, nr_lines);
2011 
2012 	    // put '] mark at last inserted character
2013 	    curbuf->b_op_end.lnum = lnum;
2014 	    // correct length for change in indent
2015 	    col = (colnr_T)STRLEN(y_array[y_size - 1]) - lendiff;
2016 	    if (col > 1)
2017 		curbuf->b_op_end.col = col - 1;
2018 	    else
2019 		curbuf->b_op_end.col = 0;
2020 
2021 	    if (flags & PUT_CURSLINE)
2022 	    {
2023 		// ":put": put cursor on last inserted line
2024 		curwin->w_cursor.lnum = lnum;
2025 		beginline(BL_WHITE | BL_FIX);
2026 	    }
2027 	    else if (flags & PUT_CURSEND)
2028 	    {
2029 		// put cursor after inserted text
2030 		if (y_type == MLINE)
2031 		{
2032 		    if (lnum >= curbuf->b_ml.ml_line_count)
2033 			curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
2034 		    else
2035 			curwin->w_cursor.lnum = lnum + 1;
2036 		    curwin->w_cursor.col = 0;
2037 		}
2038 		else
2039 		{
2040 		    curwin->w_cursor.lnum = lnum;
2041 		    curwin->w_cursor.col = col;
2042 		}
2043 	    }
2044 	    else if (y_type == MLINE)
2045 	    {
2046 		// put cursor on first non-blank in first inserted line
2047 		curwin->w_cursor.col = 0;
2048 		if (dir == FORWARD)
2049 		    ++curwin->w_cursor.lnum;
2050 		beginline(BL_WHITE | BL_FIX);
2051 	    }
2052 	    else	// put cursor on first inserted character
2053 		curwin->w_cursor = new_cursor;
2054 	}
2055     }
2056 
2057     msgmore(nr_lines);
2058     curwin->w_set_curswant = TRUE;
2059 
2060 end:
2061     if (cmdmod.lockmarks)
2062     {
2063 	curbuf->b_op_start = orig_start;
2064 	curbuf->b_op_end = orig_end;
2065     }
2066     if (allocated)
2067 	vim_free(insert_string);
2068     if (regname == '=')
2069 	vim_free(y_array);
2070 
2071     VIsual_active = FALSE;
2072 
2073     // If the cursor is past the end of the line put it at the end.
2074     adjust_cursor_eol();
2075 }
2076 
2077 /*
2078  * Return the character name of the register with the given number.
2079  */
2080     int
2081 get_register_name(int num)
2082 {
2083     if (num == -1)
2084 	return '"';
2085     else if (num < 10)
2086 	return num + '0';
2087     else if (num == DELETION_REGISTER)
2088 	return '-';
2089 #ifdef FEAT_CLIPBOARD
2090     else if (num == STAR_REGISTER)
2091 	return '*';
2092     else if (num == PLUS_REGISTER)
2093 	return '+';
2094 #endif
2095     else
2096     {
2097 #ifdef EBCDIC
2098 	int i;
2099 
2100 	// EBCDIC is really braindead ...
2101 	i = 'a' + (num - 10);
2102 	if (i > 'i')
2103 	    i += 7;
2104 	if (i > 'r')
2105 	    i += 8;
2106 	return i;
2107 #else
2108 	return num + 'a' - 10;
2109 #endif
2110     }
2111 }
2112 
2113 /*
2114  * ":dis" and ":registers": Display the contents of the yank registers.
2115  */
2116     void
2117 ex_display(exarg_T *eap)
2118 {
2119     int		i, n;
2120     long	j;
2121     char_u	*p;
2122     yankreg_T	*yb;
2123     int		name;
2124     int		attr;
2125     char_u	*arg = eap->arg;
2126     int		clen;
2127     int		type;
2128 
2129     if (arg != NULL && *arg == NUL)
2130 	arg = NULL;
2131     attr = HL_ATTR(HLF_8);
2132 
2133     // Highlight title
2134     msg_puts_title(_("\nType Name Content"));
2135     for (i = -1; i < NUM_REGISTERS && !got_int; ++i)
2136     {
2137 	name = get_register_name(i);
2138 	switch (get_reg_type(name, NULL))
2139 	{
2140 	    case MLINE: type = 'l'; break;
2141 	    case MCHAR: type = 'c'; break;
2142 	    default:	type = 'b'; break;
2143 	}
2144 	if (arg != NULL && vim_strchr(arg, name) == NULL
2145 #ifdef ONE_CLIPBOARD
2146 	    // Star register and plus register contain the same thing.
2147 		&& (name != '*' || vim_strchr(arg, '+') == NULL)
2148 #endif
2149 		)
2150 	    continue;	    // did not ask for this register
2151 
2152 #ifdef FEAT_CLIPBOARD
2153 	// Adjust register name for "unnamed" in 'clipboard'.
2154 	// When it's a clipboard register, fill it with the current contents
2155 	// of the clipboard.
2156 	adjust_clip_reg(&name);
2157 	(void)may_get_selection(name);
2158 #endif
2159 
2160 	if (i == -1)
2161 	{
2162 	    if (y_previous != NULL)
2163 		yb = y_previous;
2164 	    else
2165 		yb = &(y_regs[0]);
2166 	}
2167 	else
2168 	    yb = &(y_regs[i]);
2169 
2170 #ifdef FEAT_EVAL
2171 	if (name == MB_TOLOWER(redir_reg)
2172 		|| (redir_reg == '"' && yb == y_previous))
2173 	    continue;	    // do not list register being written to, the
2174 			    // pointer can be freed
2175 #endif
2176 
2177 	if (yb->y_array != NULL)
2178 	{
2179 	    int do_show = FALSE;
2180 
2181 	    for (j = 0; !do_show && j < yb->y_size; ++j)
2182 		do_show = !message_filtered(yb->y_array[j]);
2183 
2184 	    if (do_show || yb->y_size == 0)
2185 	    {
2186 		msg_putchar('\n');
2187 		msg_puts("  ");
2188 		msg_putchar(type);
2189 		msg_puts("  ");
2190 		msg_putchar('"');
2191 		msg_putchar(name);
2192 		msg_puts("   ");
2193 
2194 		n = (int)Columns - 11;
2195 		for (j = 0; j < yb->y_size && n > 1; ++j)
2196 		{
2197 		    if (j)
2198 		    {
2199 			msg_puts_attr("^J", attr);
2200 			n -= 2;
2201 		    }
2202 		    for (p = yb->y_array[j]; *p && (n -= ptr2cells(p)) >= 0;
2203 									   ++p)
2204 		    {
2205 			clen = (*mb_ptr2len)(p);
2206 			msg_outtrans_len(p, clen);
2207 			p += clen - 1;
2208 		    }
2209 		}
2210 		if (n > 1 && yb->y_type == MLINE)
2211 		    msg_puts_attr("^J", attr);
2212 		out_flush();		    // show one line at a time
2213 	    }
2214 	    ui_breakcheck();
2215 	}
2216     }
2217 
2218     // display last inserted text
2219     if ((p = get_last_insert()) != NULL
2220 		  && (arg == NULL || vim_strchr(arg, '.') != NULL) && !got_int
2221 						      && !message_filtered(p))
2222     {
2223 	msg_puts("\n  c  \".   ");
2224 	dis_msg(p, TRUE);
2225     }
2226 
2227     // display last command line
2228     if (last_cmdline != NULL && (arg == NULL || vim_strchr(arg, ':') != NULL)
2229 			       && !got_int && !message_filtered(last_cmdline))
2230     {
2231 	msg_puts("\n  c  \":   ");
2232 	dis_msg(last_cmdline, FALSE);
2233     }
2234 
2235     // display current file name
2236     if (curbuf->b_fname != NULL
2237 	    && (arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int
2238 					&& !message_filtered(curbuf->b_fname))
2239     {
2240 	msg_puts("\n  c  \"%   ");
2241 	dis_msg(curbuf->b_fname, FALSE);
2242     }
2243 
2244     // display alternate file name
2245     if ((arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int)
2246     {
2247 	char_u	    *fname;
2248 	linenr_T    dummy;
2249 
2250 	if (buflist_name_nr(0, &fname, &dummy) != FAIL
2251 						  && !message_filtered(fname))
2252 	{
2253 	    msg_puts("\n  c  \"#   ");
2254 	    dis_msg(fname, FALSE);
2255 	}
2256     }
2257 
2258     // display last search pattern
2259     if (last_search_pat() != NULL
2260 		 && (arg == NULL || vim_strchr(arg, '/') != NULL) && !got_int
2261 				      && !message_filtered(last_search_pat()))
2262     {
2263 	msg_puts("\n  c  \"/   ");
2264 	dis_msg(last_search_pat(), FALSE);
2265     }
2266 
2267 #ifdef FEAT_EVAL
2268     // display last used expression
2269     if (expr_line != NULL && (arg == NULL || vim_strchr(arg, '=') != NULL)
2270 				  && !got_int && !message_filtered(expr_line))
2271     {
2272 	msg_puts("\n  c  \"=   ");
2273 	dis_msg(expr_line, FALSE);
2274     }
2275 #endif
2276 }
2277 
2278 /*
2279  * display a string for do_dis()
2280  * truncate at end of screen line
2281  */
2282     static void
2283 dis_msg(
2284     char_u	*p,
2285     int		skip_esc)	    // if TRUE, ignore trailing ESC
2286 {
2287     int		n;
2288     int		l;
2289 
2290     n = (int)Columns - 6;
2291     while (*p != NUL
2292 	    && !(*p == ESC && skip_esc && *(p + 1) == NUL)
2293 	    && (n -= ptr2cells(p)) >= 0)
2294     {
2295 	if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
2296 	{
2297 	    msg_outtrans_len(p, l);
2298 	    p += l;
2299 	}
2300 	else
2301 	    msg_outtrans_len(p++, 1);
2302     }
2303     ui_breakcheck();
2304 }
2305 
2306 #if defined(FEAT_DND) || defined(PROTO)
2307 /*
2308  * Replace the contents of the '~' register with str.
2309  */
2310     void
2311 dnd_yank_drag_data(char_u *str, long len)
2312 {
2313     yankreg_T *curr;
2314 
2315     curr = y_current;
2316     y_current = &y_regs[TILDE_REGISTER];
2317     free_yank_all();
2318     str_to_reg(y_current, MCHAR, str, len, 0L, FALSE);
2319     y_current = curr;
2320 }
2321 #endif
2322 
2323 
2324 /*
2325  * Return the type of a register.
2326  * Used for getregtype()
2327  * Returns MAUTO for error.
2328  */
2329     char_u
2330 get_reg_type(int regname, long *reglen)
2331 {
2332     switch (regname)
2333     {
2334 	case '%':		// file name
2335 	case '#':		// alternate file name
2336 	case '=':		// expression
2337 	case ':':		// last command line
2338 	case '/':		// last search-pattern
2339 	case '.':		// last inserted text
2340 # ifdef FEAT_SEARCHPATH
2341 	case Ctrl_F:		// Filename under cursor
2342 	case Ctrl_P:		// Path under cursor, expand via "path"
2343 # endif
2344 	case Ctrl_W:		// word under cursor
2345 	case Ctrl_A:		// WORD (mnemonic All) under cursor
2346 	case '_':		// black hole: always empty
2347 	    return MCHAR;
2348     }
2349 
2350 # ifdef FEAT_CLIPBOARD
2351     regname = may_get_selection(regname);
2352 # endif
2353 
2354     if (regname != NUL && !valid_yank_reg(regname, FALSE))
2355 	return MAUTO;
2356 
2357     get_yank_register(regname, FALSE);
2358 
2359     if (y_current->y_array != NULL)
2360     {
2361 	if (reglen != NULL && y_current->y_type == MBLOCK)
2362 	    *reglen = y_current->y_width;
2363 	return y_current->y_type;
2364     }
2365     return MAUTO;
2366 }
2367 
2368 #if defined(FEAT_EVAL) || defined(PROTO)
2369 /*
2370  * When "flags" has GREG_LIST return a list with text "s".
2371  * Otherwise just return "s".
2372  */
2373     static char_u *
2374 getreg_wrap_one_line(char_u *s, int flags)
2375 {
2376     if (flags & GREG_LIST)
2377     {
2378 	list_T *list = list_alloc();
2379 
2380 	if (list != NULL)
2381 	{
2382 	    if (list_append_string(list, NULL, -1) == FAIL)
2383 	    {
2384 		list_free(list);
2385 		return NULL;
2386 	    }
2387 	    list->lv_first->li_tv.vval.v_string = s;
2388 	}
2389 	return (char_u *)list;
2390     }
2391     return s;
2392 }
2393 
2394 /*
2395  * Return the contents of a register as a single allocated string or as a list.
2396  * Used for "@r" in expressions and for getreg().
2397  * Returns NULL for error.
2398  * Flags:
2399  *	GREG_NO_EXPR	Do not allow expression register
2400  *	GREG_EXPR_SRC	For the expression register: return expression itself,
2401  *			not the result of its evaluation.
2402  *	GREG_LIST	Return a list of lines instead of a single string.
2403  */
2404     char_u *
2405 get_reg_contents(int regname, int flags)
2406 {
2407     long	i;
2408     char_u	*retval;
2409     int		allocated;
2410     long	len;
2411 
2412     // Don't allow using an expression register inside an expression
2413     if (regname == '=')
2414     {
2415 	if (flags & GREG_NO_EXPR)
2416 	    return NULL;
2417 	if (flags & GREG_EXPR_SRC)
2418 	    return getreg_wrap_one_line(get_expr_line_src(), flags);
2419 	return getreg_wrap_one_line(get_expr_line(), flags);
2420     }
2421 
2422     if (regname == '@')	    // "@@" is used for unnamed register
2423 	regname = '"';
2424 
2425     // check for valid regname
2426     if (regname != NUL && !valid_yank_reg(regname, FALSE))
2427 	return NULL;
2428 
2429 # ifdef FEAT_CLIPBOARD
2430     regname = may_get_selection(regname);
2431 # endif
2432 
2433     if (get_spec_reg(regname, &retval, &allocated, FALSE))
2434     {
2435 	if (retval == NULL)
2436 	    return NULL;
2437 	if (allocated)
2438 	    return getreg_wrap_one_line(retval, flags);
2439 	return getreg_wrap_one_line(vim_strsave(retval), flags);
2440     }
2441 
2442     get_yank_register(regname, FALSE);
2443     if (y_current->y_array == NULL)
2444 	return NULL;
2445 
2446     if (flags & GREG_LIST)
2447     {
2448 	list_T	*list = list_alloc();
2449 	int	error = FALSE;
2450 
2451 	if (list == NULL)
2452 	    return NULL;
2453 	for (i = 0; i < y_current->y_size; ++i)
2454 	    if (list_append_string(list, y_current->y_array[i], -1) == FAIL)
2455 		error = TRUE;
2456 	if (error)
2457 	{
2458 	    list_free(list);
2459 	    return NULL;
2460 	}
2461 	return (char_u *)list;
2462     }
2463 
2464     // Compute length of resulting string.
2465     len = 0;
2466     for (i = 0; i < y_current->y_size; ++i)
2467     {
2468 	len += (long)STRLEN(y_current->y_array[i]);
2469 	// Insert a newline between lines and after last line if
2470 	// y_type is MLINE.
2471 	if (y_current->y_type == MLINE || i < y_current->y_size - 1)
2472 	    ++len;
2473     }
2474 
2475     retval = alloc(len + 1);
2476 
2477     // Copy the lines of the yank register into the string.
2478     if (retval != NULL)
2479     {
2480 	len = 0;
2481 	for (i = 0; i < y_current->y_size; ++i)
2482 	{
2483 	    STRCPY(retval + len, y_current->y_array[i]);
2484 	    len += (long)STRLEN(retval + len);
2485 
2486 	    // Insert a NL between lines and after the last line if y_type is
2487 	    // MLINE.
2488 	    if (y_current->y_type == MLINE || i < y_current->y_size - 1)
2489 		retval[len++] = '\n';
2490 	}
2491 	retval[len] = NUL;
2492     }
2493 
2494     return retval;
2495 }
2496 
2497     static int
2498 init_write_reg(
2499     int		name,
2500     yankreg_T	**old_y_previous,
2501     yankreg_T	**old_y_current,
2502     int		must_append,
2503     int		*yank_type UNUSED)
2504 {
2505     if (!valid_yank_reg(name, TRUE))	    // check for valid reg name
2506     {
2507 	emsg_invreg(name);
2508 	return FAIL;
2509     }
2510 
2511     // Don't want to change the current (unnamed) register
2512     *old_y_previous = y_previous;
2513     *old_y_current = y_current;
2514 
2515     get_yank_register(name, TRUE);
2516     if (!y_append && !must_append)
2517 	free_yank_all();
2518     return OK;
2519 }
2520 
2521     static void
2522 finish_write_reg(
2523     int		name,
2524     yankreg_T	*old_y_previous,
2525     yankreg_T	*old_y_current)
2526 {
2527 # ifdef FEAT_CLIPBOARD
2528     // Send text of clipboard register to the clipboard.
2529     may_set_selection();
2530 # endif
2531 
2532     // ':let @" = "val"' should change the meaning of the "" register
2533     if (name != '"')
2534 	y_previous = old_y_previous;
2535     y_current = old_y_current;
2536 }
2537 
2538 /*
2539  * Store string "str" in register "name".
2540  * "maxlen" is the maximum number of bytes to use, -1 for all bytes.
2541  * If "must_append" is TRUE, always append to the register.  Otherwise append
2542  * if "name" is an uppercase letter.
2543  * Note: "maxlen" and "must_append" don't work for the "/" register.
2544  * Careful: 'str' is modified, you may have to use a copy!
2545  * If "str" ends in '\n' or '\r', use linewise, otherwise use characterwise.
2546  */
2547     void
2548 write_reg_contents(
2549     int		name,
2550     char_u	*str,
2551     int		maxlen,
2552     int		must_append)
2553 {
2554     write_reg_contents_ex(name, str, maxlen, must_append, MAUTO, 0L);
2555 }
2556 
2557     void
2558 write_reg_contents_lst(
2559     int		name,
2560     char_u	**strings,
2561     int		maxlen UNUSED,
2562     int		must_append,
2563     int		yank_type,
2564     long	block_len)
2565 {
2566     yankreg_T  *old_y_previous, *old_y_current;
2567 
2568     if (name == '/' || name == '=')
2569     {
2570 	char_u	*s;
2571 
2572 	if (strings[0] == NULL)
2573 	    s = (char_u *)"";
2574 	else if (strings[1] != NULL)
2575 	{
2576 	    emsg(_("E883: search pattern and expression register may not "
2577 			"contain two or more lines"));
2578 	    return;
2579 	}
2580 	else
2581 	    s = strings[0];
2582 	write_reg_contents_ex(name, s, -1, must_append, yank_type, block_len);
2583 	return;
2584     }
2585 
2586     if (name == '_')	    // black hole: nothing to do
2587 	return;
2588 
2589     if (init_write_reg(name, &old_y_previous, &old_y_current, must_append,
2590 		&yank_type) == FAIL)
2591 	return;
2592 
2593     str_to_reg(y_current, yank_type, (char_u *) strings, -1, block_len, TRUE);
2594 
2595     finish_write_reg(name, old_y_previous, old_y_current);
2596 }
2597 
2598     void
2599 write_reg_contents_ex(
2600     int		name,
2601     char_u	*str,
2602     int		maxlen,
2603     int		must_append,
2604     int		yank_type,
2605     long	block_len)
2606 {
2607     yankreg_T	*old_y_previous, *old_y_current;
2608     long	len;
2609 
2610     if (maxlen >= 0)
2611 	len = maxlen;
2612     else
2613 	len = (long)STRLEN(str);
2614 
2615     // Special case: '/' search pattern
2616     if (name == '/')
2617     {
2618 	set_last_search_pat(str, RE_SEARCH, TRUE, TRUE);
2619 	return;
2620     }
2621 
2622     if (name == '#')
2623     {
2624 	buf_T	*buf;
2625 
2626 	if (VIM_ISDIGIT(*str))
2627 	{
2628 	    int	num = atoi((char *)str);
2629 
2630 	    buf = buflist_findnr(num);
2631 	    if (buf == NULL)
2632 		semsg(_(e_nobufnr), (long)num);
2633 	}
2634 	else
2635 	    buf = buflist_findnr(buflist_findpat(str, str + STRLEN(str),
2636 							 TRUE, FALSE, FALSE));
2637 	if (buf == NULL)
2638 	    return;
2639 	curwin->w_alt_fnum = buf->b_fnum;
2640 	return;
2641     }
2642 
2643     if (name == '=')
2644     {
2645 	char_u	    *p, *s;
2646 
2647 	p = vim_strnsave(str, (int)len);
2648 	if (p == NULL)
2649 	    return;
2650 	if (must_append && expr_line != NULL)
2651 	{
2652 	    s = concat_str(expr_line, p);
2653 	    vim_free(p);
2654 	    p = s;
2655 	}
2656 	set_expr_line(p);
2657 	return;
2658     }
2659 
2660     if (name == '_')	    // black hole: nothing to do
2661 	return;
2662 
2663     if (init_write_reg(name, &old_y_previous, &old_y_current, must_append,
2664 		&yank_type) == FAIL)
2665 	return;
2666 
2667     str_to_reg(y_current, yank_type, str, len, block_len, FALSE);
2668 
2669     finish_write_reg(name, old_y_previous, old_y_current);
2670 }
2671 #endif	// FEAT_EVAL
2672 
2673 #if defined(FEAT_CLIPBOARD) || defined(FEAT_EVAL)
2674 /*
2675  * Put a string into a register.  When the register is not empty, the string
2676  * is appended.
2677  */
2678     void
2679 str_to_reg(
2680     yankreg_T	*y_ptr,		// pointer to yank register
2681     int		yank_type,	// MCHAR, MLINE, MBLOCK, MAUTO
2682     char_u	*str,		// string to put in register
2683     long	len,		// length of string
2684     long	blocklen,	// width of Visual block
2685     int		str_list)	// TRUE if str is char_u **
2686 {
2687     int		type;			// MCHAR, MLINE or MBLOCK
2688     int		lnum;
2689     long	start;
2690     long	i;
2691     int		extra;
2692     int		newlines;		// number of lines added
2693     int		extraline = 0;		// extra line at the end
2694     int		append = FALSE;		// append to last line in register
2695     char_u	*s;
2696     char_u	**ss;
2697     char_u	**pp;
2698     long	maxlen;
2699 
2700     if (y_ptr->y_array == NULL)		// NULL means empty register
2701 	y_ptr->y_size = 0;
2702 
2703     if (yank_type == MAUTO)
2704 	type = ((str_list || (len > 0 && (str[len - 1] == NL
2705 					    || str[len - 1] == CAR)))
2706 							     ? MLINE : MCHAR);
2707     else
2708 	type = yank_type;
2709 
2710     // Count the number of lines within the string
2711     newlines = 0;
2712     if (str_list)
2713     {
2714 	for (ss = (char_u **) str; *ss != NULL; ++ss)
2715 	    ++newlines;
2716     }
2717     else
2718     {
2719 	for (i = 0; i < len; i++)
2720 	    if (str[i] == '\n')
2721 		++newlines;
2722 	if (type == MCHAR || len == 0 || str[len - 1] != '\n')
2723 	{
2724 	    extraline = 1;
2725 	    ++newlines;	// count extra newline at the end
2726 	}
2727 	if (y_ptr->y_size > 0 && y_ptr->y_type == MCHAR)
2728 	{
2729 	    append = TRUE;
2730 	    --newlines;	// uncount newline when appending first line
2731 	}
2732     }
2733 
2734     // Without any lines make the register empty.
2735     if (y_ptr->y_size + newlines == 0)
2736     {
2737 	VIM_CLEAR(y_ptr->y_array);
2738 	return;
2739     }
2740 
2741     // Allocate an array to hold the pointers to the new register lines.
2742     // If the register was not empty, move the existing lines to the new array.
2743     pp = lalloc_clear((y_ptr->y_size + newlines) * sizeof(char_u *), TRUE);
2744     if (pp == NULL)	// out of memory
2745 	return;
2746     for (lnum = 0; lnum < y_ptr->y_size; ++lnum)
2747 	pp[lnum] = y_ptr->y_array[lnum];
2748     vim_free(y_ptr->y_array);
2749     y_ptr->y_array = pp;
2750     maxlen = 0;
2751 
2752     // Find the end of each line and save it into the array.
2753     if (str_list)
2754     {
2755 	for (ss = (char_u **) str; *ss != NULL; ++ss, ++lnum)
2756 	{
2757 	    i = (long)STRLEN(*ss);
2758 	    pp[lnum] = vim_strnsave(*ss, i);
2759 	    if (i > maxlen)
2760 		maxlen = i;
2761 	}
2762     }
2763     else
2764     {
2765 	for (start = 0; start < len + extraline; start += i + 1)
2766 	{
2767 	    for (i = start; i < len; ++i)	// find the end of the line
2768 		if (str[i] == '\n')
2769 		    break;
2770 	    i -= start;			// i is now length of line
2771 	    if (i > maxlen)
2772 		maxlen = i;
2773 	    if (append)
2774 	    {
2775 		--lnum;
2776 		extra = (int)STRLEN(y_ptr->y_array[lnum]);
2777 	    }
2778 	    else
2779 		extra = 0;
2780 	    s = alloc(i + extra + 1);
2781 	    if (s == NULL)
2782 		break;
2783 	    if (extra)
2784 		mch_memmove(s, y_ptr->y_array[lnum], (size_t)extra);
2785 	    if (append)
2786 		vim_free(y_ptr->y_array[lnum]);
2787 	    if (i)
2788 		mch_memmove(s + extra, str + start, (size_t)i);
2789 	    extra += i;
2790 	    s[extra] = NUL;
2791 	    y_ptr->y_array[lnum++] = s;
2792 	    while (--extra >= 0)
2793 	    {
2794 		if (*s == NUL)
2795 		    *s = '\n';	    // replace NUL with newline
2796 		++s;
2797 	    }
2798 	    append = FALSE;		    // only first line is appended
2799 	}
2800     }
2801     y_ptr->y_type = type;
2802     y_ptr->y_size = lnum;
2803     if (type == MBLOCK)
2804 	y_ptr->y_width = (blocklen < 0 ? maxlen - 1 : blocklen);
2805     else
2806 	y_ptr->y_width = 0;
2807 # ifdef FEAT_VIMINFO
2808     y_ptr->y_time_set = vim_time();
2809 # endif
2810 }
2811 #endif // FEAT_CLIPBOARD || FEAT_EVAL || PROTO
2812