blob: 58494d4d0a2732c2e1c449eb076f875c8316fdcc [file] [log] [blame]
Bram Moolenaardefa0672019-07-21 19:25:37 +02001/* 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 * viminfo.c: viminfo related functions
12 */
13
14#include "vim.h"
15#include "version.h"
16
Bram Moolenaar6bd1d772019-10-09 22:01:25 +020017/*
18 * Structure used for reading from the viminfo file.
19 */
20typedef struct
21{
22 char_u *vir_line; // text of the current line
23 FILE *vir_fd; // file descriptor
24 vimconv_T vir_conv; // encoding conversion
25 int vir_version; // viminfo version detected or -1
26 garray_T vir_barlines; // lines starting with |
27} vir_T;
28
Bram Moolenaar408030e2020-02-10 22:44:32 +010029typedef enum {
30 BVAL_NR,
31 BVAL_STRING,
32 BVAL_EMPTY
33} btype_T;
34
35typedef struct {
36 btype_T bv_type;
37 long bv_nr;
38 char_u *bv_string;
39 char_u *bv_tofree; // free later when not NULL
40 int bv_len; // length of bv_string
41 int bv_allocated; // bv_string was allocated
42} bval_T;
43
Bram Moolenaardefa0672019-07-21 19:25:37 +020044#if defined(FEAT_VIMINFO) || defined(PROTO)
45
46static int viminfo_errcnt;
47
48/*
Bram Moolenaarc3328162019-07-23 22:15:25 +020049 * Find the parameter represented by the given character (eg ''', ':', '"', or
50 * '/') in the 'viminfo' option and return a pointer to the string after it.
51 * Return NULL if the parameter is not specified in the string.
52 */
53 static char_u *
54find_viminfo_parameter(int type)
55{
56 char_u *p;
57
58 for (p = p_viminfo; *p; ++p)
59 {
60 if (*p == type)
61 return p + 1;
62 if (*p == 'n') // 'n' is always the last one
63 break;
64 p = vim_strchr(p, ','); // skip until next ','
65 if (p == NULL) // hit the end without finding parameter
66 break;
67 }
68 return NULL;
69}
70
71/*
72 * Find the parameter represented by the given character (eg ', :, ", or /),
73 * and return its associated value in the 'viminfo' string.
74 * Only works for number parameters, not for 'r' or 'n'.
75 * If the parameter is not specified in the string or there is no following
76 * number, return -1.
77 */
78 int
79get_viminfo_parameter(int type)
80{
81 char_u *p;
82
83 p = find_viminfo_parameter(type);
84 if (p != NULL && VIM_ISDIGIT(*p))
85 return atoi((char *)p);
86 return -1;
87}
88
89/*
Bram Moolenaardefa0672019-07-21 19:25:37 +020090 * Get the viminfo file name to use.
91 * If "file" is given and not empty, use it (has already been expanded by
92 * cmdline functions).
93 * Otherwise use "-i file_name", value from 'viminfo' or the default, and
94 * expand environment variables.
95 * Returns an allocated string. NULL when out of memory.
96 */
97 static char_u *
98viminfo_filename(char_u *file)
99{
100 if (file == NULL || *file == NUL)
101 {
102 if (*p_viminfofile != NUL)
103 file = p_viminfofile;
104 else if ((file = find_viminfo_parameter('n')) == NULL || *file == NUL)
105 {
106#ifdef VIMINFO_FILE2
107# ifdef VMS
108 if (mch_getenv((char_u *)"SYS$LOGIN") == NULL)
109# else
110# ifdef MSWIN
111 // Use $VIM only if $HOME is the default "C:/".
112 if (STRCMP(vim_getenv((char_u *)"HOME", NULL), "C:/") == 0
113 && mch_getenv((char_u *)"HOME") == NULL)
114# else
115 if (mch_getenv((char_u *)"HOME") == NULL)
116# endif
117# endif
118 {
119 // don't use $VIM when not available.
120 expand_env((char_u *)"$VIM", NameBuff, MAXPATHL);
121 if (STRCMP("$VIM", NameBuff) != 0) // $VIM was expanded
122 file = (char_u *)VIMINFO_FILE2;
123 else
124 file = (char_u *)VIMINFO_FILE;
125 }
126 else
127#endif
128 file = (char_u *)VIMINFO_FILE;
129 }
130 expand_env(file, NameBuff, MAXPATHL);
131 file = NameBuff;
132 }
133 return vim_strsave(file);
134}
135
Bram Moolenaarc3328162019-07-23 22:15:25 +0200136/*
137 * write string to viminfo file
138 * - replace CTRL-V with CTRL-V CTRL-V
139 * - replace '\n' with CTRL-V 'n'
140 * - add a '\n' at the end
141 *
142 * For a long line:
143 * - write " CTRL-V <length> \n " in first line
144 * - write " < <string> \n " in second line
145 */
146 static void
147viminfo_writestring(FILE *fd, char_u *p)
148{
149 int c;
150 char_u *s;
151 int len = 0;
152
153 for (s = p; *s != NUL; ++s)
154 {
155 if (*s == Ctrl_V || *s == '\n')
156 ++len;
157 ++len;
158 }
159
160 // If the string will be too long, write its length and put it in the next
161 // line. Take into account that some room is needed for what comes before
162 // the string (e.g., variable name). Add something to the length for the
163 // '<', NL and trailing NUL.
164 if (len > LSIZE / 2)
Bram Moolenaar424bcae2022-01-31 14:59:41 +0000165 fprintf(fd, "\026%d\n<", len + 3);
Bram Moolenaarc3328162019-07-23 22:15:25 +0200166
167 while ((c = *p++) != NUL)
168 {
169 if (c == Ctrl_V || c == '\n')
170 {
171 putc(Ctrl_V, fd);
172 if (c == '\n')
173 c = 'n';
174 }
175 putc(c, fd);
176 }
177 putc('\n', fd);
178}
179
180/*
181 * Write a string in quotes that barline_parse() can read back.
182 * Breaks the line in less than LSIZE pieces when needed.
183 * Returns remaining characters in the line.
184 */
185 static int
186barline_writestring(FILE *fd, char_u *s, int remaining_start)
187{
188 char_u *p;
189 int remaining = remaining_start;
190 int len = 2;
191
192 // Count the number of characters produced, including quotes.
193 for (p = s; *p != NUL; ++p)
194 {
195 if (*p == NL)
196 len += 2;
197 else if (*p == '"' || *p == '\\')
198 len += 2;
199 else
200 ++len;
201 }
202 if (len > remaining - 2)
203 {
204 fprintf(fd, ">%d\n|<", len);
205 remaining = LSIZE - 20;
206 }
207
208 putc('"', fd);
209 for (p = s; *p != NUL; ++p)
210 {
211 if (*p == NL)
212 {
213 putc('\\', fd);
214 putc('n', fd);
215 --remaining;
216 }
217 else if (*p == '"' || *p == '\\')
218 {
219 putc('\\', fd);
220 putc(*p, fd);
221 --remaining;
222 }
223 else
224 putc(*p, fd);
225 --remaining;
226
227 if (remaining < 3)
228 {
229 putc('\n', fd);
230 putc('|', fd);
231 putc('<', fd);
232 // Leave enough space for another continuation.
233 remaining = LSIZE - 20;
234 }
235 }
236 putc('"', fd);
237 return remaining - 2;
238}
239
240/*
241 * Check string read from viminfo file.
242 * Remove '\n' at the end of the line.
243 * - replace CTRL-V CTRL-V with CTRL-V
244 * - replace CTRL-V 'n' with '\n'
245 *
246 * Check for a long line as written by viminfo_writestring().
247 *
248 * Return the string in allocated memory (NULL when out of memory).
249 */
250 static char_u *
251viminfo_readstring(
252 vir_T *virp,
253 int off, // offset for virp->vir_line
254 int convert UNUSED) // convert the string
255{
Bram Moolenaared7cb2d2021-08-11 17:13:54 +0200256 char_u *retval = NULL;
Bram Moolenaarc3328162019-07-23 22:15:25 +0200257 char_u *s, *d;
258 long len;
259
260 if (virp->vir_line[off] == Ctrl_V && vim_isdigit(virp->vir_line[off + 1]))
261 {
262 len = atol((char *)virp->vir_line + off + 1);
Bram Moolenaared7cb2d2021-08-11 17:13:54 +0200263 if (len > 0 && len < 1000000)
264 retval = lalloc(len, TRUE);
Bram Moolenaarc3328162019-07-23 22:15:25 +0200265 if (retval == NULL)
266 {
Bram Moolenaared7cb2d2021-08-11 17:13:54 +0200267 // Invalid length, line too long, out of memory? Skip next line.
Bram Moolenaarc3328162019-07-23 22:15:25 +0200268 (void)vim_fgets(virp->vir_line, 10, virp->vir_fd);
269 return NULL;
270 }
271 (void)vim_fgets(retval, (int)len, virp->vir_fd);
272 s = retval + 1; // Skip the leading '<'
273 }
274 else
275 {
276 retval = vim_strsave(virp->vir_line + off);
277 if (retval == NULL)
278 return NULL;
279 s = retval;
280 }
281
282 // Change CTRL-V CTRL-V to CTRL-V and CTRL-V n to \n in-place.
283 d = retval;
284 while (*s != NUL && *s != '\n')
285 {
286 if (s[0] == Ctrl_V && s[1] != NUL)
287 {
288 if (s[1] == 'n')
289 *d++ = '\n';
290 else
291 *d++ = Ctrl_V;
292 s += 2;
293 }
294 else
295 *d++ = *s++;
296 }
297 *d = NUL;
298
299 if (convert && virp->vir_conv.vc_type != CONV_NONE && *retval != NUL)
300 {
301 d = string_convert(&virp->vir_conv, retval, NULL);
302 if (d != NULL)
303 {
304 vim_free(retval);
305 retval = d;
306 }
307 }
308
309 return retval;
310}
311
312/*
313 * Read a line from the viminfo file.
314 * Returns TRUE for end-of-file;
315 */
316 static int
317viminfo_readline(vir_T *virp)
318{
319 return vim_fgets(virp->vir_line, LSIZE, virp->vir_fd);
320}
321
Bram Moolenaardefa0672019-07-21 19:25:37 +0200322 static int
323read_viminfo_bufferlist(
324 vir_T *virp,
325 int writing)
326{
327 char_u *tab;
328 linenr_T lnum;
329 colnr_T col;
330 buf_T *buf;
331 char_u *sfname;
332 char_u *xline;
333
334 // Handle long line and escaped characters.
335 xline = viminfo_readstring(virp, 1, FALSE);
336
337 // don't read in if there are files on the command-line or if writing:
338 if (xline != NULL && !writing && ARGCOUNT == 0
339 && find_viminfo_parameter('%') != NULL)
340 {
341 // Format is: <fname> Tab <lnum> Tab <col>.
342 // Watch out for a Tab in the file name, work from the end.
343 lnum = 0;
344 col = 0;
345 tab = vim_strrchr(xline, '\t');
346 if (tab != NULL)
347 {
348 *tab++ = '\0';
349 col = (colnr_T)atoi((char *)tab);
350 tab = vim_strrchr(xline, '\t');
351 if (tab != NULL)
352 {
353 *tab++ = '\0';
354 lnum = atol((char *)tab);
355 }
356 }
357
358 // Expand "~/" in the file name at "line + 1" to a full path.
359 // Then try shortening it by comparing with the current directory
360 expand_env(xline, NameBuff, MAXPATHL);
361 sfname = shorten_fname1(NameBuff);
362
363 buf = buflist_new(NameBuff, sfname, (linenr_T)0, BLN_LISTED);
364 if (buf != NULL) // just in case...
365 {
366 buf->b_last_cursor.lnum = lnum;
367 buf->b_last_cursor.col = col;
368 buflist_setfpos(buf, curwin, lnum, col, FALSE);
369 }
370 }
371 vim_free(xline);
372
373 return viminfo_readline(virp);
374}
375
Bram Moolenaarc3328162019-07-23 22:15:25 +0200376/*
377 * Return TRUE if "name" is on removable media (depending on 'viminfo').
378 */
379 static int
380removable(char_u *name)
381{
382 char_u *p;
383 char_u part[51];
384 int retval = FALSE;
385 size_t n;
386
387 name = home_replace_save(NULL, name);
388 if (name != NULL)
389 {
390 for (p = p_viminfo; *p; )
391 {
392 copy_option_part(&p, part, 51, ", ");
393 if (part[0] == 'r')
394 {
395 n = STRLEN(part + 1);
396 if (MB_STRNICMP(part + 1, name, n) == 0)
397 {
398 retval = TRUE;
399 break;
400 }
401 }
402 }
403 vim_free(name);
404 }
405 return retval;
406}
407
Bram Moolenaardefa0672019-07-21 19:25:37 +0200408 static void
409write_viminfo_bufferlist(FILE *fp)
410{
411 buf_T *buf;
412 win_T *win;
413 tabpage_T *tp;
414 char_u *line;
415 int max_buffers;
416
417 if (find_viminfo_parameter('%') == NULL)
418 return;
419
420 // Without a number -1 is returned: do all buffers.
421 max_buffers = get_viminfo_parameter('%');
422
423 // Allocate room for the file name, lnum and col.
424#define LINE_BUF_LEN (MAXPATHL + 40)
425 line = alloc(LINE_BUF_LEN);
426 if (line == NULL)
427 return;
428
429 FOR_ALL_TAB_WINDOWS(tp, win)
430 set_last_cursor(win);
431
432 fputs(_("\n# Buffer list:\n"), fp);
433 FOR_ALL_BUFFERS(buf)
434 {
435 if (buf->b_fname == NULL
436 || !buf->b_p_bl
Bram Moolenaardefa0672019-07-21 19:25:37 +0200437 || bt_quickfix(buf)
Bram Moolenaardefa0672019-07-21 19:25:37 +0200438 || bt_terminal(buf)
Bram Moolenaardefa0672019-07-21 19:25:37 +0200439 || removable(buf->b_ffname))
440 continue;
441
442 if (max_buffers-- == 0)
443 break;
444 putc('%', fp);
445 home_replace(NULL, buf->b_ffname, line, MAXPATHL, TRUE);
446 vim_snprintf_add((char *)line, LINE_BUF_LEN, "\t%ld\t%d",
447 (long)buf->b_last_cursor.lnum,
448 buf->b_last_cursor.col);
449 viminfo_writestring(fp, line);
450 }
451 vim_free(line);
452}
453
Bram Moolenaar5f32ece2019-07-21 21:51:59 +0200454/*
455 * Buffers for history read from a viminfo file. Only valid while reading.
456 */
457static histentry_T *viminfo_history[HIST_COUNT] =
458 {NULL, NULL, NULL, NULL, NULL};
459static int viminfo_hisidx[HIST_COUNT] = {0, 0, 0, 0, 0};
460static int viminfo_hislen[HIST_COUNT] = {0, 0, 0, 0, 0};
461static int viminfo_add_at_front = FALSE;
462
463/*
464 * Translate a history type number to the associated character.
465 */
466 static int
467hist_type2char(
468 int type,
469 int use_question) // use '?' instead of '/'
470{
471 if (type == HIST_CMD)
472 return ':';
473 if (type == HIST_SEARCH)
474 {
475 if (use_question)
476 return '?';
477 else
478 return '/';
479 }
480 if (type == HIST_EXPR)
481 return '=';
482 return '@';
483}
484
485/*
486 * Prepare for reading the history from the viminfo file.
487 * This allocates history arrays to store the read history lines.
488 */
489 static void
490prepare_viminfo_history(int asklen, int writing)
491{
492 int i;
493 int num;
494 int type;
495 int len;
Bram Moolenaar26b654a2019-07-22 20:50:17 +0200496 int hislen;
Bram Moolenaar5f32ece2019-07-21 21:51:59 +0200497
498 init_history();
Bram Moolenaar26b654a2019-07-22 20:50:17 +0200499 hislen = get_hislen();
Bram Moolenaar5f32ece2019-07-21 21:51:59 +0200500 viminfo_add_at_front = (asklen != 0 && !writing);
501 if (asklen > hislen)
502 asklen = hislen;
503
504 for (type = 0; type < HIST_COUNT; ++type)
505 {
506 histentry_T *histentry = get_histentry(type);
507
508 // Count the number of empty spaces in the history list. Entries read
509 // from viminfo previously are also considered empty. If there are
510 // more spaces available than we request, then fill them up.
511 for (i = 0, num = 0; i < hislen; i++)
512 if (histentry[i].hisstr == NULL || histentry[i].viminfo)
513 num++;
514 len = asklen;
515 if (num > len)
516 len = num;
517 if (len <= 0)
518 viminfo_history[type] = NULL;
519 else
520 viminfo_history[type] = LALLOC_MULT(histentry_T, len);
521 if (viminfo_history[type] == NULL)
522 len = 0;
523 viminfo_hislen[type] = len;
524 viminfo_hisidx[type] = 0;
525 }
526}
527
528/*
529 * Accept a line from the viminfo, store it in the history array when it's
530 * new.
531 */
532 static int
533read_viminfo_history(vir_T *virp, int writing)
534{
535 int type;
536 long_u len;
537 char_u *val;
538 char_u *p;
539
540 type = hist_char2type(virp->vir_line[0]);
541 if (viminfo_hisidx[type] < viminfo_hislen[type])
542 {
543 val = viminfo_readstring(virp, 1, TRUE);
544 if (val != NULL && *val != NUL)
545 {
546 int sep = (*val == ' ' ? NUL : *val);
547
548 if (!in_history(type, val + (type == HIST_SEARCH),
549 viminfo_add_at_front, sep, writing))
550 {
551 // Need to re-allocate to append the separator byte.
552 len = STRLEN(val);
553 p = alloc(len + 2);
554 if (p != NULL)
555 {
556 if (type == HIST_SEARCH)
557 {
558 // Search entry: Move the separator from the first
559 // column to after the NUL.
560 mch_memmove(p, val + 1, (size_t)len);
561 p[len] = sep;
562 }
563 else
564 {
565 // Not a search entry: No separator in the viminfo
566 // file, add a NUL separator.
567 mch_memmove(p, val, (size_t)len + 1);
568 p[len + 1] = NUL;
569 }
570 viminfo_history[type][viminfo_hisidx[type]].hisstr = p;
571 viminfo_history[type][viminfo_hisidx[type]].time_set = 0;
572 viminfo_history[type][viminfo_hisidx[type]].viminfo = TRUE;
573 viminfo_history[type][viminfo_hisidx[type]].hisnum = 0;
574 viminfo_hisidx[type]++;
575 }
576 }
577 }
578 vim_free(val);
579 }
580 return viminfo_readline(virp);
581}
582
583/*
584 * Accept a new style history line from the viminfo, store it in the history
585 * array when it's new.
586 */
587 static void
588handle_viminfo_history(
589 garray_T *values,
590 int writing)
591{
592 int type;
593 long_u len;
594 char_u *val;
595 char_u *p;
596 bval_T *vp = (bval_T *)values->ga_data;
597
598 // Check the format:
599 // |{bartype},{histtype},{timestamp},{separator},"text"
600 if (values->ga_len < 4
601 || vp[0].bv_type != BVAL_NR
602 || vp[1].bv_type != BVAL_NR
603 || (vp[2].bv_type != BVAL_NR && vp[2].bv_type != BVAL_EMPTY)
604 || vp[3].bv_type != BVAL_STRING)
605 return;
606
607 type = vp[0].bv_nr;
608 if (type >= HIST_COUNT)
609 return;
610 if (viminfo_hisidx[type] < viminfo_hislen[type])
611 {
612 val = vp[3].bv_string;
613 if (val != NULL && *val != NUL)
614 {
615 int sep = type == HIST_SEARCH && vp[2].bv_type == BVAL_NR
616 ? vp[2].bv_nr : NUL;
617 int idx;
618 int overwrite = FALSE;
619
620 if (!in_history(type, val, viminfo_add_at_front, sep, writing))
621 {
622 // If lines were written by an older Vim we need to avoid
623 // getting duplicates. See if the entry already exists.
624 for (idx = 0; idx < viminfo_hisidx[type]; ++idx)
625 {
626 p = viminfo_history[type][idx].hisstr;
627 if (STRCMP(val, p) == 0
628 && (type != HIST_SEARCH || sep == p[STRLEN(p) + 1]))
629 {
630 overwrite = TRUE;
631 break;
632 }
633 }
634
635 if (!overwrite)
636 {
637 // Need to re-allocate to append the separator byte.
638 len = vp[3].bv_len;
639 p = alloc(len + 2);
640 }
641 else
642 len = 0; // for picky compilers
643 if (p != NULL)
644 {
645 viminfo_history[type][idx].time_set = vp[1].bv_nr;
646 if (!overwrite)
647 {
648 mch_memmove(p, val, (size_t)len + 1);
649 // Put the separator after the NUL.
650 p[len + 1] = sep;
651 viminfo_history[type][idx].hisstr = p;
652 viminfo_history[type][idx].hisnum = 0;
653 viminfo_history[type][idx].viminfo = TRUE;
654 viminfo_hisidx[type]++;
655 }
656 }
657 }
658 }
659 }
660}
661
662/*
663 * Concatenate history lines from viminfo after the lines typed in this Vim.
664 */
665 static void
666concat_history(int type)
667{
668 int idx;
669 int i;
670 int hislen = get_hislen();
671 histentry_T *histentry = get_histentry(type);
672 int *hisidx = get_hisidx(type);
673 int *hisnum = get_hisnum(type);
674
675 idx = *hisidx + viminfo_hisidx[type];
676 if (idx >= hislen)
677 idx -= hislen;
678 else if (idx < 0)
679 idx = hislen - 1;
680 if (viminfo_add_at_front)
681 *hisidx = idx;
682 else
683 {
684 if (*hisidx == -1)
685 *hisidx = hislen - 1;
686 do
687 {
688 if (histentry[idx].hisstr != NULL || histentry[idx].viminfo)
689 break;
690 if (++idx == hislen)
691 idx = 0;
692 } while (idx != *hisidx);
693 if (idx != *hisidx && --idx < 0)
694 idx = hislen - 1;
695 }
696 for (i = 0; i < viminfo_hisidx[type]; i++)
697 {
698 vim_free(histentry[idx].hisstr);
699 histentry[idx].hisstr = viminfo_history[type][i].hisstr;
700 histentry[idx].viminfo = TRUE;
701 histentry[idx].time_set = viminfo_history[type][i].time_set;
702 if (--idx < 0)
703 idx = hislen - 1;
704 }
705 idx += 1;
706 idx %= hislen;
707 for (i = 0; i < viminfo_hisidx[type]; i++)
708 {
709 histentry[idx++].hisnum = ++*hisnum;
710 idx %= hislen;
711 }
712}
713
714 static int
715sort_hist(const void *s1, const void *s2)
716{
717 histentry_T *p1 = *(histentry_T **)s1;
718 histentry_T *p2 = *(histentry_T **)s2;
719
720 if (p1->time_set < p2->time_set) return -1;
721 if (p1->time_set > p2->time_set) return 1;
722 return 0;
723}
724
725/*
726 * Merge history lines from viminfo and lines typed in this Vim based on the
727 * timestamp;
728 */
729 static void
730merge_history(int type)
731{
732 int max_len;
733 histentry_T **tot_hist;
734 histentry_T *new_hist;
735 int i;
736 int len;
737 int hislen = get_hislen();
738 histentry_T *histentry = get_histentry(type);
739 int *hisidx = get_hisidx(type);
740 int *hisnum = get_hisnum(type);
741
742 // Make one long list with all entries.
743 max_len = hislen + viminfo_hisidx[type];
744 tot_hist = ALLOC_MULT(histentry_T *, max_len);
Bram Moolenaar26b654a2019-07-22 20:50:17 +0200745 new_hist = ALLOC_MULT(histentry_T, hislen);
Bram Moolenaar5f32ece2019-07-21 21:51:59 +0200746 if (tot_hist == NULL || new_hist == NULL)
747 {
748 vim_free(tot_hist);
749 vim_free(new_hist);
750 return;
751 }
752 for (i = 0; i < viminfo_hisidx[type]; i++)
753 tot_hist[i] = &viminfo_history[type][i];
754 len = i;
755 for (i = 0; i < hislen; i++)
756 if (histentry[i].hisstr != NULL)
757 tot_hist[len++] = &histentry[i];
758
759 // Sort the list on timestamp.
760 qsort((void *)tot_hist, (size_t)len, sizeof(histentry_T *), sort_hist);
761
762 // Keep the newest ones.
763 for (i = 0; i < hislen; i++)
764 {
765 if (i < len)
766 {
767 new_hist[i] = *tot_hist[i];
768 tot_hist[i]->hisstr = NULL;
769 if (new_hist[i].hisnum == 0)
770 new_hist[i].hisnum = ++*hisnum;
771 }
772 else
773 clear_hist_entry(&new_hist[i]);
774 }
775 *hisidx = (i < len ? i : len) - 1;
776
777 // Free what is not kept.
778 for (i = 0; i < viminfo_hisidx[type]; i++)
779 vim_free(viminfo_history[type][i].hisstr);
780 for (i = 0; i < hislen; i++)
781 vim_free(histentry[i].hisstr);
782 vim_free(histentry);
783 set_histentry(type, new_hist);
784 vim_free(tot_hist);
785}
786
787/*
788 * Finish reading history lines from viminfo. Not used when writing viminfo.
789 */
790 static void
791finish_viminfo_history(vir_T *virp)
792{
793 int type;
794 int merge = virp->vir_version >= VIMINFO_VERSION_WITH_HISTORY;
795
796 for (type = 0; type < HIST_COUNT; ++type)
797 {
798 if (get_histentry(type) == NULL)
799 continue;
800
801 if (merge)
802 merge_history(type);
803 else
804 concat_history(type);
805
806 VIM_CLEAR(viminfo_history[type]);
807 viminfo_hisidx[type] = 0;
808 }
809}
810
811/*
812 * Write history to viminfo file in "fp".
813 * When "merge" is TRUE merge history lines with a previously read viminfo
814 * file, data is in viminfo_history[].
815 * When "merge" is FALSE just write all history lines. Used for ":wviminfo!".
816 */
817 static void
818write_viminfo_history(FILE *fp, int merge)
819{
820 int i;
821 int type;
822 int num_saved;
823 int round;
824 int hislen;
825
826 init_history();
827 hislen = get_hislen();
828 if (hislen == 0)
829 return;
830 for (type = 0; type < HIST_COUNT; ++type)
831 {
832 histentry_T *histentry = get_histentry(type);
833 int *hisidx = get_hisidx(type);
834
835 num_saved = get_viminfo_parameter(hist_type2char(type, FALSE));
836 if (num_saved == 0)
837 continue;
838 if (num_saved < 0) // Use default
839 num_saved = hislen;
840 fprintf(fp, _("\n# %s History (newest to oldest):\n"),
841 type == HIST_CMD ? _("Command Line") :
842 type == HIST_SEARCH ? _("Search String") :
843 type == HIST_EXPR ? _("Expression") :
844 type == HIST_INPUT ? _("Input Line") :
845 _("Debug Line"));
846 if (num_saved > hislen)
847 num_saved = hislen;
848
Bram Moolenaar6bd1d772019-10-09 22:01:25 +0200849 // Merge typed and viminfo history:
850 // round 1: history of typed commands.
851 // round 2: history from recently read viminfo.
Bram Moolenaar5f32ece2019-07-21 21:51:59 +0200852 for (round = 1; round <= 2; ++round)
853 {
854 if (round == 1)
855 // start at newest entry, somewhere in the list
856 i = *hisidx;
857 else if (viminfo_hisidx[type] > 0)
858 // start at newest entry, first in the list
859 i = 0;
860 else
861 // empty list
862 i = -1;
863 if (i >= 0)
864 while (num_saved > 0
865 && !(round == 2 && i >= viminfo_hisidx[type]))
866 {
867 char_u *p;
868 time_t timestamp;
869 int c = NUL;
870
871 if (round == 1)
872 {
873 p = histentry[i].hisstr;
874 timestamp = histentry[i].time_set;
875 }
876 else
877 {
878 p = viminfo_history[type] == NULL ? NULL
879 : viminfo_history[type][i].hisstr;
880 timestamp = viminfo_history[type] == NULL ? 0
881 : viminfo_history[type][i].time_set;
882 }
883
884 if (p != NULL && (round == 2
885 || !merge
886 || !histentry[i].viminfo))
887 {
888 --num_saved;
889 fputc(hist_type2char(type, TRUE), fp);
890 // For the search history: put the separator in the
891 // second column; use a space if there isn't one.
892 if (type == HIST_SEARCH)
893 {
894 c = p[STRLEN(p) + 1];
895 putc(c == NUL ? ' ' : c, fp);
896 }
897 viminfo_writestring(fp, p);
898
899 {
900 char cbuf[NUMBUFLEN];
901
902 // New style history with a bar line. Format:
903 // |{bartype},{histtype},{timestamp},{separator},"text"
904 if (c == NUL)
905 cbuf[0] = NUL;
906 else
907 sprintf(cbuf, "%d", c);
908 fprintf(fp, "|%d,%d,%ld,%s,", BARTYPE_HISTORY,
909 type, (long)timestamp, cbuf);
910 barline_writestring(fp, p, LSIZE - 20);
911 putc('\n', fp);
912 }
913 }
914 if (round == 1)
915 {
916 // Decrement index, loop around and stop when back at
917 // the start.
918 if (--i < 0)
919 i = hislen - 1;
920 if (i == *hisidx)
921 break;
922 }
923 else
924 {
925 // Increment index. Stop at the end in the while.
926 ++i;
927 }
928 }
929 }
930 for (i = 0; i < viminfo_hisidx[type]; ++i)
931 if (viminfo_history[type] != NULL)
932 vim_free(viminfo_history[type][i].hisstr);
933 VIM_CLEAR(viminfo_history[type]);
934 viminfo_hisidx[type] = 0;
935 }
936}
Bram Moolenaar5f32ece2019-07-21 21:51:59 +0200937
Bram Moolenaardefa0672019-07-21 19:25:37 +0200938 static void
939write_viminfo_barlines(vir_T *virp, FILE *fp_out)
940{
941 int i;
942 garray_T *gap = &virp->vir_barlines;
943 int seen_useful = FALSE;
944 char *line;
945
946 if (gap->ga_len > 0)
947 {
948 fputs(_("\n# Bar lines, copied verbatim:\n"), fp_out);
949
950 // Skip over continuation lines until seeing a useful line.
951 for (i = 0; i < gap->ga_len; ++i)
952 {
953 line = ((char **)(gap->ga_data))[i];
954 if (seen_useful || line[1] != '<')
955 {
956 fputs(line, fp_out);
957 seen_useful = TRUE;
958 }
959 }
960 }
961}
962
963/*
964 * Parse a viminfo line starting with '|'.
965 * Add each decoded value to "values".
966 * Returns TRUE if the next line is to be read after using the parsed values.
967 */
968 static int
969barline_parse(vir_T *virp, char_u *text, garray_T *values)
970{
971 char_u *p = text;
972 char_u *nextp = NULL;
973 char_u *buf = NULL;
974 bval_T *value;
975 int i;
976 int allocated = FALSE;
977 int eof;
978 char_u *sconv;
979 int converted;
980
981 while (*p == ',')
982 {
983 ++p;
984 if (ga_grow(values, 1) == FAIL)
985 break;
986 value = (bval_T *)(values->ga_data) + values->ga_len;
987
988 if (*p == '>')
989 {
990 // Need to read a continuation line. Put strings in allocated
991 // memory, because virp->vir_line is overwritten.
992 if (!allocated)
993 {
994 for (i = 0; i < values->ga_len; ++i)
995 {
996 bval_T *vp = (bval_T *)(values->ga_data) + i;
997
998 if (vp->bv_type == BVAL_STRING && !vp->bv_allocated)
999 {
1000 vp->bv_string = vim_strnsave(vp->bv_string, vp->bv_len);
1001 vp->bv_allocated = TRUE;
1002 }
1003 }
1004 allocated = TRUE;
1005 }
1006
1007 if (vim_isdigit(p[1]))
1008 {
1009 size_t len;
1010 size_t todo;
1011 size_t n;
1012
1013 // String value was split into lines that are each shorter
1014 // than LSIZE:
1015 // |{bartype},>{length of "{text}{text2}"}
1016 // |<"{text1}
1017 // |<{text2}",{value}
1018 // Length includes the quotes.
1019 ++p;
1020 len = getdigits(&p);
1021 buf = alloc((int)(len + 1));
1022 if (buf == NULL)
1023 return TRUE;
1024 p = buf;
1025 for (todo = len; todo > 0; todo -= n)
1026 {
1027 eof = viminfo_readline(virp);
1028 if (eof || virp->vir_line[0] != '|'
1029 || virp->vir_line[1] != '<')
1030 {
1031 // File was truncated or garbled. Read another line if
1032 // this one starts with '|'.
1033 vim_free(buf);
1034 return eof || virp->vir_line[0] == '|';
1035 }
1036 // Get length of text, excluding |< and NL chars.
1037 n = STRLEN(virp->vir_line);
1038 while (n > 0 && (virp->vir_line[n - 1] == NL
1039 || virp->vir_line[n - 1] == CAR))
1040 --n;
1041 n -= 2;
1042 if (n > todo)
1043 {
1044 // more values follow after the string
1045 nextp = virp->vir_line + 2 + todo;
1046 n = todo;
1047 }
1048 mch_memmove(p, virp->vir_line + 2, n);
1049 p += n;
1050 }
1051 *p = NUL;
1052 p = buf;
1053 }
1054 else
1055 {
1056 // Line ending in ">" continues in the next line:
1057 // |{bartype},{lots of values},>
1058 // |<{value},{value}
1059 eof = viminfo_readline(virp);
1060 if (eof || virp->vir_line[0] != '|'
1061 || virp->vir_line[1] != '<')
1062 // File was truncated or garbled. Read another line if
1063 // this one starts with '|'.
1064 return eof || virp->vir_line[0] == '|';
1065 p = virp->vir_line + 2;
1066 }
1067 }
1068
1069 if (isdigit(*p))
1070 {
1071 value->bv_type = BVAL_NR;
1072 value->bv_nr = getdigits(&p);
1073 ++values->ga_len;
1074 }
1075 else if (*p == '"')
1076 {
1077 int len = 0;
1078 char_u *s = p;
1079
1080 // Unescape special characters in-place.
1081 ++p;
1082 while (*p != '"')
1083 {
1084 if (*p == NL || *p == NUL)
1085 return TRUE; // syntax error, drop the value
1086 if (*p == '\\')
1087 {
1088 ++p;
1089 if (*p == 'n')
1090 s[len++] = '\n';
1091 else
1092 s[len++] = *p;
1093 ++p;
1094 }
1095 else
1096 s[len++] = *p++;
1097 }
1098 ++p;
1099 s[len] = NUL;
1100
1101 converted = FALSE;
Bram Moolenaar408030e2020-02-10 22:44:32 +01001102 value->bv_tofree = NULL;
Bram Moolenaardefa0672019-07-21 19:25:37 +02001103 if (virp->vir_conv.vc_type != CONV_NONE && *s != NUL)
1104 {
1105 sconv = string_convert(&virp->vir_conv, s, NULL);
1106 if (sconv != NULL)
1107 {
1108 if (s == buf)
Bram Moolenaar408030e2020-02-10 22:44:32 +01001109 // the converted string is stored in bv_string and
1110 // freed later, also need to free "buf" later
1111 value->bv_tofree = buf;
Bram Moolenaardefa0672019-07-21 19:25:37 +02001112 s = sconv;
Bram Moolenaardefa0672019-07-21 19:25:37 +02001113 converted = TRUE;
1114 }
1115 }
1116
1117 // Need to copy in allocated memory if the string wasn't allocated
1118 // above and we did allocate before, thus vir_line may change.
Bram Moolenaar408030e2020-02-10 22:44:32 +01001119 if (s != buf && allocated && !converted)
Bram Moolenaardefa0672019-07-21 19:25:37 +02001120 s = vim_strsave(s);
1121 value->bv_string = s;
1122 value->bv_type = BVAL_STRING;
1123 value->bv_len = len;
1124 value->bv_allocated = allocated || converted;
1125 ++values->ga_len;
1126 if (nextp != NULL)
1127 {
1128 // values following a long string
1129 p = nextp;
1130 nextp = NULL;
1131 }
1132 }
1133 else if (*p == ',')
1134 {
1135 value->bv_type = BVAL_EMPTY;
1136 ++values->ga_len;
1137 }
1138 else
1139 break;
1140 }
1141 return TRUE;
1142}
1143
Bram Moolenaardefa0672019-07-21 19:25:37 +02001144 static void
1145write_viminfo_version(FILE *fp_out)
1146{
1147 fprintf(fp_out, "# Viminfo version\n|%d,%d\n\n",
1148 BARTYPE_VERSION, VIMINFO_VERSION);
1149}
1150
1151 static int
1152no_viminfo(void)
1153{
1154 // "vim -i NONE" does not read or write a viminfo file
1155 return STRCMP(p_viminfofile, "NONE") == 0;
1156}
1157
1158/*
1159 * Report an error for reading a viminfo file.
1160 * Count the number of errors. When there are more than 10, return TRUE.
1161 */
Bram Moolenaarc3328162019-07-23 22:15:25 +02001162 static int
Bram Moolenaardefa0672019-07-21 19:25:37 +02001163viminfo_error(char *errnum, char *message, char_u *line)
1164{
1165 vim_snprintf((char *)IObuff, IOSIZE, _("%sviminfo: %s in line: "),
1166 errnum, message);
1167 STRNCAT(IObuff, line, IOSIZE - STRLEN(IObuff) - 1);
1168 if (IObuff[STRLEN(IObuff) - 1] == '\n')
1169 IObuff[STRLEN(IObuff) - 1] = NUL;
1170 emsg((char *)IObuff);
1171 if (++viminfo_errcnt >= 10)
1172 {
Bram Moolenaarc553a212021-12-26 20:20:34 +00001173 emsg(_(e_viminfo_too_many_errors_skipping_rest_of_file));
Bram Moolenaardefa0672019-07-21 19:25:37 +02001174 return TRUE;
1175 }
1176 return FALSE;
1177}
1178
1179/*
1180 * Compare the 'encoding' value in the viminfo file with the current value of
1181 * 'encoding'. If different and the 'c' flag is in 'viminfo', setup for
1182 * conversion of text with iconv() in viminfo_readstring().
1183 */
1184 static int
1185viminfo_encoding(vir_T *virp)
1186{
1187 char_u *p;
1188 int i;
1189
1190 if (get_viminfo_parameter('c') != 0)
1191 {
1192 p = vim_strchr(virp->vir_line, '=');
1193 if (p != NULL)
1194 {
1195 // remove trailing newline
1196 ++p;
1197 for (i = 0; vim_isprintc(p[i]); ++i)
1198 ;
1199 p[i] = NUL;
1200
1201 convert_setup(&virp->vir_conv, p, p_enc);
1202 }
1203 }
1204 return viminfo_readline(virp);
1205}
1206
1207#if defined(FEAT_EVAL) || defined(PROTO)
1208/*
1209 * Restore global vars that start with a capital from the viminfo file
1210 */
1211 static int
1212read_viminfo_varlist(vir_T *virp, int writing)
1213{
1214 char_u *tab;
1215 int type = VAR_NUMBER;
1216 typval_T tv;
1217 funccal_entry_T funccal_entry;
1218
1219 if (!writing && (find_viminfo_parameter('!') != NULL))
1220 {
1221 tab = vim_strchr(virp->vir_line + 1, '\t');
1222 if (tab != NULL)
1223 {
1224 *tab++ = '\0'; // isolate the variable name
1225 switch (*tab)
1226 {
1227 case 'S': type = VAR_STRING; break;
Bram Moolenaardefa0672019-07-21 19:25:37 +02001228 case 'F': type = VAR_FLOAT; break;
Bram Moolenaardefa0672019-07-21 19:25:37 +02001229 case 'D': type = VAR_DICT; break;
1230 case 'L': type = VAR_LIST; break;
1231 case 'B': type = VAR_BLOB; break;
1232 case 'X': type = VAR_SPECIAL; break;
1233 }
1234
1235 tab = vim_strchr(tab, '\t');
1236 if (tab != NULL)
1237 {
1238 tv.v_type = type;
1239 if (type == VAR_STRING || type == VAR_DICT
1240 || type == VAR_LIST || type == VAR_BLOB)
1241 tv.vval.v_string = viminfo_readstring(virp,
1242 (int)(tab - virp->vir_line + 1), TRUE);
Bram Moolenaardefa0672019-07-21 19:25:37 +02001243 else if (type == VAR_FLOAT)
Bram Moolenaar29500652021-08-08 15:43:34 +02001244 (void)string2float(tab + 1, &tv.vval.v_float, FALSE);
Bram Moolenaardefa0672019-07-21 19:25:37 +02001245 else
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001246 {
Bram Moolenaardefa0672019-07-21 19:25:37 +02001247 tv.vval.v_number = atol((char *)tab + 1);
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001248 if (type == VAR_SPECIAL && (tv.vval.v_number == VVAL_FALSE
1249 || tv.vval.v_number == VVAL_TRUE))
1250 tv.v_type = VAR_BOOL;
1251 }
Bram Moolenaardefa0672019-07-21 19:25:37 +02001252 if (type == VAR_DICT || type == VAR_LIST)
1253 {
1254 typval_T *etv = eval_expr(tv.vval.v_string, NULL);
1255
1256 if (etv == NULL)
1257 // Failed to parse back the dict or list, use it as a
1258 // string.
1259 tv.v_type = VAR_STRING;
1260 else
1261 {
1262 vim_free(tv.vval.v_string);
1263 tv = *etv;
1264 vim_free(etv);
1265 }
1266 }
1267 else if (type == VAR_BLOB)
1268 {
1269 blob_T *blob = string2blob(tv.vval.v_string);
1270
1271 if (blob == NULL)
1272 // Failed to parse back the blob, use it as a string.
1273 tv.v_type = VAR_STRING;
1274 else
1275 {
1276 vim_free(tv.vval.v_string);
1277 tv.v_type = VAR_BLOB;
1278 tv.vval.v_blob = blob;
1279 }
1280 }
1281
1282 // when in a function use global variables
1283 save_funccal(&funccal_entry);
1284 set_var(virp->vir_line + 1, &tv, FALSE);
1285 restore_funccal();
1286
1287 if (tv.v_type == VAR_STRING)
1288 vim_free(tv.vval.v_string);
1289 else if (tv.v_type == VAR_DICT || tv.v_type == VAR_LIST ||
1290 tv.v_type == VAR_BLOB)
1291 clear_tv(&tv);
1292 }
1293 }
1294 }
1295
1296 return viminfo_readline(virp);
1297}
1298
1299/*
1300 * Write global vars that start with a capital to the viminfo file
1301 */
1302 static void
1303write_viminfo_varlist(FILE *fp)
1304{
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001305 hashtab_T *gvht = get_globvar_ht();
Bram Moolenaardefa0672019-07-21 19:25:37 +02001306 hashitem_T *hi;
1307 dictitem_T *this_var;
1308 int todo;
1309 char *s = "";
1310 char_u *p;
1311 char_u *tofree;
1312 char_u numbuf[NUMBUFLEN];
1313
1314 if (find_viminfo_parameter('!') == NULL)
1315 return;
1316
1317 fputs(_("\n# global variables:\n"), fp);
1318
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001319 todo = (int)gvht->ht_used;
1320 for (hi = gvht->ht_array; todo > 0; ++hi)
Bram Moolenaardefa0672019-07-21 19:25:37 +02001321 {
1322 if (!HASHITEM_EMPTY(hi))
1323 {
1324 --todo;
1325 this_var = HI2DI(hi);
1326 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
1327 {
1328 switch (this_var->di_tv.v_type)
1329 {
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001330 case VAR_STRING: s = "STR"; break;
1331 case VAR_NUMBER: s = "NUM"; break;
1332 case VAR_FLOAT: s = "FLO"; break;
Bram Moolenaar5b157fe2020-06-07 16:08:08 +02001333 case VAR_DICT:
1334 {
1335 dict_T *di = this_var->di_tv.vval.v_dict;
1336 int copyID = get_copyID();
1337
1338 s = "DIC";
1339 if (di != NULL && !set_ref_in_ht(
1340 &di->dv_hashtab, copyID, NULL)
1341 && di->dv_copyID == copyID)
1342 // has a circular reference, can't turn the
1343 // value into a string
1344 continue;
1345 break;
1346 }
1347 case VAR_LIST:
1348 {
1349 list_T *l = this_var->di_tv.vval.v_list;
1350 int copyID = get_copyID();
1351
1352 s = "LIS";
1353 if (l != NULL && !set_ref_in_list_items(
1354 l, copyID, NULL)
1355 && l->lv_copyID == copyID)
1356 // has a circular reference, can't turn the
1357 // value into a string
1358 continue;
1359 break;
1360 }
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001361 case VAR_BLOB: s = "BLO"; break;
1362 case VAR_BOOL: s = "XPL"; break; // backwards compat.
Bram Moolenaardefa0672019-07-21 19:25:37 +02001363 case VAR_SPECIAL: s = "XPL"; break;
1364
1365 case VAR_UNKNOWN:
Bram Moolenaar4c683752020-04-05 21:38:23 +02001366 case VAR_ANY:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001367 case VAR_VOID:
Bram Moolenaardefa0672019-07-21 19:25:37 +02001368 case VAR_FUNC:
1369 case VAR_PARTIAL:
1370 case VAR_JOB:
1371 case VAR_CHANNEL:
Bram Moolenaarf18332f2021-05-07 17:55:55 +02001372 case VAR_INSTR:
Bram Moolenaardefa0672019-07-21 19:25:37 +02001373 continue;
1374 }
1375 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001376 if (this_var->di_tv.v_type == VAR_BOOL
1377 || this_var->di_tv.v_type == VAR_SPECIAL)
Bram Moolenaardefa0672019-07-21 19:25:37 +02001378 {
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001379 // do not use "v:true" but "1"
Bram Moolenaardefa0672019-07-21 19:25:37 +02001380 sprintf((char *)numbuf, "%ld",
1381 (long)this_var->di_tv.vval.v_number);
1382 p = numbuf;
1383 tofree = NULL;
1384 }
1385 else
1386 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
1387 if (p != NULL)
1388 viminfo_writestring(fp, p);
1389 vim_free(tofree);
1390 }
1391 }
1392 }
1393}
1394#endif // FEAT_EVAL
1395
Bram Moolenaarc3328162019-07-23 22:15:25 +02001396 static int
1397read_viminfo_sub_string(vir_T *virp, int force)
1398{
1399 if (force || get_old_sub() == NULL)
1400 set_old_sub(viminfo_readstring(virp, 1, TRUE));
1401 return viminfo_readline(virp);
1402}
1403
1404 static void
1405write_viminfo_sub_string(FILE *fp)
1406{
1407 char_u *old_sub = get_old_sub();
1408
1409 if (get_viminfo_parameter('/') != 0 && old_sub != NULL)
1410 {
1411 fputs(_("\n# Last Substitute String:\n$"), fp);
1412 viminfo_writestring(fp, old_sub);
1413 }
1414}
1415
1416/*
1417 * Functions relating to reading/writing the search pattern from viminfo
1418 */
1419
1420 static int
1421read_viminfo_search_pattern(vir_T *virp, int force)
1422{
1423 char_u *lp;
1424 int idx = -1;
1425 int magic = FALSE;
1426 int no_scs = FALSE;
1427 int off_line = FALSE;
1428 int off_end = 0;
1429 long off = 0;
1430 int setlast = FALSE;
1431#ifdef FEAT_SEARCH_EXTRA
1432 static int hlsearch_on = FALSE;
1433#endif
1434 char_u *val;
1435 spat_T *spat;
1436
1437 // Old line types:
1438 // "/pat", "&pat": search/subst. pat
1439 // "~/pat", "~&pat": last used search/subst. pat
1440 // New line types:
1441 // "~h", "~H": hlsearch highlighting off/on
1442 // "~<magic><smartcase><line><end><off><last><which>pat"
1443 // <magic>: 'm' off, 'M' on
1444 // <smartcase>: 's' off, 'S' on
1445 // <line>: 'L' line offset, 'l' char offset
1446 // <end>: 'E' from end, 'e' from start
1447 // <off>: decimal, offset
1448 // <last>: '~' last used pattern
1449 // <which>: '/' search pat, '&' subst. pat
1450 lp = virp->vir_line;
1451 if (lp[0] == '~' && (lp[1] == 'm' || lp[1] == 'M')) // new line type
1452 {
1453 if (lp[1] == 'M') // magic on
1454 magic = TRUE;
1455 if (lp[2] == 's')
1456 no_scs = TRUE;
1457 if (lp[3] == 'L')
1458 off_line = TRUE;
1459 if (lp[4] == 'E')
1460 off_end = SEARCH_END;
1461 lp += 5;
1462 off = getdigits(&lp);
1463 }
1464 if (lp[0] == '~') // use this pattern for last-used pattern
1465 {
1466 setlast = TRUE;
1467 lp++;
1468 }
1469 if (lp[0] == '/')
1470 idx = RE_SEARCH;
1471 else if (lp[0] == '&')
1472 idx = RE_SUBST;
1473#ifdef FEAT_SEARCH_EXTRA
1474 else if (lp[0] == 'h') // ~h: 'hlsearch' highlighting off
1475 hlsearch_on = FALSE;
1476 else if (lp[0] == 'H') // ~H: 'hlsearch' highlighting on
1477 hlsearch_on = TRUE;
1478#endif
Bram Moolenaarc3328162019-07-23 22:15:25 +02001479 if (idx >= 0)
1480 {
Bram Moolenaar736cd2c2019-07-25 21:58:19 +02001481 spat = get_spat(idx);
Bram Moolenaarc3328162019-07-23 22:15:25 +02001482 if (force || spat->pat == NULL)
1483 {
1484 val = viminfo_readstring(virp, (int)(lp - virp->vir_line + 1),
1485 TRUE);
1486 if (val != NULL)
1487 {
1488 set_last_search_pat(val, idx, magic, setlast);
1489 vim_free(val);
1490 spat->no_scs = no_scs;
1491 spat->off.line = off_line;
1492 spat->off.end = off_end;
1493 spat->off.off = off;
1494#ifdef FEAT_SEARCH_EXTRA
1495 if (setlast)
1496 set_no_hlsearch(!hlsearch_on);
1497#endif
1498 }
1499 }
1500 }
1501 return viminfo_readline(virp);
1502}
1503
1504 static void
1505wvsp_one(
1506 FILE *fp, // file to write to
1507 int idx, // spats[] index
1508 char *s, // search pat
1509 int sc) // dir char
1510{
1511 spat_T *spat = get_spat(idx);
1512 if (spat->pat != NULL)
1513 {
1514 fprintf(fp, _("\n# Last %sSearch Pattern:\n~"), s);
1515 // off.dir is not stored, it's reset to forward
1516 fprintf(fp, "%c%c%c%c%ld%s%c",
1517 spat->magic ? 'M' : 'm', // magic
1518 spat->no_scs ? 's' : 'S', // smartcase
1519 spat->off.line ? 'L' : 'l', // line offset
1520 spat->off.end ? 'E' : 'e', // offset from end
1521 spat->off.off, // offset
1522 get_spat_last_idx() == idx ? "~" : "", // last used pat
1523 sc);
1524 viminfo_writestring(fp, spat->pat);
1525 }
1526}
1527
1528 static void
1529write_viminfo_search_pattern(FILE *fp)
1530{
1531 if (get_viminfo_parameter('/') != 0)
1532 {
1533#ifdef FEAT_SEARCH_EXTRA
1534 fprintf(fp, "\n# hlsearch on (H) or off (h):\n~%c",
1535 (no_hlsearch || find_viminfo_parameter('h') != NULL) ? 'h' : 'H');
1536#endif
1537 wvsp_one(fp, RE_SEARCH, "", '/');
1538 wvsp_one(fp, RE_SUBST, _("Substitute "), '&');
1539 }
1540}
1541
1542/*
1543 * Functions relating to reading/writing registers from viminfo
1544 */
1545
1546static yankreg_T *y_read_regs = NULL;
1547
1548#define REG_PREVIOUS 1
1549#define REG_EXEC 2
1550
1551/*
1552 * Prepare for reading viminfo registers when writing viminfo later.
1553 */
1554 static void
1555prepare_viminfo_registers(void)
1556{
1557 y_read_regs = ALLOC_CLEAR_MULT(yankreg_T, NUM_REGISTERS);
1558}
1559
1560 static void
1561finish_viminfo_registers(void)
1562{
1563 int i;
1564 int j;
1565
1566 if (y_read_regs != NULL)
1567 {
1568 for (i = 0; i < NUM_REGISTERS; ++i)
1569 if (y_read_regs[i].y_array != NULL)
1570 {
1571 for (j = 0; j < y_read_regs[i].y_size; j++)
1572 vim_free(y_read_regs[i].y_array[j]);
1573 vim_free(y_read_regs[i].y_array);
1574 }
1575 VIM_CLEAR(y_read_regs);
1576 }
1577}
1578
1579 static int
1580read_viminfo_register(vir_T *virp, int force)
1581{
1582 int eof;
1583 int do_it = TRUE;
1584 int size;
1585 int limit;
1586 int i;
1587 int set_prev = FALSE;
1588 char_u *str;
1589 char_u **array = NULL;
1590 int new_type = MCHAR; // init to shut up compiler
1591 colnr_T new_width = 0; // init to shut up compiler
1592 yankreg_T *y_current_p;
1593
1594 // We only get here (hopefully) if line[0] == '"'
1595 str = virp->vir_line + 1;
1596
1597 // If the line starts with "" this is the y_previous register.
1598 if (*str == '"')
1599 {
1600 set_prev = TRUE;
1601 str++;
1602 }
1603
1604 if (!ASCII_ISALNUM(*str) && *str != '-')
1605 {
Bram Moolenaar1d423ef2022-01-02 21:26:16 +00001606 if (viminfo_error("E577: ", _(e_illegal_register_name), virp->vir_line))
Bram Moolenaarc3328162019-07-23 22:15:25 +02001607 return TRUE; // too many errors, pretend end-of-file
1608 do_it = FALSE;
1609 }
1610 get_yank_register(*str++, FALSE);
1611 y_current_p = get_y_current();
1612 if (!force && y_current_p->y_array != NULL)
1613 do_it = FALSE;
1614
1615 if (*str == '@')
1616 {
1617 // "x@: register x used for @@
1618 if (force || get_execreg_lastc() == NUL)
1619 set_execreg_lastc(str[-1]);
1620 }
1621
1622 size = 0;
1623 limit = 100; // Optimized for registers containing <= 100 lines
1624 if (do_it)
1625 {
1626 // Build the new register in array[].
1627 // y_array is kept as-is until done.
1628 // The "do_it" flag is reset when something is wrong, in which case
1629 // array[] needs to be freed.
1630 if (set_prev)
1631 set_y_previous(y_current_p);
1632 array = ALLOC_MULT(char_u *, limit);
1633 str = skipwhite(skiptowhite(str));
1634 if (STRNCMP(str, "CHAR", 4) == 0)
1635 new_type = MCHAR;
1636 else if (STRNCMP(str, "BLOCK", 5) == 0)
1637 new_type = MBLOCK;
1638 else
1639 new_type = MLINE;
1640 // get the block width; if it's missing we get a zero, which is OK
1641 str = skipwhite(skiptowhite(str));
1642 new_width = getdigits(&str);
1643 }
1644
1645 while (!(eof = viminfo_readline(virp))
1646 && (virp->vir_line[0] == TAB || virp->vir_line[0] == '<'))
1647 {
1648 if (do_it)
1649 {
1650 if (size == limit)
1651 {
1652 char_u **new_array = (char_u **)
1653 alloc(limit * 2 * sizeof(char_u *));
1654
1655 if (new_array == NULL)
1656 {
1657 do_it = FALSE;
1658 break;
1659 }
1660 for (i = 0; i < limit; i++)
1661 new_array[i] = array[i];
1662 vim_free(array);
1663 array = new_array;
1664 limit *= 2;
1665 }
1666 str = viminfo_readstring(virp, 1, TRUE);
1667 if (str != NULL)
1668 array[size++] = str;
1669 else
1670 // error, don't store the result
1671 do_it = FALSE;
1672 }
1673 }
1674
1675 if (do_it)
1676 {
1677 // free y_array[]
1678 for (i = 0; i < y_current_p->y_size; i++)
1679 vim_free(y_current_p->y_array[i]);
1680 vim_free(y_current_p->y_array);
1681
1682 y_current_p->y_type = new_type;
1683 y_current_p->y_width = new_width;
1684 y_current_p->y_size = size;
1685 y_current_p->y_time_set = 0;
1686 if (size == 0)
1687 {
1688 y_current_p->y_array = NULL;
1689 }
1690 else
1691 {
1692 // Move the lines from array[] to y_array[].
1693 y_current_p->y_array = ALLOC_MULT(char_u *, size);
1694 for (i = 0; i < size; i++)
1695 {
1696 if (y_current_p->y_array == NULL)
1697 vim_free(array[i]);
1698 else
1699 y_current_p->y_array[i] = array[i];
1700 }
1701 }
1702 }
1703 else
1704 {
1705 // Free array[] if it was filled.
1706 for (i = 0; i < size; i++)
1707 vim_free(array[i]);
1708 }
1709 vim_free(array);
1710
1711 return eof;
1712}
1713
1714/*
1715 * Accept a new style register line from the viminfo, store it when it's new.
1716 */
1717 static void
1718handle_viminfo_register(garray_T *values, int force)
1719{
1720 bval_T *vp = (bval_T *)values->ga_data;
1721 int flags;
1722 int name;
1723 int type;
1724 int linecount;
1725 int width;
1726 time_t timestamp;
1727 yankreg_T *y_ptr;
1728 yankreg_T *y_regs_p = get_y_regs();
1729 int i;
1730
1731 // Check the format:
1732 // |{bartype},{flags},{name},{type},
1733 // {linecount},{width},{timestamp},"line1","line2"
1734 if (values->ga_len < 6
1735 || vp[0].bv_type != BVAL_NR
1736 || vp[1].bv_type != BVAL_NR
1737 || vp[2].bv_type != BVAL_NR
1738 || vp[3].bv_type != BVAL_NR
1739 || vp[4].bv_type != BVAL_NR
1740 || vp[5].bv_type != BVAL_NR)
1741 return;
1742 flags = vp[0].bv_nr;
1743 name = vp[1].bv_nr;
1744 if (name < 0 || name >= NUM_REGISTERS)
1745 return;
1746 type = vp[2].bv_nr;
1747 if (type != MCHAR && type != MLINE && type != MBLOCK)
1748 return;
1749 linecount = vp[3].bv_nr;
1750 if (values->ga_len < 6 + linecount)
1751 return;
1752 width = vp[4].bv_nr;
1753 if (width < 0)
1754 return;
1755
1756 if (y_read_regs != NULL)
1757 // Reading viminfo for merging and writing. Store the register
1758 // content, don't update the current registers.
1759 y_ptr = &y_read_regs[name];
1760 else
1761 y_ptr = &y_regs_p[name];
1762
1763 // Do not overwrite unless forced or the timestamp is newer.
1764 timestamp = (time_t)vp[5].bv_nr;
1765 if (y_ptr->y_array != NULL && !force
1766 && (timestamp == 0 || y_ptr->y_time_set > timestamp))
1767 return;
1768
1769 if (y_ptr->y_array != NULL)
1770 for (i = 0; i < y_ptr->y_size; i++)
1771 vim_free(y_ptr->y_array[i]);
1772 vim_free(y_ptr->y_array);
1773
1774 if (y_read_regs == NULL)
1775 {
1776 if (flags & REG_PREVIOUS)
1777 set_y_previous(y_ptr);
1778 if ((flags & REG_EXEC) && (force || get_execreg_lastc() == NUL))
1779 set_execreg_lastc(get_register_name(name));
1780 }
1781 y_ptr->y_type = type;
1782 y_ptr->y_width = width;
1783 y_ptr->y_size = linecount;
1784 y_ptr->y_time_set = timestamp;
1785 if (linecount == 0)
1786 {
1787 y_ptr->y_array = NULL;
1788 return;
1789 }
1790 y_ptr->y_array = ALLOC_MULT(char_u *, linecount);
1791 if (y_ptr->y_array == NULL)
1792 {
1793 y_ptr->y_size = 0; // ensure object state is consistent
1794 return;
1795 }
1796 for (i = 0; i < linecount; i++)
1797 {
1798 if (vp[i + 6].bv_allocated)
1799 {
1800 y_ptr->y_array[i] = vp[i + 6].bv_string;
1801 vp[i + 6].bv_string = NULL;
1802 }
1803 else
1804 y_ptr->y_array[i] = vim_strsave(vp[i + 6].bv_string);
1805 }
1806}
1807
1808 static void
1809write_viminfo_registers(FILE *fp)
1810{
1811 int i, j;
1812 char_u *type;
1813 char_u c;
1814 int num_lines;
1815 int max_num_lines;
1816 int max_kbyte;
1817 long len;
1818 yankreg_T *y_ptr;
1819 yankreg_T *y_regs_p = get_y_regs();;
1820
1821 fputs(_("\n# Registers:\n"), fp);
1822
1823 // Get '<' value, use old '"' value if '<' is not found.
1824 max_num_lines = get_viminfo_parameter('<');
1825 if (max_num_lines < 0)
1826 max_num_lines = get_viminfo_parameter('"');
1827 if (max_num_lines == 0)
1828 return;
1829 max_kbyte = get_viminfo_parameter('s');
1830 if (max_kbyte == 0)
1831 return;
1832
1833 for (i = 0; i < NUM_REGISTERS; i++)
1834 {
1835#ifdef FEAT_CLIPBOARD
1836 // Skip '*'/'+' register, we don't want them back next time
1837 if (i == STAR_REGISTER || i == PLUS_REGISTER)
1838 continue;
1839#endif
1840#ifdef FEAT_DND
1841 // Neither do we want the '~' register
1842 if (i == TILDE_REGISTER)
1843 continue;
1844#endif
1845 // When reading viminfo for merging and writing: Use the register from
1846 // viminfo if it's newer.
1847 if (y_read_regs != NULL
1848 && y_read_regs[i].y_array != NULL
1849 && (y_regs_p[i].y_array == NULL ||
1850 y_read_regs[i].y_time_set > y_regs_p[i].y_time_set))
1851 y_ptr = &y_read_regs[i];
1852 else if (y_regs_p[i].y_array == NULL)
1853 continue;
1854 else
1855 y_ptr = &y_regs_p[i];
1856
1857 // Skip empty registers.
1858 num_lines = y_ptr->y_size;
1859 if (num_lines == 0
1860 || (num_lines == 1 && y_ptr->y_type == MCHAR
1861 && *y_ptr->y_array[0] == NUL))
1862 continue;
1863
1864 if (max_kbyte > 0)
1865 {
1866 // Skip register if there is more text than the maximum size.
1867 len = 0;
1868 for (j = 0; j < num_lines; j++)
1869 len += (long)STRLEN(y_ptr->y_array[j]) + 1L;
1870 if (len > (long)max_kbyte * 1024L)
1871 continue;
1872 }
1873
1874 switch (y_ptr->y_type)
1875 {
1876 case MLINE:
1877 type = (char_u *)"LINE";
1878 break;
1879 case MCHAR:
1880 type = (char_u *)"CHAR";
1881 break;
1882 case MBLOCK:
1883 type = (char_u *)"BLOCK";
1884 break;
1885 default:
Bram Moolenaar1d423ef2022-01-02 21:26:16 +00001886 semsg(_(e_unknown_register_type_nr), y_ptr->y_type);
Bram Moolenaarc3328162019-07-23 22:15:25 +02001887 type = (char_u *)"LINE";
1888 break;
1889 }
1890 if (get_y_previous() == &y_regs_p[i])
1891 fprintf(fp, "\"");
1892 c = get_register_name(i);
1893 fprintf(fp, "\"%c", c);
1894 if (c == get_execreg_lastc())
1895 fprintf(fp, "@");
1896 fprintf(fp, "\t%s\t%d\n", type, (int)y_ptr->y_width);
1897
1898 // If max_num_lines < 0, then we save ALL the lines in the register
1899 if (max_num_lines > 0 && num_lines > max_num_lines)
1900 num_lines = max_num_lines;
1901 for (j = 0; j < num_lines; j++)
1902 {
1903 putc('\t', fp);
1904 viminfo_writestring(fp, y_ptr->y_array[j]);
1905 }
1906
1907 {
1908 int flags = 0;
1909 int remaining;
1910
1911 // New style with a bar line. Format:
1912 // |{bartype},{flags},{name},{type},
1913 // {linecount},{width},{timestamp},"line1","line2"
1914 // flags: REG_PREVIOUS - register is y_previous
1915 // REG_EXEC - used for @@
1916 if (get_y_previous() == &y_regs_p[i])
1917 flags |= REG_PREVIOUS;
1918 if (c == get_execreg_lastc())
1919 flags |= REG_EXEC;
1920 fprintf(fp, "|%d,%d,%d,%d,%d,%d,%ld", BARTYPE_REGISTER, flags,
1921 i, y_ptr->y_type, num_lines, (int)y_ptr->y_width,
1922 (long)y_ptr->y_time_set);
1923 // 11 chars for type/flags/name/type, 3 * 20 for numbers
1924 remaining = LSIZE - 71;
1925 for (j = 0; j < num_lines; j++)
1926 {
1927 putc(',', fp);
1928 --remaining;
1929 remaining = barline_writestring(fp, y_ptr->y_array[j],
1930 remaining);
1931 }
1932 putc('\n', fp);
1933 }
1934 }
1935}
1936
1937/*
1938 * Functions relating to reading/writing marks from viminfo
1939 */
1940
1941static xfmark_T *vi_namedfm = NULL;
Bram Moolenaarc3328162019-07-23 22:15:25 +02001942static xfmark_T *vi_jumplist = NULL;
1943static int vi_jumplist_len = 0;
Bram Moolenaarc3328162019-07-23 22:15:25 +02001944
1945 static void
1946write_one_mark(FILE *fp_out, int c, pos_T *pos)
1947{
1948 if (pos->lnum != 0)
1949 fprintf(fp_out, "\t%c\t%ld\t%d\n", c, (long)pos->lnum, (int)pos->col);
1950}
1951
1952 static void
1953write_buffer_marks(buf_T *buf, FILE *fp_out)
1954{
1955 int i;
1956 pos_T pos;
1957
1958 home_replace(NULL, buf->b_ffname, IObuff, IOSIZE, TRUE);
1959 fprintf(fp_out, "\n> ");
1960 viminfo_writestring(fp_out, IObuff);
1961
1962 // Write the last used timestamp as the lnum of the non-existing mark '*'.
1963 // Older Vims will ignore it and/or copy it.
1964 pos.lnum = (linenr_T)buf->b_last_used;
1965 pos.col = 0;
1966 write_one_mark(fp_out, '*', &pos);
1967
1968 write_one_mark(fp_out, '"', &buf->b_last_cursor);
1969 write_one_mark(fp_out, '^', &buf->b_last_insert);
1970 write_one_mark(fp_out, '.', &buf->b_last_change);
Bram Moolenaarc3328162019-07-23 22:15:25 +02001971 // changelist positions are stored oldest first
1972 for (i = 0; i < buf->b_changelistlen; ++i)
1973 {
1974 // skip duplicates
1975 if (i == 0 || !EQUAL_POS(buf->b_changelist[i - 1],
1976 buf->b_changelist[i]))
1977 write_one_mark(fp_out, '+', &buf->b_changelist[i]);
1978 }
Bram Moolenaarc3328162019-07-23 22:15:25 +02001979 for (i = 0; i < NMARKS; i++)
1980 write_one_mark(fp_out, 'a' + i, &buf->b_namedm[i]);
1981}
1982
1983/*
1984 * Return TRUE if marks for "buf" should not be written.
1985 */
1986 static int
1987skip_for_viminfo(buf_T *buf)
1988{
Bram Moolenaar6d4b2f52022-08-25 15:11:15 +01001989 return bt_terminal(buf) || removable(buf->b_ffname);
Bram Moolenaarc3328162019-07-23 22:15:25 +02001990}
1991
1992/*
1993 * Write all the named marks for all buffers.
1994 * When "buflist" is not NULL fill it with the buffers for which marks are to
1995 * be written.
1996 */
1997 static void
1998write_viminfo_marks(FILE *fp_out, garray_T *buflist)
1999{
2000 buf_T *buf;
2001 int is_mark_set;
2002 int i;
2003 win_T *win;
2004 tabpage_T *tp;
2005
2006 // Set b_last_cursor for the all buffers that have a window.
2007 FOR_ALL_TAB_WINDOWS(tp, win)
2008 set_last_cursor(win);
2009
2010 fputs(_("\n# History of marks within files (newest to oldest):\n"), fp_out);
2011 FOR_ALL_BUFFERS(buf)
2012 {
2013 // Only write something if buffer has been loaded and at least one
2014 // mark is set.
2015 if (buf->b_marks_read)
2016 {
2017 if (buf->b_last_cursor.lnum != 0)
2018 is_mark_set = TRUE;
2019 else
2020 {
2021 is_mark_set = FALSE;
2022 for (i = 0; i < NMARKS; i++)
2023 if (buf->b_namedm[i].lnum != 0)
2024 {
2025 is_mark_set = TRUE;
2026 break;
2027 }
2028 }
2029 if (is_mark_set && buf->b_ffname != NULL
2030 && buf->b_ffname[0] != NUL
2031 && !skip_for_viminfo(buf))
2032 {
2033 if (buflist == NULL)
2034 write_buffer_marks(buf, fp_out);
2035 else if (ga_grow(buflist, 1) == OK)
2036 ((buf_T **)buflist->ga_data)[buflist->ga_len++] = buf;
2037 }
2038 }
2039 }
2040}
2041
2042 static void
2043write_one_filemark(
2044 FILE *fp,
2045 xfmark_T *fm,
2046 int c1,
2047 int c2)
2048{
2049 char_u *name;
2050
2051 if (fm->fmark.mark.lnum == 0) // not set
2052 return;
2053
2054 if (fm->fmark.fnum != 0) // there is a buffer
2055 name = buflist_nr2name(fm->fmark.fnum, TRUE, FALSE);
2056 else
2057 name = fm->fname; // use name from .viminfo
2058 if (name != NULL && *name != NUL)
2059 {
2060 fprintf(fp, "%c%c %ld %ld ", c1, c2, (long)fm->fmark.mark.lnum,
2061 (long)fm->fmark.mark.col);
2062 viminfo_writestring(fp, name);
2063
2064 // Barline: |{bartype},{name},{lnum},{col},{timestamp},{filename}
2065 // size up to filename: 8 + 3 * 20
2066 fprintf(fp, "|%d,%d,%ld,%ld,%ld,", BARTYPE_MARK, c2,
2067 (long)fm->fmark.mark.lnum, (long)fm->fmark.mark.col,
2068 (long)fm->time_set);
2069 barline_writestring(fp, name, LSIZE - 70);
2070 putc('\n', fp);
2071 }
2072
2073 if (fm->fmark.fnum != 0)
2074 vim_free(name);
2075}
2076
2077 static void
2078write_viminfo_filemarks(FILE *fp)
2079{
2080 int i;
2081 char_u *name;
2082 buf_T *buf;
2083 xfmark_T *namedfm_p = get_namedfm();
2084 xfmark_T *fm;
2085 int vi_idx;
2086 int idx;
2087
2088 if (get_viminfo_parameter('f') == 0)
2089 return;
2090
2091 fputs(_("\n# File marks:\n"), fp);
2092
2093 // Write the filemarks 'A - 'Z
2094 for (i = 0; i < NMARKS; i++)
2095 {
2096 if (vi_namedfm != NULL
Bram Moolenaar8cd6cd82019-12-27 17:33:26 +01002097 && (vi_namedfm[i].time_set > namedfm_p[i].time_set))
Bram Moolenaarc3328162019-07-23 22:15:25 +02002098 fm = &vi_namedfm[i];
2099 else
2100 fm = &namedfm_p[i];
2101 write_one_filemark(fp, fm, '\'', i + 'A');
2102 }
2103
2104 // Find a mark that is the same file and position as the cursor.
2105 // That one, or else the last one is deleted.
2106 // Move '0 to '1, '1 to '2, etc. until the matching one or '9
2107 // Set the '0 mark to current cursor position.
2108 if (curbuf->b_ffname != NULL && !skip_for_viminfo(curbuf))
2109 {
2110 name = buflist_nr2name(curbuf->b_fnum, TRUE, FALSE);
2111 for (i = NMARKS; i < NMARKS + EXTRA_MARKS - 1; ++i)
2112 if (namedfm_p[i].fmark.mark.lnum == curwin->w_cursor.lnum
2113 && (namedfm_p[i].fname == NULL
2114 ? namedfm_p[i].fmark.fnum == curbuf->b_fnum
2115 : (name != NULL
2116 && STRCMP(name, namedfm_p[i].fname) == 0)))
2117 break;
2118 vim_free(name);
2119
2120 vim_free(namedfm_p[i].fname);
2121 for ( ; i > NMARKS; --i)
2122 namedfm_p[i] = namedfm_p[i - 1];
2123 namedfm_p[NMARKS].fmark.mark = curwin->w_cursor;
2124 namedfm_p[NMARKS].fmark.fnum = curbuf->b_fnum;
2125 namedfm_p[NMARKS].fname = NULL;
2126 namedfm_p[NMARKS].time_set = vim_time();
2127 }
2128
2129 // Write the filemarks '0 - '9. Newest (highest timestamp) first.
2130 vi_idx = NMARKS;
2131 idx = NMARKS;
2132 for (i = NMARKS; i < NMARKS + EXTRA_MARKS; i++)
2133 {
2134 xfmark_T *vi_fm = vi_namedfm != NULL ? &vi_namedfm[vi_idx] : NULL;
2135
2136 if (vi_fm != NULL
2137 && vi_fm->fmark.mark.lnum != 0
2138 && (vi_fm->time_set > namedfm_p[idx].time_set
2139 || namedfm_p[idx].fmark.mark.lnum == 0))
2140 {
2141 fm = vi_fm;
2142 ++vi_idx;
2143 }
2144 else
2145 {
2146 fm = &namedfm_p[idx++];
2147 if (vi_fm != NULL
2148 && vi_fm->fmark.mark.lnum == fm->fmark.mark.lnum
2149 && vi_fm->time_set == fm->time_set
2150 && ((vi_fm->fmark.fnum != 0
2151 && vi_fm->fmark.fnum == fm->fmark.fnum)
2152 || (vi_fm->fname != NULL
2153 && fm->fname != NULL
2154 && STRCMP(vi_fm->fname, fm->fname) == 0)))
2155 ++vi_idx; // skip duplicate
2156 }
2157 write_one_filemark(fp, fm, '\'', i - NMARKS + '0');
2158 }
2159
Bram Moolenaarc3328162019-07-23 22:15:25 +02002160 // Write the jumplist with -'
2161 fputs(_("\n# Jumplist (newest first):\n"), fp);
2162 setpcmark(); // add current cursor position
2163 cleanup_jumplist(curwin, FALSE);
2164 vi_idx = 0;
2165 idx = curwin->w_jumplistlen - 1;
2166 for (i = 0; i < JUMPLISTSIZE; ++i)
2167 {
2168 xfmark_T *vi_fm;
2169
2170 fm = idx >= 0 ? &curwin->w_jumplist[idx] : NULL;
Bram Moolenaar4ad739f2020-09-02 10:25:45 +02002171 vi_fm = (vi_jumplist != NULL && vi_idx < vi_jumplist_len)
2172 ? &vi_jumplist[vi_idx] : NULL;
Bram Moolenaarc3328162019-07-23 22:15:25 +02002173 if (fm == NULL && vi_fm == NULL)
2174 break;
2175 if (fm == NULL || (vi_fm != NULL && fm->time_set < vi_fm->time_set))
2176 {
2177 fm = vi_fm;
2178 ++vi_idx;
2179 }
2180 else
2181 --idx;
2182 if (fm->fmark.fnum == 0
2183 || ((buf = buflist_findnr(fm->fmark.fnum)) != NULL
2184 && !skip_for_viminfo(buf)))
2185 write_one_filemark(fp, fm, '-', '\'');
2186 }
Bram Moolenaarc3328162019-07-23 22:15:25 +02002187}
2188
2189/*
2190 * Compare functions for qsort() below, that compares b_last_used.
2191 */
Bram Moolenaar52410572019-10-27 05:12:45 +01002192 int
Bram Moolenaarc3328162019-07-23 22:15:25 +02002193buf_compare(const void *s1, const void *s2)
2194{
2195 buf_T *buf1 = *(buf_T **)s1;
2196 buf_T *buf2 = *(buf_T **)s2;
2197
2198 if (buf1->b_last_used == buf2->b_last_used)
2199 return 0;
2200 return buf1->b_last_used > buf2->b_last_used ? -1 : 1;
2201}
2202
2203/*
2204 * Handle marks in the viminfo file:
2205 * fp_out != NULL: copy marks, in time order with buffers in "buflist".
Bram Moolenaar3ff656f2021-02-10 19:22:15 +01002206 * fp_out == NULL && (flags & VIF_WANT_MARKS): read marks for curbuf
2207 * fp_out == NULL && (flags & VIF_ONLY_CURBUF): bail out after curbuf marks
Bram Moolenaarc3328162019-07-23 22:15:25 +02002208 * fp_out == NULL && (flags & VIF_GET_OLDFILES | VIF_FORCEIT): fill v:oldfiles
2209 */
2210 static void
2211copy_viminfo_marks(
2212 vir_T *virp,
2213 FILE *fp_out,
2214 garray_T *buflist,
2215 int eof,
2216 int flags)
2217{
2218 char_u *line = virp->vir_line;
2219 buf_T *buf;
2220 int num_marked_files;
2221 int load_marks;
2222 int copy_marks_out;
2223 char_u *str;
2224 int i;
2225 char_u *p;
2226 char_u *name_buf;
2227 pos_T pos;
2228#ifdef FEAT_EVAL
2229 list_T *list = NULL;
2230#endif
2231 int count = 0;
2232 int buflist_used = 0;
2233 buf_T *buflist_buf = NULL;
2234
2235 if ((name_buf = alloc(LSIZE)) == NULL)
2236 return;
2237 *name_buf = NUL;
2238
2239 if (fp_out != NULL && buflist->ga_len > 0)
2240 {
2241 // Sort the list of buffers on b_last_used.
2242 qsort(buflist->ga_data, (size_t)buflist->ga_len,
2243 sizeof(buf_T *), buf_compare);
2244 buflist_buf = ((buf_T **)buflist->ga_data)[0];
2245 }
2246
2247#ifdef FEAT_EVAL
2248 if (fp_out == NULL && (flags & (VIF_GET_OLDFILES | VIF_FORCEIT)))
2249 {
2250 list = list_alloc();
2251 if (list != NULL)
2252 set_vim_var_list(VV_OLDFILES, list);
2253 }
2254#endif
2255
2256 num_marked_files = get_viminfo_parameter('\'');
2257 while (!eof && (count < num_marked_files || fp_out == NULL))
2258 {
2259 if (line[0] != '>')
2260 {
2261 if (line[0] != '\n' && line[0] != '\r' && line[0] != '#')
2262 {
Bram Moolenaar1d423ef2022-01-02 21:26:16 +00002263 if (viminfo_error("E576: ", _(e_nonr_missing_gt), line))
Bram Moolenaarc3328162019-07-23 22:15:25 +02002264 break; // too many errors, return now
2265 }
2266 eof = vim_fgets(line, LSIZE, virp->vir_fd);
2267 continue; // Skip this dud line
2268 }
2269
2270 // Handle long line and translate escaped characters.
2271 // Find file name, set str to start.
2272 // Ignore leading and trailing white space.
2273 str = skipwhite(line + 1);
2274 str = viminfo_readstring(virp, (int)(str - virp->vir_line), FALSE);
2275 if (str == NULL)
2276 continue;
2277 p = str + STRLEN(str);
2278 while (p != str && (*p == NUL || vim_isspace(*p)))
2279 p--;
2280 if (*p)
2281 p++;
2282 *p = NUL;
2283
2284#ifdef FEAT_EVAL
2285 if (list != NULL)
2286 list_append_string(list, str, -1);
2287#endif
2288
2289 // If fp_out == NULL, load marks for current buffer.
2290 // If fp_out != NULL, copy marks for buffers not in buflist.
2291 load_marks = copy_marks_out = FALSE;
2292 if (fp_out == NULL)
2293 {
2294 if ((flags & VIF_WANT_MARKS) && curbuf->b_ffname != NULL)
2295 {
2296 if (*name_buf == NUL) // only need to do this once
2297 home_replace(NULL, curbuf->b_ffname, name_buf, LSIZE, TRUE);
2298 if (fnamecmp(str, name_buf) == 0)
2299 load_marks = TRUE;
2300 }
2301 }
2302 else // fp_out != NULL
2303 {
2304 // This is slow if there are many buffers!!
2305 FOR_ALL_BUFFERS(buf)
2306 if (buf->b_ffname != NULL)
2307 {
2308 home_replace(NULL, buf->b_ffname, name_buf, LSIZE, TRUE);
2309 if (fnamecmp(str, name_buf) == 0)
2310 break;
2311 }
2312
2313 // Copy marks if the buffer has not been loaded.
2314 if (buf == NULL || !buf->b_marks_read)
2315 {
2316 int did_read_line = FALSE;
2317
2318 if (buflist_buf != NULL)
2319 {
2320 // Read the next line. If it has the "*" mark compare the
2321 // time stamps. Write entries from "buflist" that are
2322 // newer.
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01002323 if (!viminfo_readline(virp) && line[0] == TAB)
Bram Moolenaarc3328162019-07-23 22:15:25 +02002324 {
2325 did_read_line = TRUE;
2326 if (line[1] == '*')
2327 {
2328 long ltime;
2329
2330 sscanf((char *)line + 2, "%ld ", &ltime);
2331 while ((time_T)ltime < buflist_buf->b_last_used)
2332 {
2333 write_buffer_marks(buflist_buf, fp_out);
2334 if (++count >= num_marked_files)
2335 break;
2336 if (++buflist_used == buflist->ga_len)
2337 {
2338 buflist_buf = NULL;
2339 break;
2340 }
2341 buflist_buf =
2342 ((buf_T **)buflist->ga_data)[buflist_used];
2343 }
2344 }
2345 else
2346 {
2347 // No timestamp, must be written by an older Vim.
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002348 // Assume all remaining buffers are older than
Bram Moolenaarc3328162019-07-23 22:15:25 +02002349 // ours.
2350 while (count < num_marked_files
2351 && buflist_used < buflist->ga_len)
2352 {
2353 buflist_buf = ((buf_T **)buflist->ga_data)
2354 [buflist_used++];
2355 write_buffer_marks(buflist_buf, fp_out);
2356 ++count;
2357 }
2358 buflist_buf = NULL;
2359 }
2360
2361 if (count >= num_marked_files)
2362 {
2363 vim_free(str);
2364 break;
2365 }
2366 }
2367 }
2368
2369 fputs("\n> ", fp_out);
2370 viminfo_writestring(fp_out, str);
2371 if (did_read_line)
2372 fputs((char *)line, fp_out);
2373
2374 count++;
2375 copy_marks_out = TRUE;
2376 }
2377 }
2378 vim_free(str);
2379
2380 pos.coladd = 0;
2381 while (!(eof = viminfo_readline(virp)) && line[0] == TAB)
2382 {
2383 if (load_marks)
2384 {
2385 if (line[1] != NUL)
2386 {
2387 unsigned u;
2388
2389 sscanf((char *)line + 2, "%ld %u", &pos.lnum, &u);
2390 pos.col = u;
2391 switch (line[1])
2392 {
2393 case '"': curbuf->b_last_cursor = pos; break;
2394 case '^': curbuf->b_last_insert = pos; break;
2395 case '.': curbuf->b_last_change = pos; break;
2396 case '+':
Bram Moolenaarc3328162019-07-23 22:15:25 +02002397 // changelist positions are stored oldest
2398 // first
2399 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2400 // list is full, remove oldest entry
2401 mch_memmove(curbuf->b_changelist,
2402 curbuf->b_changelist + 1,
2403 sizeof(pos_T) * (JUMPLISTSIZE - 1));
2404 else
2405 ++curbuf->b_changelistlen;
2406 curbuf->b_changelist[
2407 curbuf->b_changelistlen - 1] = pos;
Bram Moolenaarc3328162019-07-23 22:15:25 +02002408 break;
2409
2410 // Using the line number for the last-used
2411 // timestamp.
2412 case '*': curbuf->b_last_used = pos.lnum; break;
2413
2414 default: if ((i = line[1] - 'a') >= 0 && i < NMARKS)
2415 curbuf->b_namedm[i] = pos;
2416 }
2417 }
2418 }
2419 else if (copy_marks_out)
2420 fputs((char *)line, fp_out);
2421 }
2422
2423 if (load_marks)
2424 {
Bram Moolenaarc3328162019-07-23 22:15:25 +02002425 win_T *wp;
2426
2427 FOR_ALL_WINDOWS(wp)
2428 {
2429 if (wp->w_buffer == curbuf)
2430 wp->w_changelistidx = curbuf->b_changelistlen;
2431 }
Bram Moolenaar3ff656f2021-02-10 19:22:15 +01002432 if (flags & VIF_ONLY_CURBUF)
2433 break;
Bram Moolenaarc3328162019-07-23 22:15:25 +02002434 }
2435 }
2436
2437 if (fp_out != NULL)
2438 // Write any remaining entries from buflist.
2439 while (count < num_marked_files && buflist_used < buflist->ga_len)
2440 {
2441 buflist_buf = ((buf_T **)buflist->ga_data)[buflist_used++];
2442 write_buffer_marks(buflist_buf, fp_out);
2443 ++count;
2444 }
2445
2446 vim_free(name_buf);
2447}
2448
2449/*
2450 * Read marks for the current buffer from the viminfo file, when we support
2451 * buffer marks and the buffer has a name.
2452 */
2453 void
2454check_marks_read(void)
2455{
2456 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2457 && curbuf->b_ffname != NULL)
Bram Moolenaar3ff656f2021-02-10 19:22:15 +01002458 read_viminfo(NULL, VIF_WANT_MARKS | VIF_ONLY_CURBUF);
Bram Moolenaarc3328162019-07-23 22:15:25 +02002459
2460 // Always set b_marks_read; needed when 'viminfo' is changed to include
2461 // the ' parameter after opening a buffer.
2462 curbuf->b_marks_read = TRUE;
2463}
2464
2465 static int
2466read_viminfo_filemark(vir_T *virp, int force)
2467{
2468 char_u *str;
2469 xfmark_T *namedfm_p = get_namedfm();
2470 xfmark_T *fm;
2471 int i;
2472
2473 // We only get here if line[0] == '\'' or '-'.
2474 // Illegal mark names are ignored (for future expansion).
2475 str = virp->vir_line + 1;
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002476 if (*str <= 127
2477 && ((*virp->vir_line == '\''
2478 && (VIM_ISDIGIT(*str) || isupper(*str)))
Bram Moolenaarc3328162019-07-23 22:15:25 +02002479 || (*virp->vir_line == '-' && *str == '\'')))
2480 {
2481 if (*str == '\'')
2482 {
Bram Moolenaarc3328162019-07-23 22:15:25 +02002483 // If the jumplist isn't full insert fmark as oldest entry
2484 if (curwin->w_jumplistlen == JUMPLISTSIZE)
2485 fm = NULL;
2486 else
2487 {
2488 for (i = curwin->w_jumplistlen; i > 0; --i)
2489 curwin->w_jumplist[i] = curwin->w_jumplist[i - 1];
2490 ++curwin->w_jumplistidx;
2491 ++curwin->w_jumplistlen;
2492 fm = &curwin->w_jumplist[0];
2493 fm->fmark.mark.lnum = 0;
2494 fm->fname = NULL;
2495 }
Bram Moolenaarc3328162019-07-23 22:15:25 +02002496 }
2497 else if (VIM_ISDIGIT(*str))
2498 fm = &namedfm_p[*str - '0' + NMARKS];
2499 else
2500 fm = &namedfm_p[*str - 'A'];
2501 if (fm != NULL && (fm->fmark.mark.lnum == 0 || force))
2502 {
2503 str = skipwhite(str + 1);
2504 fm->fmark.mark.lnum = getdigits(&str);
2505 str = skipwhite(str);
2506 fm->fmark.mark.col = getdigits(&str);
2507 fm->fmark.mark.coladd = 0;
2508 fm->fmark.fnum = 0;
2509 str = skipwhite(str);
2510 vim_free(fm->fname);
2511 fm->fname = viminfo_readstring(virp, (int)(str - virp->vir_line),
2512 FALSE);
2513 fm->time_set = 0;
2514 }
2515 }
2516 return vim_fgets(virp->vir_line, LSIZE, virp->vir_fd);
2517}
2518
2519/*
2520 * Prepare for reading viminfo marks when writing viminfo later.
2521 */
2522 static void
2523prepare_viminfo_marks(void)
2524{
2525 vi_namedfm = ALLOC_CLEAR_MULT(xfmark_T, NMARKS + EXTRA_MARKS);
Bram Moolenaarc3328162019-07-23 22:15:25 +02002526 vi_jumplist = ALLOC_CLEAR_MULT(xfmark_T, JUMPLISTSIZE);
2527 vi_jumplist_len = 0;
Bram Moolenaarc3328162019-07-23 22:15:25 +02002528}
2529
2530 static void
2531finish_viminfo_marks(void)
2532{
2533 int i;
2534
2535 if (vi_namedfm != NULL)
2536 {
2537 for (i = 0; i < NMARKS + EXTRA_MARKS; ++i)
2538 vim_free(vi_namedfm[i].fname);
2539 VIM_CLEAR(vi_namedfm);
2540 }
Bram Moolenaarc3328162019-07-23 22:15:25 +02002541 if (vi_jumplist != NULL)
2542 {
2543 for (i = 0; i < vi_jumplist_len; ++i)
2544 vim_free(vi_jumplist[i].fname);
2545 VIM_CLEAR(vi_jumplist);
2546 }
Bram Moolenaarc3328162019-07-23 22:15:25 +02002547}
2548
2549/*
2550 * Accept a new style mark line from the viminfo, store it when it's new.
2551 */
2552 static void
2553handle_viminfo_mark(garray_T *values, int force)
2554{
2555 bval_T *vp = (bval_T *)values->ga_data;
2556 int name;
2557 linenr_T lnum;
2558 colnr_T col;
2559 time_t timestamp;
2560 xfmark_T *fm = NULL;
2561
2562 // Check the format:
2563 // |{bartype},{name},{lnum},{col},{timestamp},{filename}
2564 if (values->ga_len < 5
2565 || vp[0].bv_type != BVAL_NR
2566 || vp[1].bv_type != BVAL_NR
2567 || vp[2].bv_type != BVAL_NR
2568 || vp[3].bv_type != BVAL_NR
2569 || vp[4].bv_type != BVAL_STRING)
2570 return;
2571
2572 name = vp[0].bv_nr;
2573 if (name != '\'' && !VIM_ISDIGIT(name) && !ASCII_ISUPPER(name))
2574 return;
2575 lnum = vp[1].bv_nr;
2576 col = vp[2].bv_nr;
2577 if (lnum <= 0 || col < 0)
2578 return;
2579 timestamp = (time_t)vp[3].bv_nr;
2580
2581 if (name == '\'')
2582 {
Bram Moolenaarc3328162019-07-23 22:15:25 +02002583 if (vi_jumplist != NULL)
2584 {
2585 if (vi_jumplist_len < JUMPLISTSIZE)
2586 fm = &vi_jumplist[vi_jumplist_len++];
2587 }
2588 else
2589 {
2590 int idx;
2591 int i;
2592
2593 // If we have a timestamp insert it in the right place.
2594 if (timestamp != 0)
2595 {
2596 for (idx = curwin->w_jumplistlen - 1; idx >= 0; --idx)
2597 if (curwin->w_jumplist[idx].time_set < timestamp)
2598 {
2599 ++idx;
2600 break;
2601 }
2602 // idx cannot be zero now
2603 if (idx < 0 && curwin->w_jumplistlen < JUMPLISTSIZE)
2604 // insert as the oldest entry
2605 idx = 0;
2606 }
2607 else if (curwin->w_jumplistlen < JUMPLISTSIZE)
2608 // insert as oldest entry
2609 idx = 0;
2610 else
2611 idx = -1;
2612
2613 if (idx >= 0)
2614 {
2615 if (curwin->w_jumplistlen == JUMPLISTSIZE)
2616 {
2617 // Drop the oldest entry.
2618 --idx;
2619 vim_free(curwin->w_jumplist[0].fname);
2620 for (i = 0; i < idx; ++i)
2621 curwin->w_jumplist[i] = curwin->w_jumplist[i + 1];
2622 }
2623 else
2624 {
2625 // Move newer entries forward.
2626 for (i = curwin->w_jumplistlen; i > idx; --i)
2627 curwin->w_jumplist[i] = curwin->w_jumplist[i - 1];
2628 ++curwin->w_jumplistidx;
2629 ++curwin->w_jumplistlen;
2630 }
2631 fm = &curwin->w_jumplist[idx];
2632 fm->fmark.mark.lnum = 0;
2633 fm->fname = NULL;
2634 fm->time_set = 0;
2635 }
2636 }
Bram Moolenaarc3328162019-07-23 22:15:25 +02002637 }
2638 else
2639 {
2640 int idx;
2641 xfmark_T *namedfm_p = get_namedfm();
2642
2643 if (VIM_ISDIGIT(name))
2644 {
2645 if (vi_namedfm != NULL)
2646 idx = name - '0' + NMARKS;
2647 else
2648 {
2649 int i;
2650
2651 // Do not use the name from the viminfo file, insert in time
2652 // order.
2653 for (idx = NMARKS; idx < NMARKS + EXTRA_MARKS; ++idx)
2654 if (namedfm_p[idx].time_set < timestamp)
2655 break;
2656 if (idx == NMARKS + EXTRA_MARKS)
2657 // All existing entries are newer.
2658 return;
2659 i = NMARKS + EXTRA_MARKS - 1;
2660
2661 vim_free(namedfm_p[i].fname);
2662 for ( ; i > idx; --i)
2663 namedfm_p[i] = namedfm_p[i - 1];
2664 namedfm_p[idx].fname = NULL;
2665 }
2666 }
2667 else
2668 idx = name - 'A';
2669 if (vi_namedfm != NULL)
2670 fm = &vi_namedfm[idx];
2671 else
2672 fm = &namedfm_p[idx];
2673 }
2674
2675 if (fm != NULL)
2676 {
2677 if (vi_namedfm != NULL || fm->fmark.mark.lnum == 0
2678 || fm->time_set < timestamp || force)
2679 {
2680 fm->fmark.mark.lnum = lnum;
2681 fm->fmark.mark.col = col;
2682 fm->fmark.mark.coladd = 0;
2683 fm->fmark.fnum = 0;
2684 vim_free(fm->fname);
2685 if (vp[4].bv_allocated)
2686 {
2687 fm->fname = vp[4].bv_string;
2688 vp[4].bv_string = NULL;
2689 }
2690 else
2691 fm->fname = vim_strsave(vp[4].bv_string);
2692 fm->time_set = timestamp;
2693 }
2694 }
2695}
2696
2697 static int
2698read_viminfo_barline(vir_T *virp, int got_encoding, int force, int writing)
2699{
2700 char_u *p = virp->vir_line + 1;
2701 int bartype;
2702 garray_T values;
2703 bval_T *vp;
2704 int i;
2705 int read_next = TRUE;
2706
Bram Moolenaar6bd1d772019-10-09 22:01:25 +02002707 // The format is: |{bartype},{value},...
2708 // For a very long string:
2709 // |{bartype},>{length of "{text}{text2}"}
2710 // |<{text1}
2711 // |<{text2},{value}
2712 // For a long line not using a string
2713 // |{bartype},{lots of values},>
2714 // |<{value},{value}
Bram Moolenaarc3328162019-07-23 22:15:25 +02002715 if (*p == '<')
2716 {
2717 // Continuation line of an unrecognized item.
2718 if (writing)
Bram Moolenaar9f1a39a2022-01-08 15:39:39 +00002719 ga_copy_string(&virp->vir_barlines, virp->vir_line);
Bram Moolenaarc3328162019-07-23 22:15:25 +02002720 }
2721 else
2722 {
2723 ga_init2(&values, sizeof(bval_T), 20);
2724 bartype = getdigits(&p);
2725 switch (bartype)
2726 {
2727 case BARTYPE_VERSION:
2728 // Only use the version when it comes before the encoding.
2729 // If it comes later it was copied by a Vim version that
2730 // doesn't understand the version.
2731 if (!got_encoding)
2732 {
2733 read_next = barline_parse(virp, p, &values);
2734 vp = (bval_T *)values.ga_data;
2735 if (values.ga_len > 0 && vp->bv_type == BVAL_NR)
2736 virp->vir_version = vp->bv_nr;
2737 }
2738 break;
2739
2740 case BARTYPE_HISTORY:
2741 read_next = barline_parse(virp, p, &values);
2742 handle_viminfo_history(&values, writing);
2743 break;
2744
2745 case BARTYPE_REGISTER:
2746 read_next = barline_parse(virp, p, &values);
2747 handle_viminfo_register(&values, force);
2748 break;
2749
2750 case BARTYPE_MARK:
2751 read_next = barline_parse(virp, p, &values);
2752 handle_viminfo_mark(&values, force);
2753 break;
2754
2755 default:
2756 // copy unrecognized line (for future use)
2757 if (writing)
Bram Moolenaar9f1a39a2022-01-08 15:39:39 +00002758 ga_copy_string(&virp->vir_barlines, virp->vir_line);
Bram Moolenaarc3328162019-07-23 22:15:25 +02002759 }
2760 for (i = 0; i < values.ga_len; ++i)
2761 {
2762 vp = (bval_T *)values.ga_data + i;
2763 if (vp->bv_type == BVAL_STRING && vp->bv_allocated)
2764 vim_free(vp->bv_string);
Bram Moolenaar408030e2020-02-10 22:44:32 +01002765 vim_free(vp->bv_tofree);
Bram Moolenaarc3328162019-07-23 22:15:25 +02002766 }
2767 ga_clear(&values);
2768 }
2769
2770 if (read_next)
2771 return viminfo_readline(virp);
2772 return FALSE;
2773}
2774
Bram Moolenaardefa0672019-07-21 19:25:37 +02002775/*
2776 * read_viminfo_up_to_marks() -- Only called from do_viminfo(). Reads in the
2777 * first part of the viminfo file which contains everything but the marks that
2778 * are local to a file. Returns TRUE when end-of-file is reached. -- webb
2779 */
2780 static int
2781read_viminfo_up_to_marks(
2782 vir_T *virp,
2783 int forceit,
2784 int writing)
2785{
2786 int eof;
2787 buf_T *buf;
2788 int got_encoding = FALSE;
2789
Bram Moolenaardefa0672019-07-21 19:25:37 +02002790 prepare_viminfo_history(forceit ? 9999 : 0, writing);
Bram Moolenaardefa0672019-07-21 19:25:37 +02002791
2792 eof = viminfo_readline(virp);
2793 while (!eof && virp->vir_line[0] != '>')
2794 {
2795 switch (virp->vir_line[0])
2796 {
2797 // Characters reserved for future expansion, ignored now
2798 case '+': // "+40 /path/dir file", for running vim without args
2799 case '^': // to be defined
2800 case '<': // long line - ignored
2801 // A comment or empty line.
2802 case NUL:
2803 case '\r':
2804 case '\n':
2805 case '#':
2806 eof = viminfo_readline(virp);
2807 break;
2808 case '|':
2809 eof = read_viminfo_barline(virp, got_encoding,
2810 forceit, writing);
2811 break;
2812 case '*': // "*encoding=value"
2813 got_encoding = TRUE;
2814 eof = viminfo_encoding(virp);
2815 break;
2816 case '!': // global variable
2817#ifdef FEAT_EVAL
2818 eof = read_viminfo_varlist(virp, writing);
2819#else
2820 eof = viminfo_readline(virp);
2821#endif
2822 break;
2823 case '%': // entry for buffer list
2824 eof = read_viminfo_bufferlist(virp, writing);
2825 break;
2826 case '"':
2827 // When registers are in bar lines skip the old style register
2828 // lines.
2829 if (virp->vir_version < VIMINFO_VERSION_WITH_REGISTERS)
2830 eof = read_viminfo_register(virp, forceit);
2831 else
2832 do {
2833 eof = viminfo_readline(virp);
2834 } while (!eof && (virp->vir_line[0] == TAB
2835 || virp->vir_line[0] == '<'));
2836 break;
2837 case '/': // Search string
2838 case '&': // Substitute search string
2839 case '~': // Last search string, followed by '/' or '&'
2840 eof = read_viminfo_search_pattern(virp, forceit);
2841 break;
2842 case '$':
2843 eof = read_viminfo_sub_string(virp, forceit);
2844 break;
2845 case ':':
2846 case '?':
2847 case '=':
2848 case '@':
Bram Moolenaardefa0672019-07-21 19:25:37 +02002849 // When history is in bar lines skip the old style history
2850 // lines.
2851 if (virp->vir_version < VIMINFO_VERSION_WITH_HISTORY)
2852 eof = read_viminfo_history(virp, writing);
2853 else
Bram Moolenaardefa0672019-07-21 19:25:37 +02002854 eof = viminfo_readline(virp);
2855 break;
2856 case '-':
2857 case '\'':
2858 // When file marks are in bar lines skip the old style lines.
2859 if (virp->vir_version < VIMINFO_VERSION_WITH_MARKS)
2860 eof = read_viminfo_filemark(virp, forceit);
2861 else
2862 eof = viminfo_readline(virp);
2863 break;
2864 default:
Bram Moolenaar1d423ef2022-01-02 21:26:16 +00002865 if (viminfo_error("E575: ", _(e_illegal_starting_char),
Bram Moolenaardefa0672019-07-21 19:25:37 +02002866 virp->vir_line))
2867 eof = TRUE;
2868 else
2869 eof = viminfo_readline(virp);
2870 break;
2871 }
2872 }
2873
Bram Moolenaardefa0672019-07-21 19:25:37 +02002874 // Finish reading history items.
2875 if (!writing)
2876 finish_viminfo_history(virp);
Bram Moolenaardefa0672019-07-21 19:25:37 +02002877
2878 // Change file names to buffer numbers for fmarks.
2879 FOR_ALL_BUFFERS(buf)
2880 fmarks_check_names(buf);
2881
2882 return eof;
2883}
2884
2885/*
2886 * do_viminfo() -- Should only be called from read_viminfo() & write_viminfo().
2887 */
2888 static void
2889do_viminfo(FILE *fp_in, FILE *fp_out, int flags)
2890{
2891 int eof = FALSE;
2892 vir_T vir;
2893 int merge = FALSE;
2894 int do_copy_marks = FALSE;
2895 garray_T buflist;
2896
2897 if ((vir.vir_line = alloc(LSIZE)) == NULL)
2898 return;
2899 vir.vir_fd = fp_in;
2900 vir.vir_conv.vc_type = CONV_NONE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002901 ga_init2(&vir.vir_barlines, sizeof(char_u *), 100);
Bram Moolenaardefa0672019-07-21 19:25:37 +02002902 vir.vir_version = -1;
2903
2904 if (fp_in != NULL)
2905 {
2906 if (flags & VIF_WANT_INFO)
2907 {
2908 if (fp_out != NULL)
2909 {
2910 // Registers and marks are read and kept separate from what
2911 // this Vim is using. They are merged when writing.
2912 prepare_viminfo_registers();
2913 prepare_viminfo_marks();
2914 }
2915
2916 eof = read_viminfo_up_to_marks(&vir,
2917 flags & VIF_FORCEIT, fp_out != NULL);
2918 merge = TRUE;
2919 }
2920 else if (flags != 0)
2921 // Skip info, find start of marks
2922 while (!(eof = viminfo_readline(&vir))
2923 && vir.vir_line[0] != '>')
2924 ;
2925
Bram Moolenaar3ff656f2021-02-10 19:22:15 +01002926 do_copy_marks = (flags & (VIF_WANT_MARKS | VIF_ONLY_CURBUF
2927 | VIF_GET_OLDFILES | VIF_FORCEIT));
Bram Moolenaardefa0672019-07-21 19:25:37 +02002928 }
2929
2930 if (fp_out != NULL)
2931 {
2932 // Write the info:
2933 fprintf(fp_out, _("# This viminfo file was generated by Vim %s.\n"),
2934 VIM_VERSION_MEDIUM);
2935 fputs(_("# You may edit it if you're careful!\n\n"), fp_out);
2936 write_viminfo_version(fp_out);
2937 fputs(_("# Value of 'encoding' when this file was written\n"), fp_out);
2938 fprintf(fp_out, "*encoding=%s\n\n", p_enc);
2939 write_viminfo_search_pattern(fp_out);
2940 write_viminfo_sub_string(fp_out);
Bram Moolenaardefa0672019-07-21 19:25:37 +02002941 write_viminfo_history(fp_out, merge);
Bram Moolenaardefa0672019-07-21 19:25:37 +02002942 write_viminfo_registers(fp_out);
2943 finish_viminfo_registers();
2944#ifdef FEAT_EVAL
2945 write_viminfo_varlist(fp_out);
2946#endif
2947 write_viminfo_filemarks(fp_out);
2948 finish_viminfo_marks();
2949 write_viminfo_bufferlist(fp_out);
2950 write_viminfo_barlines(&vir, fp_out);
2951
2952 if (do_copy_marks)
2953 ga_init2(&buflist, sizeof(buf_T *), 50);
2954 write_viminfo_marks(fp_out, do_copy_marks ? &buflist : NULL);
2955 }
2956
2957 if (do_copy_marks)
2958 {
2959 copy_viminfo_marks(&vir, fp_out, &buflist, eof, flags);
2960 if (fp_out != NULL)
2961 ga_clear(&buflist);
2962 }
2963
2964 vim_free(vir.vir_line);
2965 if (vir.vir_conv.vc_type != CONV_NONE)
2966 convert_setup(&vir.vir_conv, NULL, NULL);
2967 ga_clear_strings(&vir.vir_barlines);
2968}
2969
2970/*
2971 * read_viminfo() -- Read the viminfo file. Registers etc. which are already
2972 * set are not over-written unless "flags" includes VIF_FORCEIT. -- webb
2973 */
2974 int
2975read_viminfo(
2976 char_u *file, // file name or NULL to use default name
2977 int flags) // VIF_WANT_INFO et al.
2978{
2979 FILE *fp;
2980 char_u *fname;
Bram Moolenaarb86abad2020-08-01 16:08:19 +02002981 stat_T st; // mch_stat() of existing viminfo file
Bram Moolenaardefa0672019-07-21 19:25:37 +02002982
2983 if (no_viminfo())
2984 return FAIL;
2985
2986 fname = viminfo_filename(file); // get file name in allocated buffer
2987 if (fname == NULL)
2988 return FAIL;
2989 fp = mch_fopen((char *)fname, READBIN);
2990
2991 if (p_verbose > 0)
2992 {
2993 verbose_enter();
Bram Moolenaardb99f9f2020-03-23 22:12:22 +01002994 smsg(_("Reading viminfo file \"%s\"%s%s%s%s"),
Bram Moolenaardefa0672019-07-21 19:25:37 +02002995 fname,
2996 (flags & VIF_WANT_INFO) ? _(" info") : "",
2997 (flags & VIF_WANT_MARKS) ? _(" marks") : "",
2998 (flags & VIF_GET_OLDFILES) ? _(" oldfiles") : "",
2999 fp == NULL ? _(" FAILED") : "");
3000 verbose_leave();
3001 }
3002
3003 vim_free(fname);
3004 if (fp == NULL)
3005 return FAIL;
Bram Moolenaarb86abad2020-08-01 16:08:19 +02003006 if (mch_fstat(fileno(fp), &st) < 0 || S_ISDIR(st.st_mode))
3007 {
3008 fclose(fp);
3009 return FAIL;
3010 }
Bram Moolenaardefa0672019-07-21 19:25:37 +02003011
3012 viminfo_errcnt = 0;
3013 do_viminfo(fp, NULL, flags);
3014
3015 fclose(fp);
3016 return OK;
3017}
3018
3019/*
3020 * Write the viminfo file. The old one is read in first so that effectively a
3021 * merge of current info and old info is done. This allows multiple vims to
3022 * run simultaneously, without losing any marks etc.
3023 * If "forceit" is TRUE, then the old file is not read in, and only internal
3024 * info is written to the file.
3025 */
3026 void
3027write_viminfo(char_u *file, int forceit)
3028{
3029 char_u *fname;
3030 FILE *fp_in = NULL; // input viminfo file, if any
3031 FILE *fp_out = NULL; // output viminfo file
3032 char_u *tempname = NULL; // name of temp viminfo file
3033 stat_T st_new; // mch_stat() of potential new file
Bram Moolenaarb86abad2020-08-01 16:08:19 +02003034 stat_T st_old; // mch_stat() of existing viminfo file
Bram Moolenaardefa0672019-07-21 19:25:37 +02003035#if defined(UNIX) || defined(VMS)
3036 mode_t umask_save;
3037#endif
3038#ifdef UNIX
3039 int shortname = FALSE; // use 8.3 file name
Bram Moolenaardefa0672019-07-21 19:25:37 +02003040#endif
3041#ifdef MSWIN
3042 int hidden = FALSE;
3043#endif
3044
3045 if (no_viminfo())
3046 return;
3047
3048 fname = viminfo_filename(file); // may set to default if NULL
3049 if (fname == NULL)
3050 return;
3051
3052 fp_in = mch_fopen((char *)fname, READBIN);
3053 if (fp_in == NULL)
3054 {
3055 int fd;
3056
3057 // if it does exist, but we can't read it, don't try writing
3058 if (mch_stat((char *)fname, &st_new) == 0)
3059 goto end;
3060
3061 // Create the new .viminfo non-accessible for others, because it may
3062 // contain text from non-accessible documents. It is up to the user to
3063 // widen access (e.g. to a group). This may also fail if there is a
3064 // race condition, then just give up.
3065 fd = mch_open((char *)fname,
3066 O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW, 0600);
3067 if (fd < 0)
3068 goto end;
3069 fp_out = fdopen(fd, WRITEBIN);
3070 }
3071 else
3072 {
Bram Moolenaar6bd1d772019-10-09 22:01:25 +02003073 // There is an existing viminfo file. Create a temporary file to
3074 // write the new viminfo into, in the same directory as the
3075 // existing viminfo file, which will be renamed once all writing is
3076 // successful.
Bram Moolenaarb86abad2020-08-01 16:08:19 +02003077 if (mch_fstat(fileno(fp_in), &st_old) < 0
3078 || S_ISDIR(st_old.st_mode)
Bram Moolenaardefa0672019-07-21 19:25:37 +02003079#ifdef UNIX
Bram Moolenaarb86abad2020-08-01 16:08:19 +02003080 // For Unix we check the owner of the file. It's not very nice
3081 // to overwrite a user's viminfo file after a "su root", with a
3082 // viminfo file that the user can't read.
3083 || (getuid() != ROOT_UID
3084 && !(st_old.st_uid == getuid()
3085 ? (st_old.st_mode & 0200)
3086 : (st_old.st_gid == getgid()
3087 ? (st_old.st_mode & 0020)
3088 : (st_old.st_mode & 0002))))
3089#endif
3090 )
Bram Moolenaardefa0672019-07-21 19:25:37 +02003091 {
3092 int tt = msg_didany;
3093
Bram Moolenaar13608d82022-08-29 15:06:50 +01003094 // avoid a wait_return() for this message, it's annoying
Bram Moolenaarc553a212021-12-26 20:20:34 +00003095 semsg(_(e_viminfo_file_is_not_writable_str), fname);
Bram Moolenaardefa0672019-07-21 19:25:37 +02003096 msg_didany = tt;
3097 fclose(fp_in);
3098 goto end;
3099 }
Bram Moolenaardefa0672019-07-21 19:25:37 +02003100#ifdef MSWIN
3101 // Get the file attributes of the existing viminfo file.
3102 hidden = mch_ishidden(fname);
3103#endif
3104
Bram Moolenaar6bd1d772019-10-09 22:01:25 +02003105 // Make tempname, find one that does not exist yet.
3106 // Beware of a race condition: If someone logs out and all Vim
3107 // instances exit at the same time a temp file might be created between
3108 // stat() and open(). Use mch_open() with O_EXCL to avoid that.
3109 // May try twice: Once normal and once with shortname set, just in
3110 // case somebody puts his viminfo file in an 8.3 filesystem.
Bram Moolenaardefa0672019-07-21 19:25:37 +02003111 for (;;)
3112 {
3113 int next_char = 'z';
3114 char_u *wp;
3115
3116 tempname = buf_modname(
3117#ifdef UNIX
3118 shortname,
3119#else
3120 FALSE,
3121#endif
3122 fname,
3123#ifdef VMS
3124 (char_u *)"-tmp",
3125#else
3126 (char_u *)".tmp",
3127#endif
3128 FALSE);
3129 if (tempname == NULL) // out of memory
3130 break;
3131
Bram Moolenaar6bd1d772019-10-09 22:01:25 +02003132 // Try a series of names. Change one character, just before
3133 // the extension. This should also work for an 8.3
3134 // file name, when after adding the extension it still is
3135 // the same file as the original.
Bram Moolenaardefa0672019-07-21 19:25:37 +02003136 wp = tempname + STRLEN(tempname) - 5;
3137 if (wp < gettail(tempname)) // empty file name?
3138 wp = gettail(tempname);
3139 for (;;)
3140 {
Bram Moolenaar6bd1d772019-10-09 22:01:25 +02003141 // Check if tempfile already exists. Never overwrite an
3142 // existing file!
Bram Moolenaardefa0672019-07-21 19:25:37 +02003143 if (mch_stat((char *)tempname, &st_new) == 0)
3144 {
3145#ifdef UNIX
Bram Moolenaar6bd1d772019-10-09 22:01:25 +02003146 // Check if tempfile is same as original file. May happen
3147 // when modname() gave the same file back. E.g. silly
3148 // link, or file name-length reached. Try again with
3149 // shortname set.
Bram Moolenaardefa0672019-07-21 19:25:37 +02003150 if (!shortname && st_new.st_dev == st_old.st_dev
3151 && st_new.st_ino == st_old.st_ino)
3152 {
3153 VIM_CLEAR(tempname);
3154 shortname = TRUE;
3155 break;
3156 }
3157#endif
3158 }
3159 else
3160 {
3161 // Try creating the file exclusively. This may fail if
3162 // another Vim tries to do it at the same time.
3163#ifdef VMS
3164 // fdopen() fails for some reason
3165 umask_save = umask(077);
3166 fp_out = mch_fopen((char *)tempname, WRITEBIN);
3167 (void)umask(umask_save);
3168#else
3169 int fd;
3170
3171 // Use mch_open() to be able to use O_NOFOLLOW and set file
3172 // protection:
3173 // Unix: same as original file, but strip s-bit. Reset
3174 // umask to avoid it getting in the way.
3175 // Others: r&w for user only.
3176# ifdef UNIX
3177 umask_save = umask(0);
3178 fd = mch_open((char *)tempname,
3179 O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW,
3180 (int)((st_old.st_mode & 0777) | 0600));
3181 (void)umask(umask_save);
3182# else
3183 fd = mch_open((char *)tempname,
3184 O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW, 0600);
3185# endif
3186 if (fd < 0)
3187 {
3188 fp_out = NULL;
3189# ifdef EEXIST
3190 // Avoid trying lots of names while the problem is lack
3191 // of permission, only retry if the file already
3192 // exists.
3193 if (errno != EEXIST)
3194 break;
3195# endif
3196 }
3197 else
3198 fp_out = fdopen(fd, WRITEBIN);
3199#endif // VMS
3200 if (fp_out != NULL)
3201 break;
3202 }
3203
3204 // Assume file exists, try again with another name.
3205 if (next_char == 'a' - 1)
3206 {
3207 // They all exist? Must be something wrong! Don't write
3208 // the viminfo file then.
Bram Moolenaard82a47d2022-01-05 20:24:39 +00003209 semsg(_(e_too_many_viminfo_temp_files_like_str), tempname);
Bram Moolenaardefa0672019-07-21 19:25:37 +02003210 break;
3211 }
3212 *wp = next_char;
3213 --next_char;
3214 }
3215
3216 if (tempname != NULL)
3217 break;
3218 // continue if shortname was set
3219 }
3220
3221#if defined(UNIX) && defined(HAVE_FCHOWN)
3222 if (tempname != NULL && fp_out != NULL)
3223 {
3224 stat_T tmp_st;
3225
Bram Moolenaar6bd1d772019-10-09 22:01:25 +02003226 // Make sure the original owner can read/write the tempfile and
3227 // otherwise preserve permissions, making sure the group matches.
Bram Moolenaardefa0672019-07-21 19:25:37 +02003228 if (mch_stat((char *)tempname, &tmp_st) >= 0)
3229 {
3230 if (st_old.st_uid != tmp_st.st_uid)
3231 // Changing the owner might fail, in which case the
Bram Moolenaar32aa1022019-11-02 22:54:41 +01003232 // file will now be owned by the current user, oh well.
Bram Moolenaardefa0672019-07-21 19:25:37 +02003233 vim_ignored = fchown(fileno(fp_out), st_old.st_uid, -1);
3234 if (st_old.st_gid != tmp_st.st_gid
3235 && fchown(fileno(fp_out), -1, st_old.st_gid) == -1)
3236 // can't set the group to what it should be, remove
3237 // group permissions
3238 (void)mch_setperm(tempname, 0600);
3239 }
3240 else
3241 // can't stat the file, set conservative permissions
3242 (void)mch_setperm(tempname, 0600);
3243 }
3244#endif
3245 }
3246
Bram Moolenaar6bd1d772019-10-09 22:01:25 +02003247 // Check if the new viminfo file can be written to.
Bram Moolenaardefa0672019-07-21 19:25:37 +02003248 if (fp_out == NULL)
3249 {
Bram Moolenaarc553a212021-12-26 20:20:34 +00003250 semsg(_(e_cant_write_viminfo_file_str),
Bram Moolenaardefa0672019-07-21 19:25:37 +02003251 (fp_in == NULL || tempname == NULL) ? fname : tempname);
3252 if (fp_in != NULL)
3253 fclose(fp_in);
3254 goto end;
3255 }
3256
3257 if (p_verbose > 0)
3258 {
3259 verbose_enter();
3260 smsg(_("Writing viminfo file \"%s\""), fname);
3261 verbose_leave();
3262 }
3263
3264 viminfo_errcnt = 0;
3265 do_viminfo(fp_in, fp_out, forceit ? 0 : (VIF_WANT_INFO | VIF_WANT_MARKS));
3266
3267 if (fclose(fp_out) == EOF)
3268 ++viminfo_errcnt;
3269
3270 if (fp_in != NULL)
3271 {
3272 fclose(fp_in);
3273
3274 // In case of an error keep the original viminfo file. Otherwise
3275 // rename the newly written file. Give an error if that fails.
3276 if (viminfo_errcnt == 0)
3277 {
3278 if (vim_rename(tempname, fname) == -1)
3279 {
3280 ++viminfo_errcnt;
Bram Moolenaard82a47d2022-01-05 20:24:39 +00003281 semsg(_(e_cant_rename_viminfo_file_to_str), fname);
Bram Moolenaardefa0672019-07-21 19:25:37 +02003282 }
3283# ifdef MSWIN
3284 // If the viminfo file was hidden then also hide the new file.
3285 else if (hidden)
3286 mch_hide(fname);
3287# endif
3288 }
3289 if (viminfo_errcnt > 0)
3290 mch_remove(tempname);
3291 }
3292
3293end:
3294 vim_free(fname);
3295 vim_free(tempname);
3296}
3297
3298/*
Bram Moolenaardefa0672019-07-21 19:25:37 +02003299 * ":rviminfo" and ":wviminfo".
3300 */
3301 void
3302ex_viminfo(
3303 exarg_T *eap)
3304{
3305 char_u *save_viminfo;
3306
3307 save_viminfo = p_viminfo;
3308 if (*p_viminfo == NUL)
3309 p_viminfo = (char_u *)"'100";
3310 if (eap->cmdidx == CMD_rviminfo)
3311 {
3312 if (read_viminfo(eap->arg, VIF_WANT_INFO | VIF_WANT_MARKS
3313 | (eap->forceit ? VIF_FORCEIT : 0)) == FAIL)
Bram Moolenaarcbadefe2022-01-01 19:33:50 +00003314 emsg(_(e_cannot_open_viminfo_file_for_reading));
Bram Moolenaardefa0672019-07-21 19:25:37 +02003315 }
3316 else
3317 write_viminfo(eap->arg, eap->forceit);
3318 p_viminfo = save_viminfo;
3319}
3320
Bram Moolenaardefa0672019-07-21 19:25:37 +02003321#endif // FEAT_VIMINFO