1 /* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10 /*
11 * misc1.c: functions that didn't seem to fit elsewhere
12 */
13
14 #include "vim.h"
15 #include "version.h"
16
17 #if defined(__HAIKU__)
18 # include <storage/FindDirectory.h>
19 #endif
20
21 #if defined(MSWIN)
22 # include <lm.h>
23 #endif
24
25 #define URL_SLASH 1 // path_is_url() has found "://"
26 #define URL_BACKSLASH 2 // path_is_url() has found ":\\"
27
28 // All user names (for ~user completion as done by shell).
29 static garray_T ga_users;
30
31 /*
32 * get_leader_len() returns the length in bytes of the prefix of the given
33 * string which introduces a comment. If this string is not a comment then
34 * 0 is returned.
35 * When "flags" is not NULL, it is set to point to the flags of the recognized
36 * comment leader.
37 * "backward" must be true for the "O" command.
38 * If "include_space" is set, include trailing whitespace while calculating the
39 * length.
40 */
41 int
get_leader_len(char_u * line,char_u ** flags,int backward,int include_space)42 get_leader_len(
43 char_u *line,
44 char_u **flags,
45 int backward,
46 int include_space)
47 {
48 int i, j;
49 int result;
50 int got_com = FALSE;
51 int found_one;
52 char_u part_buf[COM_MAX_LEN]; // buffer for one option part
53 char_u *string; // pointer to comment string
54 char_u *list;
55 int middle_match_len = 0;
56 char_u *prev_list;
57 char_u *saved_flags = NULL;
58
59 result = i = 0;
60 while (VIM_ISWHITE(line[i])) // leading white space is ignored
61 ++i;
62
63 /*
64 * Repeat to match several nested comment strings.
65 */
66 while (line[i] != NUL)
67 {
68 /*
69 * scan through the 'comments' option for a match
70 */
71 found_one = FALSE;
72 for (list = curbuf->b_p_com; *list; )
73 {
74 // Get one option part into part_buf[]. Advance "list" to next
75 // one. Put "string" at start of string.
76 if (!got_com && flags != NULL)
77 *flags = list; // remember where flags started
78 prev_list = list;
79 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
80 string = vim_strchr(part_buf, ':');
81 if (string == NULL) // missing ':', ignore this part
82 continue;
83 *string++ = NUL; // isolate flags from string
84
85 // If we found a middle match previously, use that match when this
86 // is not a middle or end.
87 if (middle_match_len != 0
88 && vim_strchr(part_buf, COM_MIDDLE) == NULL
89 && vim_strchr(part_buf, COM_END) == NULL)
90 break;
91
92 // When we already found a nested comment, only accept further
93 // nested comments.
94 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
95 continue;
96
97 // When 'O' flag present and using "O" command skip this one.
98 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
99 continue;
100
101 // Line contents and string must match.
102 // When string starts with white space, must have some white space
103 // (but the amount does not need to match, there might be a mix of
104 // TABs and spaces).
105 if (VIM_ISWHITE(string[0]))
106 {
107 if (i == 0 || !VIM_ISWHITE(line[i - 1]))
108 continue; // missing white space
109 while (VIM_ISWHITE(string[0]))
110 ++string;
111 }
112 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
113 ;
114 if (string[j] != NUL)
115 continue; // string doesn't match
116
117 // When 'b' flag used, there must be white space or an
118 // end-of-line after the string in the line.
119 if (vim_strchr(part_buf, COM_BLANK) != NULL
120 && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
121 continue;
122
123 // We have found a match, stop searching unless this is a middle
124 // comment. The middle comment can be a substring of the end
125 // comment in which case it's better to return the length of the
126 // end comment and its flags. Thus we keep searching with middle
127 // and end matches and use an end match if it matches better.
128 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
129 {
130 if (middle_match_len == 0)
131 {
132 middle_match_len = j;
133 saved_flags = prev_list;
134 }
135 continue;
136 }
137 if (middle_match_len != 0 && j > middle_match_len)
138 // Use this match instead of the middle match, since it's a
139 // longer thus better match.
140 middle_match_len = 0;
141
142 if (middle_match_len == 0)
143 i += j;
144 found_one = TRUE;
145 break;
146 }
147
148 if (middle_match_len != 0)
149 {
150 // Use the previously found middle match after failing to find a
151 // match with an end.
152 if (!got_com && flags != NULL)
153 *flags = saved_flags;
154 i += middle_match_len;
155 found_one = TRUE;
156 }
157
158 // No match found, stop scanning.
159 if (!found_one)
160 break;
161
162 result = i;
163
164 // Include any trailing white space.
165 while (VIM_ISWHITE(line[i]))
166 ++i;
167
168 if (include_space)
169 result = i;
170
171 // If this comment doesn't nest, stop here.
172 got_com = TRUE;
173 if (vim_strchr(part_buf, COM_NEST) == NULL)
174 break;
175 }
176 return result;
177 }
178
179 /*
180 * Return the offset at which the last comment in line starts. If there is no
181 * comment in the whole line, -1 is returned.
182 *
183 * When "flags" is not null, it is set to point to the flags describing the
184 * recognized comment leader.
185 */
186 int
get_last_leader_offset(char_u * line,char_u ** flags)187 get_last_leader_offset(char_u *line, char_u **flags)
188 {
189 int result = -1;
190 int i, j;
191 int lower_check_bound = 0;
192 char_u *string;
193 char_u *com_leader;
194 char_u *com_flags;
195 char_u *list;
196 int found_one;
197 char_u part_buf[COM_MAX_LEN]; // buffer for one option part
198
199 /*
200 * Repeat to match several nested comment strings.
201 */
202 i = (int)STRLEN(line);
203 while (--i >= lower_check_bound)
204 {
205 /*
206 * scan through the 'comments' option for a match
207 */
208 found_one = FALSE;
209 for (list = curbuf->b_p_com; *list; )
210 {
211 char_u *flags_save = list;
212
213 /*
214 * Get one option part into part_buf[]. Advance list to next one.
215 * put string at start of string.
216 */
217 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
218 string = vim_strchr(part_buf, ':');
219 if (string == NULL) // If everything is fine, this cannot actually
220 // happen.
221 continue;
222 *string++ = NUL; // Isolate flags from string.
223 com_leader = string;
224
225 /*
226 * Line contents and string must match.
227 * When string starts with white space, must have some white space
228 * (but the amount does not need to match, there might be a mix of
229 * TABs and spaces).
230 */
231 if (VIM_ISWHITE(string[0]))
232 {
233 if (i == 0 || !VIM_ISWHITE(line[i - 1]))
234 continue;
235 while (VIM_ISWHITE(*string))
236 ++string;
237 }
238 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
239 /* do nothing */;
240 if (string[j] != NUL)
241 continue;
242
243 /*
244 * When 'b' flag used, there must be white space or an
245 * end-of-line after the string in the line.
246 */
247 if (vim_strchr(part_buf, COM_BLANK) != NULL
248 && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
249 continue;
250
251 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
252 {
253 // For a middlepart comment, only consider it to match if
254 // everything before the current position in the line is
255 // whitespace. Otherwise we would think we are inside a
256 // comment if the middle part appears somewhere in the middle
257 // of the line. E.g. for C the "*" appears often.
258 for (j = 0; VIM_ISWHITE(line[j]) && j <= i; j++)
259 ;
260 if (j < i)
261 continue;
262 }
263
264 /*
265 * We have found a match, stop searching.
266 */
267 found_one = TRUE;
268
269 if (flags)
270 *flags = flags_save;
271 com_flags = flags_save;
272
273 break;
274 }
275
276 if (found_one)
277 {
278 char_u part_buf2[COM_MAX_LEN]; // buffer for one option part
279 int len1, len2, off;
280
281 result = i;
282 /*
283 * If this comment nests, continue searching.
284 */
285 if (vim_strchr(part_buf, COM_NEST) != NULL)
286 continue;
287
288 lower_check_bound = i;
289
290 // Let's verify whether the comment leader found is a substring
291 // of other comment leaders. If it is, let's adjust the
292 // lower_check_bound so that we make sure that we have determined
293 // the comment leader correctly.
294
295 while (VIM_ISWHITE(*com_leader))
296 ++com_leader;
297 len1 = (int)STRLEN(com_leader);
298
299 for (list = curbuf->b_p_com; *list; )
300 {
301 char_u *flags_save = list;
302
303 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
304 if (flags_save == com_flags)
305 continue;
306 string = vim_strchr(part_buf2, ':');
307 ++string;
308 while (VIM_ISWHITE(*string))
309 ++string;
310 len2 = (int)STRLEN(string);
311 if (len2 == 0)
312 continue;
313
314 // Now we have to verify whether string ends with a substring
315 // beginning the com_leader.
316 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
317 {
318 --off;
319 if (!STRNCMP(string + off, com_leader, len2 - off))
320 {
321 if (i - off < lower_check_bound)
322 lower_check_bound = i - off;
323 }
324 }
325 }
326 }
327 }
328 return result;
329 }
330
331 /*
332 * Return the number of window lines occupied by buffer line "lnum".
333 */
334 int
plines(linenr_T lnum)335 plines(linenr_T lnum)
336 {
337 return plines_win(curwin, lnum, TRUE);
338 }
339
340 int
plines_win(win_T * wp,linenr_T lnum,int winheight)341 plines_win(
342 win_T *wp,
343 linenr_T lnum,
344 int winheight) // when TRUE limit to window height
345 {
346 #if defined(FEAT_DIFF) || defined(PROTO)
347 // Check for filler lines above this buffer line. When folded the result
348 // is one line anyway.
349 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
350 }
351
352 int
plines_nofill(linenr_T lnum)353 plines_nofill(linenr_T lnum)
354 {
355 return plines_win_nofill(curwin, lnum, TRUE);
356 }
357
358 int
plines_win_nofill(win_T * wp,linenr_T lnum,int winheight)359 plines_win_nofill(
360 win_T *wp,
361 linenr_T lnum,
362 int winheight) // when TRUE limit to window height
363 {
364 #endif
365 int lines;
366
367 if (!wp->w_p_wrap)
368 return 1;
369
370 if (wp->w_width == 0)
371 return 1;
372
373 #ifdef FEAT_FOLDING
374 // A folded lines is handled just like an empty line.
375 // NOTE: Caller must handle lines that are MAYBE folded.
376 if (lineFolded(wp, lnum) == TRUE)
377 return 1;
378 #endif
379
380 lines = plines_win_nofold(wp, lnum);
381 if (winheight > 0 && lines > wp->w_height)
382 return (int)wp->w_height;
383 return lines;
384 }
385
386 /*
387 * Return number of window lines physical line "lnum" will occupy in window
388 * "wp". Does not care about folding, 'wrap' or 'diff'.
389 */
390 int
plines_win_nofold(win_T * wp,linenr_T lnum)391 plines_win_nofold(win_T *wp, linenr_T lnum)
392 {
393 char_u *s;
394 long col;
395 int width;
396
397 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
398 if (*s == NUL) // empty line
399 return 1;
400 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
401
402 /*
403 * If list mode is on, then the '$' at the end of the line may take up one
404 * extra column.
405 */
406 if (wp->w_p_list && wp->w_lcs_chars.eol != NUL)
407 col += 1;
408
409 /*
410 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
411 */
412 width = wp->w_width - win_col_off(wp);
413 if (width <= 0)
414 return 32000;
415 if (col <= width)
416 return 1;
417 col -= width;
418 width += win_col_off2(wp);
419 return (col + (width - 1)) / width + 1;
420 }
421
422 /*
423 * Like plines_win(), but only reports the number of physical screen lines
424 * used from the start of the line to the given column number.
425 */
426 int
plines_win_col(win_T * wp,linenr_T lnum,long column)427 plines_win_col(win_T *wp, linenr_T lnum, long column)
428 {
429 long col;
430 char_u *s;
431 int lines = 0;
432 int width;
433 char_u *line;
434
435 #ifdef FEAT_DIFF
436 // Check for filler lines above this buffer line. When folded the result
437 // is one line anyway.
438 lines = diff_check_fill(wp, lnum);
439 #endif
440
441 if (!wp->w_p_wrap)
442 return lines + 1;
443
444 if (wp->w_width == 0)
445 return lines + 1;
446
447 line = s = ml_get_buf(wp->w_buffer, lnum, FALSE);
448
449 col = 0;
450 while (*s != NUL && --column >= 0)
451 {
452 col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL);
453 MB_PTR_ADV(s);
454 }
455
456 /*
457 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
458 * INSERT mode, then col must be adjusted so that it represents the last
459 * screen position of the TAB. This only fixes an error when the TAB wraps
460 * from one screen line to the next (when 'columns' is not a multiple of
461 * 'ts') -- webb.
462 */
463 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list ||
464 wp->w_lcs_chars.tab1))
465 col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL) - 1;
466
467 /*
468 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
469 */
470 width = wp->w_width - win_col_off(wp);
471 if (width <= 0)
472 return 9999;
473
474 lines += 1;
475 if (col > width)
476 lines += (col - width) / (width + win_col_off2(wp)) + 1;
477 return lines;
478 }
479
480 int
plines_m_win(win_T * wp,linenr_T first,linenr_T last)481 plines_m_win(win_T *wp, linenr_T first, linenr_T last)
482 {
483 int count = 0;
484
485 while (first <= last)
486 {
487 #ifdef FEAT_FOLDING
488 int x;
489
490 // Check if there are any really folded lines, but also included lines
491 // that are maybe folded.
492 x = foldedCount(wp, first, NULL);
493 if (x > 0)
494 {
495 ++count; // count 1 for "+-- folded" line
496 first += x;
497 }
498 else
499 #endif
500 {
501 #ifdef FEAT_DIFF
502 if (first == wp->w_topline)
503 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
504 else
505 #endif
506 count += plines_win(wp, first, TRUE);
507 ++first;
508 }
509 }
510 return (count);
511 }
512
513 int
gchar_pos(pos_T * pos)514 gchar_pos(pos_T *pos)
515 {
516 char_u *ptr;
517
518 // When searching columns is sometimes put at the end of a line.
519 if (pos->col == MAXCOL)
520 return NUL;
521 ptr = ml_get_pos(pos);
522 if (has_mbyte)
523 return (*mb_ptr2char)(ptr);
524 return (int)*ptr;
525 }
526
527 int
gchar_cursor(void)528 gchar_cursor(void)
529 {
530 if (has_mbyte)
531 return (*mb_ptr2char)(ml_get_cursor());
532 return (int)*ml_get_cursor();
533 }
534
535 /*
536 * Write a character at the current cursor position.
537 * It is directly written into the block.
538 */
539 void
pchar_cursor(int c)540 pchar_cursor(int c)
541 {
542 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
543 + curwin->w_cursor.col) = c;
544 }
545
546 /*
547 * Skip to next part of an option argument: Skip space and comma.
548 */
549 char_u *
skip_to_option_part(char_u * p)550 skip_to_option_part(char_u *p)
551 {
552 if (*p == ',')
553 ++p;
554 while (*p == ' ')
555 ++p;
556 return p;
557 }
558
559 /*
560 * check_status: called when the status bars for the buffer 'buf'
561 * need to be updated
562 */
563 void
check_status(buf_T * buf)564 check_status(buf_T *buf)
565 {
566 win_T *wp;
567
568 FOR_ALL_WINDOWS(wp)
569 if (wp->w_buffer == buf && wp->w_status_height)
570 {
571 wp->w_redr_status = TRUE;
572 if (must_redraw < VALID)
573 must_redraw = VALID;
574 }
575 }
576
577 /*
578 * Ask for a reply from the user, a 'y' or a 'n'.
579 * No other characters are accepted, the message is repeated until a valid
580 * reply is entered or CTRL-C is hit.
581 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
582 * from any buffers but directly from the user.
583 *
584 * return the 'y' or 'n'
585 */
586 int
ask_yesno(char_u * str,int direct)587 ask_yesno(char_u *str, int direct)
588 {
589 int r = ' ';
590 int save_State = State;
591
592 if (exiting) // put terminal in raw mode for this question
593 settmode(TMODE_RAW);
594 ++no_wait_return;
595 #ifdef USE_ON_FLY_SCROLL
596 dont_scroll = TRUE; // disallow scrolling here
597 #endif
598 State = CONFIRM; // mouse behaves like with :confirm
599 setmouse(); // disables mouse for xterm
600 ++no_mapping;
601 ++allow_keys; // no mapping here, but recognize keys
602
603 while (r != 'y' && r != 'n')
604 {
605 // same highlighting as for wait_return
606 smsg_attr(HL_ATTR(HLF_R), "%s (y/n)?", str);
607 if (direct)
608 r = get_keystroke();
609 else
610 r = plain_vgetc();
611 if (r == Ctrl_C || r == ESC)
612 r = 'n';
613 msg_putchar(r); // show what you typed
614 out_flush();
615 }
616 --no_wait_return;
617 State = save_State;
618 setmouse();
619 --no_mapping;
620 --allow_keys;
621
622 return r;
623 }
624
625 #if defined(FEAT_EVAL) || defined(PROTO)
626
627 /*
628 * "mode()" function
629 */
630 void
f_mode(typval_T * argvars,typval_T * rettv)631 f_mode(typval_T *argvars, typval_T *rettv)
632 {
633 char_u buf[MODE_MAX_LENGTH];
634
635 if (in_vim9script() && check_for_opt_bool_arg(argvars, 0) == FAIL)
636 return;
637
638 CLEAR_FIELD(buf);
639
640 if (time_for_testing == 93784)
641 {
642 // Testing the two-character code.
643 buf[0] = 'x';
644 buf[1] = '!';
645 }
646 #ifdef FEAT_TERMINAL
647 else if (term_use_loop())
648 buf[0] = 't';
649 #endif
650 else if (VIsual_active)
651 {
652 if (VIsual_select)
653 buf[0] = VIsual_mode + 's' - 'v';
654 else
655 {
656 buf[0] = VIsual_mode;
657 if (restart_VIsual_select)
658 buf[1] = 's';
659 }
660 }
661 else if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
662 || State == CONFIRM)
663 {
664 buf[0] = 'r';
665 if (State == ASKMORE)
666 buf[1] = 'm';
667 else if (State == CONFIRM)
668 buf[1] = '?';
669 }
670 else if (State == EXTERNCMD)
671 buf[0] = '!';
672 else if (State & INSERT)
673 {
674 if (State & VREPLACE_FLAG)
675 {
676 buf[0] = 'R';
677 buf[1] = 'v';
678
679 if (ins_compl_active())
680 buf[2] = 'c';
681 else if (ctrl_x_mode_not_defined_yet())
682 buf[2] = 'x';
683 }
684 else
685 {
686 if (State & REPLACE_FLAG)
687 buf[0] = 'R';
688 else
689 buf[0] = 'i';
690
691 if (ins_compl_active())
692 buf[1] = 'c';
693 else if (ctrl_x_mode_not_defined_yet())
694 buf[1] = 'x';
695 }
696 }
697 else if ((State & CMDLINE) || exmode_active)
698 {
699 buf[0] = 'c';
700 if (exmode_active == EXMODE_VIM)
701 buf[1] = 'v';
702 else if (exmode_active == EXMODE_NORMAL)
703 buf[1] = 'e';
704 }
705 else
706 {
707 buf[0] = 'n';
708 if (finish_op)
709 {
710 buf[1] = 'o';
711 // to be able to detect force-linewise/blockwise/characterwise
712 // operations
713 buf[2] = motion_force;
714 }
715 else if (restart_edit == 'I' || restart_edit == 'R'
716 || restart_edit == 'V')
717 {
718 buf[1] = 'i';
719 buf[2] = restart_edit;
720 }
721 #ifdef FEAT_TERMINAL
722 else if (term_in_normal_mode())
723 buf[1] = 't';
724 #endif
725 }
726
727 // Clear out the minor mode when the argument is not a non-zero number or
728 // non-empty string.
729 if (!non_zero_arg(&argvars[0]))
730 buf[1] = NUL;
731
732 rettv->vval.v_string = vim_strsave(buf);
733 rettv->v_type = VAR_STRING;
734 }
735
736 static void
may_add_state_char(garray_T * gap,char_u * include,int c)737 may_add_state_char(garray_T *gap, char_u *include, int c)
738 {
739 if (include == NULL || vim_strchr(include, c) != NULL)
740 ga_append(gap, c);
741 }
742
743 /*
744 * "state()" function
745 */
746 void
f_state(typval_T * argvars,typval_T * rettv)747 f_state(typval_T *argvars, typval_T *rettv)
748 {
749 garray_T ga;
750 char_u *include = NULL;
751 int i;
752
753 if (in_vim9script() && check_for_opt_string_arg(argvars, 0) == FAIL)
754 return;
755
756 ga_init2(&ga, 1, 20);
757 if (argvars[0].v_type != VAR_UNKNOWN)
758 include = tv_get_string(&argvars[0]);
759
760 if (!(stuff_empty() && typebuf.tb_len == 0 && scriptin[curscript] == NULL))
761 may_add_state_char(&ga, include, 'm');
762 if (op_pending())
763 may_add_state_char(&ga, include, 'o');
764 if (autocmd_busy)
765 may_add_state_char(&ga, include, 'x');
766 if (ins_compl_active())
767 may_add_state_char(&ga, include, 'a');
768
769 # ifdef FEAT_JOB_CHANNEL
770 if (channel_in_blocking_wait())
771 may_add_state_char(&ga, include, 'w');
772 # endif
773 if (!get_was_safe_state())
774 may_add_state_char(&ga, include, 'S');
775 for (i = 0; i < get_callback_depth() && i < 3; ++i)
776 may_add_state_char(&ga, include, 'c');
777 if (msg_scrolled > 0)
778 may_add_state_char(&ga, include, 's');
779
780 rettv->v_type = VAR_STRING;
781 rettv->vval.v_string = ga.ga_data;
782 }
783
784 #endif // FEAT_EVAL
785
786 /*
787 * Get a key stroke directly from the user.
788 * Ignores mouse clicks and scrollbar events, except a click for the left
789 * button (used at the more prompt).
790 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
791 * Disadvantage: typeahead is ignored.
792 * Translates the interrupt character for unix to ESC.
793 */
794 int
get_keystroke(void)795 get_keystroke(void)
796 {
797 char_u *buf = NULL;
798 int buflen = 150;
799 int maxlen;
800 int len = 0;
801 int n;
802 int save_mapped_ctrl_c = mapped_ctrl_c;
803 int waited = 0;
804
805 mapped_ctrl_c = FALSE; // mappings are not used here
806 for (;;)
807 {
808 cursor_on();
809 out_flush();
810
811 // Leave some room for check_termcode() to insert a key code into (max
812 // 5 chars plus NUL). And fix_input_buffer() can triple the number of
813 // bytes.
814 maxlen = (buflen - 6 - len) / 3;
815 if (buf == NULL)
816 buf = alloc(buflen);
817 else if (maxlen < 10)
818 {
819 char_u *t_buf = buf;
820
821 // Need some more space. This might happen when receiving a long
822 // escape sequence.
823 buflen += 100;
824 buf = vim_realloc(buf, buflen);
825 if (buf == NULL)
826 vim_free(t_buf);
827 maxlen = (buflen - 6 - len) / 3;
828 }
829 if (buf == NULL)
830 {
831 do_outofmem_msg((long_u)buflen);
832 return ESC; // panic!
833 }
834
835 // First time: blocking wait. Second time: wait up to 100ms for a
836 // terminal code to complete.
837 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
838 if (n > 0)
839 {
840 // Replace zero and CSI by a special key code.
841 n = fix_input_buffer(buf + len, n);
842 len += n;
843 waited = 0;
844 }
845 else if (len > 0)
846 ++waited; // keep track of the waiting time
847
848 // Incomplete termcode and not timed out yet: get more characters
849 if ((n = check_termcode(1, buf, buflen, &len)) < 0
850 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
851 continue;
852
853 if (n == KEYLEN_REMOVED) // key code removed
854 {
855 if (must_redraw != 0 && !need_wait_return
856 && (State & (CMDLINE|HITRETURN|ASKMORE)) == 0)
857 {
858 // Redrawing was postponed, do it now.
859 update_screen(0);
860 setcursor(); // put cursor back where it belongs
861 }
862 continue;
863 }
864 if (n > 0) // found a termcode: adjust length
865 len = n;
866 if (len == 0) // nothing typed yet
867 continue;
868
869 // Handle modifier and/or special key code.
870 n = buf[0];
871 if (n == K_SPECIAL)
872 {
873 n = TO_SPECIAL(buf[1], buf[2]);
874 if (buf[1] == KS_MODIFIER
875 || n == K_IGNORE
876 || (is_mouse_key(n) && n != K_LEFTMOUSE)
877 #ifdef FEAT_GUI
878 || n == K_VER_SCROLLBAR
879 || n == K_HOR_SCROLLBAR
880 #endif
881 )
882 {
883 if (buf[1] == KS_MODIFIER)
884 mod_mask = buf[2];
885 len -= 3;
886 if (len > 0)
887 mch_memmove(buf, buf + 3, (size_t)len);
888 continue;
889 }
890 break;
891 }
892 if (has_mbyte)
893 {
894 if (MB_BYTE2LEN(n) > len)
895 continue; // more bytes to get
896 buf[len >= buflen ? buflen - 1 : len] = NUL;
897 n = (*mb_ptr2char)(buf);
898 }
899 #ifdef UNIX
900 if (n == intr_char)
901 n = ESC;
902 #endif
903 break;
904 }
905 vim_free(buf);
906
907 mapped_ctrl_c = save_mapped_ctrl_c;
908 return n;
909 }
910
911 /*
912 * Get a number from the user.
913 * When "mouse_used" is not NULL allow using the mouse.
914 */
915 int
get_number(int colon,int * mouse_used)916 get_number(
917 int colon, // allow colon to abort
918 int *mouse_used)
919 {
920 int n = 0;
921 int c;
922 int typed = 0;
923
924 if (mouse_used != NULL)
925 *mouse_used = FALSE;
926
927 // When not printing messages, the user won't know what to type, return a
928 // zero (as if CR was hit).
929 if (msg_silent != 0)
930 return 0;
931
932 #ifdef USE_ON_FLY_SCROLL
933 dont_scroll = TRUE; // disallow scrolling here
934 #endif
935 ++no_mapping;
936 ++allow_keys; // no mapping here, but recognize keys
937 for (;;)
938 {
939 windgoto(msg_row, msg_col);
940 c = safe_vgetc();
941 if (VIM_ISDIGIT(c))
942 {
943 n = n * 10 + c - '0';
944 msg_putchar(c);
945 ++typed;
946 }
947 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
948 {
949 if (typed > 0)
950 {
951 msg_puts("\b \b");
952 --typed;
953 }
954 n /= 10;
955 }
956 else if (mouse_used != NULL && c == K_LEFTMOUSE)
957 {
958 *mouse_used = TRUE;
959 n = mouse_row + 1;
960 break;
961 }
962 else if (n == 0 && c == ':' && colon)
963 {
964 stuffcharReadbuff(':');
965 if (!exmode_active)
966 cmdline_row = msg_row;
967 skip_redraw = TRUE; // skip redraw once
968 do_redraw = FALSE;
969 break;
970 }
971 else if (c == Ctrl_C || c == ESC || c == 'q')
972 {
973 n = 0;
974 break;
975 }
976 else if (c == CAR || c == NL )
977 break;
978 }
979 --no_mapping;
980 --allow_keys;
981 return n;
982 }
983
984 /*
985 * Ask the user to enter a number.
986 * When "mouse_used" is not NULL allow using the mouse and in that case return
987 * the line number.
988 */
989 int
prompt_for_number(int * mouse_used)990 prompt_for_number(int *mouse_used)
991 {
992 int i;
993 int save_cmdline_row;
994 int save_State;
995
996 // When using ":silent" assume that <CR> was entered.
997 if (mouse_used != NULL)
998 msg_puts(_("Type number and <Enter> or click with the mouse (q or empty cancels): "));
999 else
1000 msg_puts(_("Type number and <Enter> (q or empty cancels): "));
1001
1002 // Set the state such that text can be selected/copied/pasted and we still
1003 // get mouse events. redraw_after_callback() will not redraw if cmdline_row
1004 // is zero.
1005 save_cmdline_row = cmdline_row;
1006 cmdline_row = 0;
1007 save_State = State;
1008 State = CMDLINE;
1009 // May show different mouse shape.
1010 setmouse();
1011
1012 i = get_number(TRUE, mouse_used);
1013 if (KeyTyped)
1014 {
1015 // don't call wait_return() now
1016 if (msg_row > 0)
1017 cmdline_row = msg_row - 1;
1018 need_wait_return = FALSE;
1019 msg_didany = FALSE;
1020 msg_didout = FALSE;
1021 }
1022 else
1023 cmdline_row = save_cmdline_row;
1024 State = save_State;
1025 // May need to restore mouse shape.
1026 setmouse();
1027
1028 return i;
1029 }
1030
1031 void
msgmore(long n)1032 msgmore(long n)
1033 {
1034 long pn;
1035
1036 if (global_busy // no messages now, wait until global is finished
1037 || !messaging()) // 'lazyredraw' set, don't do messages now
1038 return;
1039
1040 // We don't want to overwrite another important message, but do overwrite
1041 // a previous "more lines" or "fewer lines" message, so that "5dd" and
1042 // then "put" reports the last action.
1043 if (keep_msg != NULL && !keep_msg_more)
1044 return;
1045
1046 if (n > 0)
1047 pn = n;
1048 else
1049 pn = -n;
1050
1051 if (pn > p_report)
1052 {
1053 if (n > 0)
1054 vim_snprintf(msg_buf, MSG_BUF_LEN,
1055 NGETTEXT("%ld more line", "%ld more lines", pn), pn);
1056 else
1057 vim_snprintf(msg_buf, MSG_BUF_LEN,
1058 NGETTEXT("%ld line less", "%ld fewer lines", pn), pn);
1059 if (got_int)
1060 vim_strcat((char_u *)msg_buf, (char_u *)_(" (Interrupted)"),
1061 MSG_BUF_LEN);
1062 if (msg(msg_buf))
1063 {
1064 set_keep_msg((char_u *)msg_buf, 0);
1065 keep_msg_more = TRUE;
1066 }
1067 }
1068 }
1069
1070 /*
1071 * flush map and typeahead buffers and give a warning for an error
1072 */
1073 void
beep_flush(void)1074 beep_flush(void)
1075 {
1076 if (emsg_silent == 0)
1077 {
1078 flush_buffers(FLUSH_MINIMAL);
1079 vim_beep(BO_ERROR);
1080 }
1081 }
1082
1083 /*
1084 * Give a warning for an error.
1085 */
1086 void
vim_beep(unsigned val)1087 vim_beep(
1088 unsigned val) // one of the BO_ values, e.g., BO_OPER
1089 {
1090 #ifdef FEAT_EVAL
1091 called_vim_beep = TRUE;
1092 #endif
1093
1094 if (emsg_silent == 0 && !in_assert_fails)
1095 {
1096 if (!((bo_flags & val) || (bo_flags & BO_ALL)))
1097 {
1098 #ifdef ELAPSED_FUNC
1099 static int did_init = FALSE;
1100 static elapsed_T start_tv;
1101
1102 // Only beep once per half a second, otherwise a sequence of beeps
1103 // would freeze Vim.
1104 if (!did_init || ELAPSED_FUNC(start_tv) > 500)
1105 {
1106 did_init = TRUE;
1107 ELAPSED_INIT(start_tv);
1108 #endif
1109 if (p_vb
1110 #ifdef FEAT_GUI
1111 // While the GUI is starting up the termcap is set for
1112 // the GUI but the output still goes to a terminal.
1113 && !(gui.in_use && gui.starting)
1114 #endif
1115 )
1116 {
1117 out_str_cf(T_VB);
1118 #ifdef FEAT_VTP
1119 // No restore color information, refresh the screen.
1120 if (has_vtp_working() != 0
1121 # ifdef FEAT_TERMGUICOLORS
1122 && (p_tgc || (!p_tgc && t_colors >= 256))
1123 # endif
1124 )
1125 {
1126 redraw_later(CLEAR);
1127 update_screen(0);
1128 redrawcmd();
1129 }
1130 #endif
1131 }
1132 else
1133 out_char(BELL);
1134 #ifdef ELAPSED_FUNC
1135 }
1136 #endif
1137 }
1138
1139 // When 'debug' contains "beep" produce a message. If we are sourcing
1140 // a script or executing a function give the user a hint where the beep
1141 // comes from.
1142 if (vim_strchr(p_debug, 'e') != NULL)
1143 {
1144 msg_source(HL_ATTR(HLF_W));
1145 msg_attr(_("Beep!"), HL_ATTR(HLF_W));
1146 }
1147 }
1148 }
1149
1150 /*
1151 * To get the "real" home directory:
1152 * - get value of $HOME
1153 * For Unix:
1154 * - go to that directory
1155 * - do mch_dirname() to get the real name of that directory.
1156 * This also works with mounts and links.
1157 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
1158 * For Windows:
1159 * This code is duplicated in init_homedir() in dosinst.c. Keep in sync!
1160 */
1161 void
init_homedir(void)1162 init_homedir(void)
1163 {
1164 char_u *var;
1165
1166 // In case we are called a second time (when 'encoding' changes).
1167 VIM_CLEAR(homedir);
1168
1169 #ifdef VMS
1170 var = mch_getenv((char_u *)"SYS$LOGIN");
1171 #else
1172 var = mch_getenv((char_u *)"HOME");
1173 #endif
1174
1175 #ifdef MSWIN
1176 /*
1177 * Typically, $HOME is not defined on Windows, unless the user has
1178 * specifically defined it for Vim's sake. However, on Windows NT
1179 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
1180 * each user. Try constructing $HOME from these.
1181 */
1182 if (var == NULL || *var == NUL)
1183 {
1184 char_u *homedrive, *homepath;
1185
1186 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
1187 homepath = mch_getenv((char_u *)"HOMEPATH");
1188 if (homepath == NULL || *homepath == NUL)
1189 homepath = (char_u *)"\\";
1190 if (homedrive != NULL
1191 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
1192 {
1193 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
1194 if (NameBuff[0] != NUL)
1195 var = NameBuff;
1196 }
1197 }
1198
1199 if (var == NULL)
1200 var = mch_getenv((char_u *)"USERPROFILE");
1201
1202 /*
1203 * Weird but true: $HOME may contain an indirect reference to another
1204 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
1205 * when $HOME is being set.
1206 */
1207 if (var != NULL && *var == '%')
1208 {
1209 char_u *p;
1210 char_u *exp;
1211
1212 p = vim_strchr(var + 1, '%');
1213 if (p != NULL)
1214 {
1215 vim_strncpy(NameBuff, var + 1, p - (var + 1));
1216 exp = mch_getenv(NameBuff);
1217 if (exp != NULL && *exp != NUL
1218 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
1219 {
1220 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
1221 var = NameBuff;
1222 }
1223 }
1224 }
1225
1226 if (var != NULL && *var == NUL) // empty is same as not set
1227 var = NULL;
1228
1229 if (enc_utf8 && var != NULL)
1230 {
1231 int len;
1232 char_u *pp = NULL;
1233
1234 // Convert from active codepage to UTF-8. Other conversions are
1235 // not done, because they would fail for non-ASCII characters.
1236 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
1237 if (pp != NULL)
1238 {
1239 homedir = pp;
1240 return;
1241 }
1242 }
1243
1244 /*
1245 * Default home dir is C:/
1246 * Best assumption we can make in such a situation.
1247 */
1248 if (var == NULL)
1249 var = (char_u *)"C:/";
1250 #endif
1251
1252 if (var != NULL)
1253 {
1254 #ifdef UNIX
1255 /*
1256 * Change to the directory and get the actual path. This resolves
1257 * links. Don't do it when we can't return.
1258 */
1259 if (mch_dirname(NameBuff, MAXPATHL) == OK
1260 && mch_chdir((char *)NameBuff) == 0)
1261 {
1262 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
1263 var = IObuff;
1264 if (mch_chdir((char *)NameBuff) != 0)
1265 emsg(_(e_prev_dir));
1266 }
1267 #endif
1268 homedir = vim_strsave(var);
1269 }
1270 }
1271
1272 #if defined(EXITFREE) || defined(PROTO)
1273 void
free_homedir(void)1274 free_homedir(void)
1275 {
1276 vim_free(homedir);
1277 }
1278
1279 void
free_users(void)1280 free_users(void)
1281 {
1282 ga_clear_strings(&ga_users);
1283 }
1284 #endif
1285
1286 /*
1287 * Call expand_env() and store the result in an allocated string.
1288 * This is not very memory efficient, this expects the result to be freed
1289 * again soon.
1290 */
1291 char_u *
expand_env_save(char_u * src)1292 expand_env_save(char_u *src)
1293 {
1294 return expand_env_save_opt(src, FALSE);
1295 }
1296
1297 /*
1298 * Idem, but when "one" is TRUE handle the string as one file name, only
1299 * expand "~" at the start.
1300 */
1301 char_u *
expand_env_save_opt(char_u * src,int one)1302 expand_env_save_opt(char_u *src, int one)
1303 {
1304 char_u *p;
1305
1306 p = alloc(MAXPATHL);
1307 if (p != NULL)
1308 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
1309 return p;
1310 }
1311
1312 /*
1313 * Expand environment variable with path name.
1314 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
1315 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
1316 * If anything fails no expansion is done and dst equals src.
1317 */
1318 void
expand_env(char_u * src,char_u * dst,int dstlen)1319 expand_env(
1320 char_u *src, // input string e.g. "$HOME/vim.hlp"
1321 char_u *dst, // where to put the result
1322 int dstlen) // maximum length of the result
1323 {
1324 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
1325 }
1326
1327 void
expand_env_esc(char_u * srcp,char_u * dst,int dstlen,int esc,int one,char_u * startstr)1328 expand_env_esc(
1329 char_u *srcp, // input string e.g. "$HOME/vim.hlp"
1330 char_u *dst, // where to put the result
1331 int dstlen, // maximum length of the result
1332 int esc, // escape spaces in expanded variables
1333 int one, // "srcp" is one file name
1334 char_u *startstr) // start again after this (can be NULL)
1335 {
1336 char_u *src;
1337 char_u *tail;
1338 int c;
1339 char_u *var;
1340 int copy_char;
1341 int mustfree; // var was allocated, need to free it later
1342 int at_start = TRUE; // at start of a name
1343 int startstr_len = 0;
1344
1345 if (startstr != NULL)
1346 startstr_len = (int)STRLEN(startstr);
1347
1348 src = skipwhite(srcp);
1349 --dstlen; // leave one char space for "\,"
1350 while (*src && dstlen > 0)
1351 {
1352 #ifdef FEAT_EVAL
1353 // Skip over `=expr`.
1354 if (src[0] == '`' && src[1] == '=')
1355 {
1356 size_t len;
1357
1358 var = src;
1359 src += 2;
1360 (void)skip_expr(&src, NULL);
1361 if (*src == '`')
1362 ++src;
1363 len = src - var;
1364 if (len > (size_t)dstlen)
1365 len = dstlen;
1366 vim_strncpy(dst, var, len);
1367 dst += len;
1368 dstlen -= (int)len;
1369 continue;
1370 }
1371 #endif
1372 copy_char = TRUE;
1373 if ((*src == '$'
1374 #ifdef VMS
1375 && at_start
1376 #endif
1377 )
1378 #if defined(MSWIN)
1379 || *src == '%'
1380 #endif
1381 || (*src == '~' && at_start))
1382 {
1383 mustfree = FALSE;
1384
1385 /*
1386 * The variable name is copied into dst temporarily, because it may
1387 * be a string in read-only memory and a NUL needs to be appended.
1388 */
1389 if (*src != '~') // environment var
1390 {
1391 tail = src + 1;
1392 var = dst;
1393 c = dstlen - 1;
1394
1395 #ifdef UNIX
1396 // Unix has ${var-name} type environment vars
1397 if (*tail == '{' && !vim_isIDc('{'))
1398 {
1399 tail++; // ignore '{'
1400 while (c-- > 0 && *tail && *tail != '}')
1401 *var++ = *tail++;
1402 }
1403 else
1404 #endif
1405 {
1406 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
1407 #if defined(MSWIN)
1408 || (*src == '%' && *tail != '%')
1409 #endif
1410 ))
1411 *var++ = *tail++;
1412 }
1413
1414 #if defined(MSWIN) || defined(UNIX)
1415 # ifdef UNIX
1416 if (src[1] == '{' && *tail != '}')
1417 # else
1418 if (*src == '%' && *tail != '%')
1419 # endif
1420 var = NULL;
1421 else
1422 {
1423 # ifdef UNIX
1424 if (src[1] == '{')
1425 # else
1426 if (*src == '%')
1427 #endif
1428 ++tail;
1429 #endif
1430 *var = NUL;
1431 var = vim_getenv(dst, &mustfree);
1432 #if defined(MSWIN) || defined(UNIX)
1433 }
1434 #endif
1435 }
1436 // home directory
1437 else if ( src[1] == NUL
1438 || vim_ispathsep(src[1])
1439 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
1440 {
1441 var = homedir;
1442 tail = src + 1;
1443 }
1444 else // user directory
1445 {
1446 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
1447 /*
1448 * Copy ~user to dst[], so we can put a NUL after it.
1449 */
1450 tail = src;
1451 var = dst;
1452 c = dstlen - 1;
1453 while ( c-- > 0
1454 && *tail
1455 && vim_isfilec(*tail)
1456 && !vim_ispathsep(*tail))
1457 *var++ = *tail++;
1458 *var = NUL;
1459 # ifdef UNIX
1460 /*
1461 * If the system supports getpwnam(), use it.
1462 * Otherwise, or if getpwnam() fails, the shell is used to
1463 * expand ~user. This is slower and may fail if the shell
1464 * does not support ~user (old versions of /bin/sh).
1465 */
1466 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
1467 {
1468 // Note: memory allocated by getpwnam() is never freed.
1469 // Calling endpwent() apparently doesn't help.
1470 struct passwd *pw = (*dst == NUL)
1471 ? NULL : getpwnam((char *)dst + 1);
1472
1473 var = (pw == NULL) ? NULL : (char_u *)pw->pw_dir;
1474 }
1475 if (var == NULL)
1476 # endif
1477 {
1478 expand_T xpc;
1479
1480 ExpandInit(&xpc);
1481 xpc.xp_context = EXPAND_FILES;
1482 var = ExpandOne(&xpc, dst, NULL,
1483 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
1484 mustfree = TRUE;
1485 }
1486
1487 # else // !UNIX, thus VMS
1488 /*
1489 * USER_HOME is a comma-separated list of
1490 * directories to search for the user account in.
1491 */
1492 {
1493 char_u test[MAXPATHL], paths[MAXPATHL];
1494 char_u *path, *next_path, *ptr;
1495 stat_T st;
1496
1497 STRCPY(paths, USER_HOME);
1498 next_path = paths;
1499 while (*next_path)
1500 {
1501 for (path = next_path; *next_path && *next_path != ',';
1502 next_path++);
1503 if (*next_path)
1504 *next_path++ = NUL;
1505 STRCPY(test, path);
1506 STRCAT(test, "/");
1507 STRCAT(test, dst + 1);
1508 if (mch_stat(test, &st) == 0)
1509 {
1510 var = alloc(STRLEN(test) + 1);
1511 STRCPY(var, test);
1512 mustfree = TRUE;
1513 break;
1514 }
1515 }
1516 }
1517 # endif // UNIX
1518 #else
1519 // cannot expand user's home directory, so don't try
1520 var = NULL;
1521 tail = (char_u *)""; // for gcc
1522 #endif // UNIX || VMS
1523 }
1524
1525 #ifdef BACKSLASH_IN_FILENAME
1526 // If 'shellslash' is set change backslashes to forward slashes.
1527 // Can't use slash_adjust(), p_ssl may be set temporarily.
1528 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
1529 {
1530 char_u *p = vim_strsave(var);
1531
1532 if (p != NULL)
1533 {
1534 if (mustfree)
1535 vim_free(var);
1536 var = p;
1537 mustfree = TRUE;
1538 forward_slash(var);
1539 }
1540 }
1541 #endif
1542
1543 // If "var" contains white space, escape it with a backslash.
1544 // Required for ":e ~/tt" when $HOME includes a space.
1545 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
1546 {
1547 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
1548
1549 if (p != NULL)
1550 {
1551 if (mustfree)
1552 vim_free(var);
1553 var = p;
1554 mustfree = TRUE;
1555 }
1556 }
1557
1558 if (var != NULL && *var != NUL
1559 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
1560 {
1561 STRCPY(dst, var);
1562 dstlen -= (int)STRLEN(var);
1563 c = (int)STRLEN(var);
1564 // if var[] ends in a path separator and tail[] starts
1565 // with it, skip a character
1566 if (*var != NUL && after_pathsep(dst, dst + c)
1567 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
1568 && dst[-1] != ':'
1569 #endif
1570 && vim_ispathsep(*tail))
1571 ++tail;
1572 dst += c;
1573 src = tail;
1574 copy_char = FALSE;
1575 }
1576 if (mustfree)
1577 vim_free(var);
1578 }
1579
1580 if (copy_char) // copy at least one char
1581 {
1582 /*
1583 * Recognize the start of a new name, for '~'.
1584 * Don't do this when "one" is TRUE, to avoid expanding "~" in
1585 * ":edit foo ~ foo".
1586 */
1587 at_start = FALSE;
1588 if (src[0] == '\\' && src[1] != NUL)
1589 {
1590 *dst++ = *src++;
1591 --dstlen;
1592 }
1593 else if ((src[0] == ' ' || src[0] == ',') && !one)
1594 at_start = TRUE;
1595 if (dstlen > 0)
1596 {
1597 *dst++ = *src++;
1598 --dstlen;
1599
1600 if (startstr != NULL && src - startstr_len >= srcp
1601 && STRNCMP(src - startstr_len, startstr,
1602 startstr_len) == 0)
1603 at_start = TRUE;
1604 }
1605 }
1606
1607 }
1608 *dst = NUL;
1609 }
1610
1611 /*
1612 * If the string between "p" and "pend" ends in "name/", return "pend" minus
1613 * the length of "name/". Otherwise return "pend".
1614 */
1615 static char_u *
remove_tail(char_u * p,char_u * pend,char_u * name)1616 remove_tail(char_u *p, char_u *pend, char_u *name)
1617 {
1618 int len = (int)STRLEN(name) + 1;
1619 char_u *newend = pend - len;
1620
1621 if (newend >= p
1622 && fnamencmp(newend, name, len - 1) == 0
1623 && (newend == p || after_pathsep(p, newend)))
1624 return newend;
1625 return pend;
1626 }
1627
1628 /*
1629 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
1630 * Return NULL if not, return its name in allocated memory otherwise.
1631 */
1632 static char_u *
vim_version_dir(char_u * vimdir)1633 vim_version_dir(char_u *vimdir)
1634 {
1635 char_u *p;
1636
1637 if (vimdir == NULL || *vimdir == NUL)
1638 return NULL;
1639 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
1640 if (p != NULL && mch_isdir(p))
1641 return p;
1642 vim_free(p);
1643 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
1644 if (p != NULL && mch_isdir(p))
1645 return p;
1646 vim_free(p);
1647 return NULL;
1648 }
1649
1650 /*
1651 * Vim's version of getenv().
1652 * Special handling of $HOME, $VIM and $VIMRUNTIME.
1653 * Also does ACP to 'enc' conversion for Win32.
1654 * "mustfree" is set to TRUE when returned is allocated, it must be
1655 * initialized to FALSE by the caller.
1656 */
1657 char_u *
vim_getenv(char_u * name,int * mustfree)1658 vim_getenv(char_u *name, int *mustfree)
1659 {
1660 char_u *p = NULL;
1661 char_u *pend;
1662 int vimruntime;
1663 #ifdef MSWIN
1664 WCHAR *wn, *wp;
1665
1666 // use "C:/" when $HOME is not set
1667 if (STRCMP(name, "HOME") == 0)
1668 return homedir;
1669
1670 // Use Wide function
1671 wn = enc_to_utf16(name, NULL);
1672 if (wn == NULL)
1673 return NULL;
1674
1675 wp = _wgetenv(wn);
1676 vim_free(wn);
1677
1678 if (wp != NULL && *wp == NUL) // empty is the same as not set
1679 wp = NULL;
1680
1681 if (wp != NULL)
1682 {
1683 p = utf16_to_enc(wp, NULL);
1684 if (p == NULL)
1685 return NULL;
1686
1687 *mustfree = TRUE;
1688 return p;
1689 }
1690 #else
1691 p = mch_getenv(name);
1692 if (p != NULL && *p == NUL) // empty is the same as not set
1693 p = NULL;
1694
1695 if (p != NULL)
1696 return p;
1697
1698 # ifdef __HAIKU__
1699 // special handling for user settings directory...
1700 if (STRCMP(name, "BE_USER_SETTINGS") == 0)
1701 {
1702 static char userSettingsPath[MAXPATHL];
1703
1704 if (find_directory(B_USER_SETTINGS_DIRECTORY, 0, false,
1705 userSettingsPath, MAXPATHL) == B_OK)
1706 return (char_u *)userSettingsPath;
1707 else
1708 return NULL;
1709 }
1710 # endif
1711 #endif
1712
1713 // handling $VIMRUNTIME and $VIM is below, bail out if it's another name.
1714 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
1715 if (!vimruntime && STRCMP(name, "VIM") != 0)
1716 return NULL;
1717
1718 /*
1719 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
1720 * Don't do this when default_vimruntime_dir is non-empty.
1721 */
1722 if (vimruntime
1723 #ifdef HAVE_PATHDEF
1724 && *default_vimruntime_dir == NUL
1725 #endif
1726 )
1727 {
1728 #ifdef MSWIN
1729 // Use Wide function
1730 wp = _wgetenv(L"VIM");
1731 if (wp != NULL && *wp == NUL) // empty is the same as not set
1732 wp = NULL;
1733 if (wp != NULL)
1734 {
1735 char_u *q = utf16_to_enc(wp, NULL);
1736 if (q != NULL)
1737 {
1738 p = vim_version_dir(q);
1739 *mustfree = TRUE;
1740 if (p == NULL)
1741 p = q;
1742 }
1743 }
1744 #else
1745 p = mch_getenv((char_u *)"VIM");
1746 if (p != NULL && *p == NUL) // empty is the same as not set
1747 p = NULL;
1748 if (p != NULL)
1749 {
1750 p = vim_version_dir(p);
1751 if (p != NULL)
1752 *mustfree = TRUE;
1753 else
1754 p = mch_getenv((char_u *)"VIM");
1755 }
1756 #endif
1757 }
1758
1759 /*
1760 * When expanding $VIM or $VIMRUNTIME fails, try using:
1761 * - the directory name from 'helpfile' (unless it contains '$')
1762 * - the executable name from argv[0]
1763 */
1764 if (p == NULL)
1765 {
1766 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
1767 p = p_hf;
1768 #ifdef USE_EXE_NAME
1769 /*
1770 * Use the name of the executable, obtained from argv[0].
1771 */
1772 else
1773 p = exe_name;
1774 #endif
1775 if (p != NULL)
1776 {
1777 // remove the file name
1778 pend = gettail(p);
1779
1780 // remove "doc/" from 'helpfile', if present
1781 if (p == p_hf)
1782 pend = remove_tail(p, pend, (char_u *)"doc");
1783
1784 #ifdef USE_EXE_NAME
1785 # ifdef MACOS_X
1786 // remove "MacOS" from exe_name and add "Resources/vim"
1787 if (p == exe_name)
1788 {
1789 char_u *pend1;
1790 char_u *pnew;
1791
1792 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
1793 if (pend1 != pend)
1794 {
1795 pnew = alloc(pend1 - p + 15);
1796 if (pnew != NULL)
1797 {
1798 STRNCPY(pnew, p, (pend1 - p));
1799 STRCPY(pnew + (pend1 - p), "Resources/vim");
1800 p = pnew;
1801 pend = p + STRLEN(p);
1802 }
1803 }
1804 }
1805 # endif
1806 // remove "src/" from exe_name, if present
1807 if (p == exe_name)
1808 pend = remove_tail(p, pend, (char_u *)"src");
1809 #endif
1810
1811 // for $VIM, remove "runtime/" or "vim54/", if present
1812 if (!vimruntime)
1813 {
1814 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
1815 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
1816 }
1817
1818 // remove trailing path separator
1819 if (pend > p && after_pathsep(p, pend))
1820 --pend;
1821
1822 #ifdef MACOS_X
1823 if (p == exe_name || p == p_hf)
1824 #endif
1825 // check that the result is a directory name
1826 p = vim_strnsave(p, pend - p);
1827
1828 if (p != NULL && !mch_isdir(p))
1829 VIM_CLEAR(p);
1830 else
1831 {
1832 #ifdef USE_EXE_NAME
1833 // may add "/vim54" or "/runtime" if it exists
1834 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
1835 {
1836 vim_free(p);
1837 p = pend;
1838 }
1839 #endif
1840 *mustfree = TRUE;
1841 }
1842 }
1843 }
1844
1845 #ifdef HAVE_PATHDEF
1846 // When there is a pathdef.c file we can use default_vim_dir and
1847 // default_vimruntime_dir
1848 if (p == NULL)
1849 {
1850 // Only use default_vimruntime_dir when it is not empty
1851 if (vimruntime && *default_vimruntime_dir != NUL)
1852 {
1853 p = default_vimruntime_dir;
1854 *mustfree = FALSE;
1855 }
1856 else if (*default_vim_dir != NUL)
1857 {
1858 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
1859 *mustfree = TRUE;
1860 else
1861 {
1862 p = default_vim_dir;
1863 *mustfree = FALSE;
1864 }
1865 }
1866 }
1867 #endif
1868
1869 /*
1870 * Set the environment variable, so that the new value can be found fast
1871 * next time, and others can also use it (e.g. Perl).
1872 */
1873 if (p != NULL)
1874 {
1875 if (vimruntime)
1876 {
1877 vim_setenv((char_u *)"VIMRUNTIME", p);
1878 didset_vimruntime = TRUE;
1879 }
1880 else
1881 {
1882 vim_setenv((char_u *)"VIM", p);
1883 didset_vim = TRUE;
1884 }
1885 }
1886 return p;
1887 }
1888
1889 #if defined(FEAT_EVAL) || defined(PROTO)
1890 void
vim_unsetenv(char_u * var)1891 vim_unsetenv(char_u *var)
1892 {
1893 #ifdef HAVE_UNSETENV
1894 unsetenv((char *)var);
1895 #else
1896 vim_setenv(var, (char_u *)"");
1897 #endif
1898 }
1899 #endif
1900
1901
1902 /*
1903 * Set environment variable "name" and take care of side effects.
1904 */
1905 void
vim_setenv_ext(char_u * name,char_u * val)1906 vim_setenv_ext(char_u *name, char_u *val)
1907 {
1908 vim_setenv(name, val);
1909 if (STRICMP(name, "HOME") == 0)
1910 init_homedir();
1911 else if (didset_vim && STRICMP(name, "VIM") == 0)
1912 didset_vim = FALSE;
1913 else if (didset_vimruntime
1914 && STRICMP(name, "VIMRUNTIME") == 0)
1915 didset_vimruntime = FALSE;
1916 }
1917
1918 /*
1919 * Our portable version of setenv.
1920 */
1921 void
vim_setenv(char_u * name,char_u * val)1922 vim_setenv(char_u *name, char_u *val)
1923 {
1924 #ifdef HAVE_SETENV
1925 mch_setenv((char *)name, (char *)val, 1);
1926 #else
1927 char_u *envbuf;
1928
1929 /*
1930 * Putenv does not copy the string, it has to remain
1931 * valid. The allocated memory will never be freed.
1932 */
1933 envbuf = alloc(STRLEN(name) + STRLEN(val) + 2);
1934 if (envbuf != NULL)
1935 {
1936 sprintf((char *)envbuf, "%s=%s", name, val);
1937 putenv((char *)envbuf);
1938 }
1939 #endif
1940 #ifdef FEAT_GETTEXT
1941 /*
1942 * When setting $VIMRUNTIME adjust the directory to find message
1943 * translations to $VIMRUNTIME/lang.
1944 */
1945 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
1946 {
1947 char_u *buf = concat_str(val, (char_u *)"/lang");
1948
1949 if (buf != NULL)
1950 {
1951 bindtextdomain(VIMPACKAGE, (char *)buf);
1952 vim_free(buf);
1953 }
1954 }
1955 #endif
1956 }
1957
1958 /*
1959 * Function given to ExpandGeneric() to obtain an environment variable name.
1960 */
1961 char_u *
get_env_name(expand_T * xp UNUSED,int idx)1962 get_env_name(
1963 expand_T *xp UNUSED,
1964 int idx)
1965 {
1966 # if defined(AMIGA)
1967 /*
1968 * No environ[] on the Amiga.
1969 */
1970 return NULL;
1971 # else
1972 # ifndef __WIN32__
1973 // Borland C++ 5.2 has this in a header file.
1974 extern char **environ;
1975 # endif
1976 # define ENVNAMELEN 100
1977 static char_u name[ENVNAMELEN];
1978 char_u *str;
1979 int n;
1980
1981 str = (char_u *)environ[idx];
1982 if (str == NULL)
1983 return NULL;
1984
1985 for (n = 0; n < ENVNAMELEN - 1; ++n)
1986 {
1987 if (str[n] == '=' || str[n] == NUL)
1988 break;
1989 name[n] = str[n];
1990 }
1991 name[n] = NUL;
1992 return name;
1993 # endif
1994 }
1995
1996 /*
1997 * Add a user name to the list of users in ga_users.
1998 * Do nothing if user name is NULL or empty.
1999 */
2000 static void
add_user(char_u * user,int need_copy)2001 add_user(char_u *user, int need_copy)
2002 {
2003 char_u *user_copy = (user != NULL && need_copy)
2004 ? vim_strsave(user) : user;
2005
2006 if (user_copy == NULL || *user_copy == NUL || ga_grow(&ga_users, 1) == FAIL)
2007 {
2008 if (need_copy)
2009 vim_free(user);
2010 return;
2011 }
2012 ((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user_copy;
2013 }
2014
2015 /*
2016 * Find all user names for user completion.
2017 * Done only once and then cached.
2018 */
2019 static void
init_users(void)2020 init_users(void)
2021 {
2022 static int lazy_init_done = FALSE;
2023
2024 if (lazy_init_done)
2025 return;
2026
2027 lazy_init_done = TRUE;
2028 ga_init2(&ga_users, sizeof(char_u *), 20);
2029
2030 # if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
2031 {
2032 struct passwd* pw;
2033
2034 setpwent();
2035 while ((pw = getpwent()) != NULL)
2036 add_user((char_u *)pw->pw_name, TRUE);
2037 endpwent();
2038 }
2039 # elif defined(MSWIN)
2040 {
2041 DWORD nusers = 0, ntotal = 0, i;
2042 PUSER_INFO_0 uinfo;
2043
2044 if (NetUserEnum(NULL, 0, 0, (LPBYTE *) &uinfo, MAX_PREFERRED_LENGTH,
2045 &nusers, &ntotal, NULL) == NERR_Success)
2046 {
2047 for (i = 0; i < nusers; i++)
2048 add_user(utf16_to_enc(uinfo[i].usri0_name, NULL), FALSE);
2049
2050 NetApiBufferFree(uinfo);
2051 }
2052 }
2053 # endif
2054 # if defined(HAVE_GETPWNAM)
2055 {
2056 char_u *user_env = mch_getenv((char_u *)"USER");
2057
2058 // The $USER environment variable may be a valid remote user name (NIS,
2059 // LDAP) not already listed by getpwent(), as getpwent() only lists
2060 // local user names. If $USER is not already listed, check whether it
2061 // is a valid remote user name using getpwnam() and if it is, add it to
2062 // the list of user names.
2063
2064 if (user_env != NULL && *user_env != NUL)
2065 {
2066 int i;
2067
2068 for (i = 0; i < ga_users.ga_len; i++)
2069 {
2070 char_u *local_user = ((char_u **)ga_users.ga_data)[i];
2071
2072 if (STRCMP(local_user, user_env) == 0)
2073 break;
2074 }
2075
2076 if (i == ga_users.ga_len)
2077 {
2078 struct passwd *pw = getpwnam((char *)user_env);
2079
2080 if (pw != NULL)
2081 add_user((char_u *)pw->pw_name, TRUE);
2082 }
2083 }
2084 }
2085 # endif
2086 }
2087
2088 /*
2089 * Function given to ExpandGeneric() to obtain an user names.
2090 */
2091 char_u*
get_users(expand_T * xp UNUSED,int idx)2092 get_users(expand_T *xp UNUSED, int idx)
2093 {
2094 init_users();
2095 if (idx < ga_users.ga_len)
2096 return ((char_u **)ga_users.ga_data)[idx];
2097 return NULL;
2098 }
2099
2100 /*
2101 * Check whether name matches a user name. Return:
2102 * 0 if name does not match any user name.
2103 * 1 if name partially matches the beginning of a user name.
2104 * 2 is name fully matches a user name.
2105 */
2106 int
match_user(char_u * name)2107 match_user(char_u *name)
2108 {
2109 int i;
2110 int n = (int)STRLEN(name);
2111 int result = 0;
2112
2113 init_users();
2114 for (i = 0; i < ga_users.ga_len; i++)
2115 {
2116 if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
2117 return 2; // full match
2118 if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
2119 result = 1; // partial match
2120 }
2121 return result;
2122 }
2123
2124 static void
prepare_to_exit(void)2125 prepare_to_exit(void)
2126 {
2127 #if defined(SIGHUP) && defined(SIG_IGN)
2128 // Ignore SIGHUP, because a dropped connection causes a read error, which
2129 // makes Vim exit and then handling SIGHUP causes various reentrance
2130 // problems.
2131 signal(SIGHUP, SIG_IGN);
2132 #endif
2133
2134 #ifdef FEAT_GUI
2135 if (gui.in_use)
2136 {
2137 gui.dying = TRUE;
2138 out_trash(); // trash any pending output
2139 }
2140 else
2141 #endif
2142 {
2143 windgoto((int)Rows - 1, 0);
2144
2145 /*
2146 * Switch terminal mode back now, so messages end up on the "normal"
2147 * screen (if there are two screens).
2148 */
2149 settmode(TMODE_COOK);
2150 stoptermcap();
2151 out_flush();
2152 }
2153 }
2154
2155 /*
2156 * Preserve files and exit.
2157 * When called IObuff must contain a message.
2158 * NOTE: This may be called from deathtrap() in a signal handler, avoid unsafe
2159 * functions, such as allocating memory.
2160 */
2161 void
preserve_exit(void)2162 preserve_exit(void)
2163 {
2164 buf_T *buf;
2165
2166 prepare_to_exit();
2167
2168 // Setting this will prevent free() calls. That avoids calling free()
2169 // recursively when free() was invoked with a bad pointer.
2170 really_exiting = TRUE;
2171
2172 out_str(IObuff);
2173 screen_start(); // don't know where cursor is now
2174 out_flush();
2175
2176 ml_close_notmod(); // close all not-modified buffers
2177
2178 FOR_ALL_BUFFERS(buf)
2179 {
2180 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
2181 {
2182 OUT_STR("Vim: preserving files...\r\n");
2183 screen_start(); // don't know where cursor is now
2184 out_flush();
2185 ml_sync_all(FALSE, FALSE); // preserve all swap files
2186 break;
2187 }
2188 }
2189
2190 ml_close_all(FALSE); // close all memfiles, without deleting
2191
2192 OUT_STR("Vim: Finished.\r\n");
2193
2194 getout(1);
2195 }
2196
2197 /*
2198 * Check for CTRL-C pressed, but only once in a while.
2199 * Should be used instead of ui_breakcheck() for functions that check for
2200 * each line in the file. Calling ui_breakcheck() each time takes too much
2201 * time, because it can be a system call.
2202 */
2203
2204 #ifndef BREAKCHECK_SKIP
2205 # define BREAKCHECK_SKIP 1000
2206 #endif
2207
2208 static int breakcheck_count = 0;
2209
2210 void
line_breakcheck(void)2211 line_breakcheck(void)
2212 {
2213 if (++breakcheck_count >= BREAKCHECK_SKIP)
2214 {
2215 breakcheck_count = 0;
2216 ui_breakcheck();
2217 }
2218 }
2219
2220 /*
2221 * Like line_breakcheck() but check 10 times less often.
2222 */
2223 void
fast_breakcheck(void)2224 fast_breakcheck(void)
2225 {
2226 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
2227 {
2228 breakcheck_count = 0;
2229 ui_breakcheck();
2230 }
2231 }
2232
2233 /*
2234 * Like line_breakcheck() but check 100 times less often.
2235 */
2236 void
veryfast_breakcheck(void)2237 veryfast_breakcheck(void)
2238 {
2239 if (++breakcheck_count >= BREAKCHECK_SKIP * 100)
2240 {
2241 breakcheck_count = 0;
2242 ui_breakcheck();
2243 }
2244 }
2245
2246 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) \
2247 || (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
2248 || defined(PROTO)
2249
2250 #ifndef SEEK_SET
2251 # define SEEK_SET 0
2252 #endif
2253 #ifndef SEEK_END
2254 # define SEEK_END 2
2255 #endif
2256
2257 /*
2258 * Get the stdout of an external command.
2259 * If "ret_len" is NULL replace NUL characters with NL. When "ret_len" is not
2260 * NULL store the length there.
2261 * Returns an allocated string, or NULL for error.
2262 */
2263 char_u *
get_cmd_output(char_u * cmd,char_u * infile,int flags,int * ret_len)2264 get_cmd_output(
2265 char_u *cmd,
2266 char_u *infile, // optional input file name
2267 int flags, // can be SHELL_SILENT
2268 int *ret_len)
2269 {
2270 char_u *tempname;
2271 char_u *command;
2272 char_u *buffer = NULL;
2273 int len;
2274 int i = 0;
2275 FILE *fd;
2276
2277 if (check_restricted() || check_secure())
2278 return NULL;
2279
2280 // get a name for the temp file
2281 if ((tempname = vim_tempname('o', FALSE)) == NULL)
2282 {
2283 emsg(_(e_notmp));
2284 return NULL;
2285 }
2286
2287 // Add the redirection stuff
2288 command = make_filter_cmd(cmd, infile, tempname);
2289 if (command == NULL)
2290 goto done;
2291
2292 /*
2293 * Call the shell to execute the command (errors are ignored).
2294 * Don't check timestamps here.
2295 */
2296 ++no_check_timestamps;
2297 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
2298 --no_check_timestamps;
2299
2300 vim_free(command);
2301
2302 /*
2303 * read the names from the file into memory
2304 */
2305 # ifdef VMS
2306 // created temporary file is not always readable as binary
2307 fd = mch_fopen((char *)tempname, "r");
2308 # else
2309 fd = mch_fopen((char *)tempname, READBIN);
2310 # endif
2311
2312 if (fd == NULL)
2313 {
2314 semsg(_(e_notopen), tempname);
2315 goto done;
2316 }
2317
2318 fseek(fd, 0L, SEEK_END);
2319 len = ftell(fd); // get size of temp file
2320 fseek(fd, 0L, SEEK_SET);
2321
2322 buffer = alloc(len + 1);
2323 if (buffer != NULL)
2324 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
2325 fclose(fd);
2326 mch_remove(tempname);
2327 if (buffer == NULL)
2328 goto done;
2329 #ifdef VMS
2330 len = i; // VMS doesn't give us what we asked for...
2331 #endif
2332 if (i != len)
2333 {
2334 semsg(_(e_notread), tempname);
2335 VIM_CLEAR(buffer);
2336 }
2337 else if (ret_len == NULL)
2338 {
2339 // Change NUL into SOH, otherwise the string is truncated.
2340 for (i = 0; i < len; ++i)
2341 if (buffer[i] == NUL)
2342 buffer[i] = 1;
2343
2344 buffer[len] = NUL; // make sure the buffer is terminated
2345 }
2346 else
2347 *ret_len = len;
2348
2349 done:
2350 vim_free(tempname);
2351 return buffer;
2352 }
2353
2354 # if defined(FEAT_EVAL) || defined(PROTO)
2355
2356 static void
get_cmd_output_as_rettv(typval_T * argvars,typval_T * rettv,int retlist)2357 get_cmd_output_as_rettv(
2358 typval_T *argvars,
2359 typval_T *rettv,
2360 int retlist)
2361 {
2362 char_u *res = NULL;
2363 char_u *p;
2364 char_u *infile = NULL;
2365 int err = FALSE;
2366 FILE *fd;
2367 list_T *list = NULL;
2368 int flags = SHELL_SILENT;
2369
2370 rettv->v_type = VAR_STRING;
2371 rettv->vval.v_string = NULL;
2372 if (check_restricted() || check_secure())
2373 goto errret;
2374
2375 if (in_vim9script()
2376 && (check_for_string_arg(argvars, 0) == FAIL
2377 || check_for_opt_string_or_number_or_list_arg(argvars, 1) == FAIL))
2378 return;
2379
2380 if (argvars[1].v_type != VAR_UNKNOWN)
2381 {
2382 /*
2383 * Write the text to a temp file, to be used for input of the shell
2384 * command.
2385 */
2386 if ((infile = vim_tempname('i', TRUE)) == NULL)
2387 {
2388 emsg(_(e_notmp));
2389 goto errret;
2390 }
2391
2392 fd = mch_fopen((char *)infile, WRITEBIN);
2393 if (fd == NULL)
2394 {
2395 semsg(_(e_notopen), infile);
2396 goto errret;
2397 }
2398 if (argvars[1].v_type == VAR_NUMBER)
2399 {
2400 linenr_T lnum;
2401 buf_T *buf;
2402
2403 buf = buflist_findnr(argvars[1].vval.v_number);
2404 if (buf == NULL)
2405 {
2406 semsg(_(e_nobufnr), argvars[1].vval.v_number);
2407 fclose(fd);
2408 goto errret;
2409 }
2410
2411 for (lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++)
2412 {
2413 for (p = ml_get_buf(buf, lnum, FALSE); *p != NUL; ++p)
2414 if (putc(*p == '\n' ? NUL : *p, fd) == EOF)
2415 {
2416 err = TRUE;
2417 break;
2418 }
2419 if (putc(NL, fd) == EOF)
2420 {
2421 err = TRUE;
2422 break;
2423 }
2424 }
2425 }
2426 else if (argvars[1].v_type == VAR_LIST)
2427 {
2428 if (write_list(fd, argvars[1].vval.v_list, TRUE) == FAIL)
2429 err = TRUE;
2430 }
2431 else
2432 {
2433 size_t len;
2434 char_u buf[NUMBUFLEN];
2435
2436 p = tv_get_string_buf_chk(&argvars[1], buf);
2437 if (p == NULL)
2438 {
2439 fclose(fd);
2440 goto errret; // type error; errmsg already given
2441 }
2442 len = STRLEN(p);
2443 if (len > 0 && fwrite(p, len, 1, fd) != 1)
2444 err = TRUE;
2445 }
2446 if (fclose(fd) != 0)
2447 err = TRUE;
2448 if (err)
2449 {
2450 emsg(_("E677: Error writing temp file"));
2451 goto errret;
2452 }
2453 }
2454
2455 // Omit SHELL_COOKED when invoked with ":silent". Avoids that the shell
2456 // echoes typeahead, that messes up the display.
2457 if (!msg_silent)
2458 flags += SHELL_COOKED;
2459
2460 if (retlist)
2461 {
2462 int len;
2463 listitem_T *li;
2464 char_u *s = NULL;
2465 char_u *start;
2466 char_u *end;
2467 int i;
2468
2469 res = get_cmd_output(tv_get_string(&argvars[0]), infile, flags, &len);
2470 if (res == NULL)
2471 goto errret;
2472
2473 list = list_alloc();
2474 if (list == NULL)
2475 goto errret;
2476
2477 for (i = 0; i < len; ++i)
2478 {
2479 start = res + i;
2480 while (i < len && res[i] != NL)
2481 ++i;
2482 end = res + i;
2483
2484 s = alloc(end - start + 1);
2485 if (s == NULL)
2486 goto errret;
2487
2488 for (p = s; start < end; ++p, ++start)
2489 *p = *start == NUL ? NL : *start;
2490 *p = NUL;
2491
2492 li = listitem_alloc();
2493 if (li == NULL)
2494 {
2495 vim_free(s);
2496 goto errret;
2497 }
2498 li->li_tv.v_type = VAR_STRING;
2499 li->li_tv.v_lock = 0;
2500 li->li_tv.vval.v_string = s;
2501 list_append(list, li);
2502 }
2503
2504 rettv_list_set(rettv, list);
2505 list = NULL;
2506 }
2507 else
2508 {
2509 res = get_cmd_output(tv_get_string(&argvars[0]), infile, flags, NULL);
2510 #ifdef USE_CRNL
2511 // translate <CR><NL> into <NL>
2512 if (res != NULL)
2513 {
2514 char_u *s, *d;
2515
2516 d = res;
2517 for (s = res; *s; ++s)
2518 {
2519 if (s[0] == CAR && s[1] == NL)
2520 ++s;
2521 *d++ = *s;
2522 }
2523 *d = NUL;
2524 }
2525 #endif
2526 rettv->vval.v_string = res;
2527 res = NULL;
2528 }
2529
2530 errret:
2531 if (infile != NULL)
2532 {
2533 mch_remove(infile);
2534 vim_free(infile);
2535 }
2536 if (res != NULL)
2537 vim_free(res);
2538 if (list != NULL)
2539 list_free(list);
2540 }
2541
2542 /*
2543 * "system()" function
2544 */
2545 void
f_system(typval_T * argvars,typval_T * rettv)2546 f_system(typval_T *argvars, typval_T *rettv)
2547 {
2548 get_cmd_output_as_rettv(argvars, rettv, FALSE);
2549 }
2550
2551 /*
2552 * "systemlist()" function
2553 */
2554 void
f_systemlist(typval_T * argvars,typval_T * rettv)2555 f_systemlist(typval_T *argvars, typval_T *rettv)
2556 {
2557 get_cmd_output_as_rettv(argvars, rettv, TRUE);
2558 }
2559 # endif // FEAT_EVAL
2560
2561 #endif
2562
2563 /*
2564 * Return TRUE when need to go to Insert mode because of 'insertmode'.
2565 * Don't do this when still processing a command or a mapping.
2566 * Don't do this when inside a ":normal" command.
2567 */
2568 int
goto_im(void)2569 goto_im(void)
2570 {
2571 return (p_im && stuff_empty() && typebuf_typed());
2572 }
2573
2574 /*
2575 * Returns the isolated name of the shell in allocated memory:
2576 * - Skip beyond any path. E.g., "/usr/bin/csh -f" -> "csh -f".
2577 * - Remove any argument. E.g., "csh -f" -> "csh".
2578 * But don't allow a space in the path, so that this works:
2579 * "/usr/bin/csh --rcfile ~/.cshrc"
2580 * But don't do that for Windows, it's common to have a space in the path.
2581 * Returns NULL when out of memory.
2582 */
2583 char_u *
get_isolated_shell_name(void)2584 get_isolated_shell_name(void)
2585 {
2586 char_u *p;
2587
2588 #ifdef MSWIN
2589 p = gettail(p_sh);
2590 p = vim_strnsave(p, skiptowhite(p) - p);
2591 #else
2592 p = skiptowhite(p_sh);
2593 if (*p == NUL)
2594 {
2595 // No white space, use the tail.
2596 p = vim_strsave(gettail(p_sh));
2597 }
2598 else
2599 {
2600 char_u *p1, *p2;
2601
2602 // Find the last path separator before the space.
2603 p1 = p_sh;
2604 for (p2 = p_sh; p2 < p; MB_PTR_ADV(p2))
2605 if (vim_ispathsep(*p2))
2606 p1 = p2 + 1;
2607 p = vim_strnsave(p1, p - p1);
2608 }
2609 #endif
2610 return p;
2611 }
2612
2613 /*
2614 * Check if the "://" of a URL is at the pointer, return URL_SLASH.
2615 * Also check for ":\\", which MS Internet Explorer accepts, return
2616 * URL_BACKSLASH.
2617 */
2618 int
path_is_url(char_u * p)2619 path_is_url(char_u *p)
2620 {
2621 if (STRNCMP(p, "://", (size_t)3) == 0)
2622 return URL_SLASH;
2623 else if (STRNCMP(p, ":\\\\", (size_t)3) == 0)
2624 return URL_BACKSLASH;
2625 return 0;
2626 }
2627
2628 /*
2629 * Check if "fname" starts with "name://" or "name:\\".
2630 * Return URL_SLASH for "name://", URL_BACKSLASH for "name:\\".
2631 * Return zero otherwise.
2632 */
2633 int
path_with_url(char_u * fname)2634 path_with_url(char_u *fname)
2635 {
2636 char_u *p;
2637
2638 // We accept alphabetic characters and a dash in scheme part.
2639 // RFC 3986 allows for more, but it increases the risk of matching
2640 // non-URL text.
2641
2642 // first character must be alpha
2643 if (!isalpha(*fname))
2644 return 0;
2645
2646 // check body: alpha or dash
2647 for (p = fname + 1; (isalpha(*p) || (*p == '-')); ++p)
2648 ;
2649
2650 // check last char is not a dash
2651 if (p[-1] == '-')
2652 return 0;
2653
2654 // "://" or ":\\" must follow
2655 return path_is_url(p);
2656 }
2657
2658 #if defined(FEAT_EVAL) || defined(PROTO)
2659 /*
2660 * Return the dictionary of v:event.
2661 * Save and clear the value in case it already has items.
2662 */
2663 dict_T *
get_v_event(save_v_event_T * sve)2664 get_v_event(save_v_event_T *sve)
2665 {
2666 dict_T *v_event = get_vim_var_dict(VV_EVENT);
2667
2668 if (v_event->dv_hashtab.ht_used > 0)
2669 {
2670 // recursive use of v:event, save, make empty and restore later
2671 sve->sve_did_save = TRUE;
2672 sve->sve_hashtab = v_event->dv_hashtab;
2673 hash_init(&v_event->dv_hashtab);
2674 }
2675 else
2676 sve->sve_did_save = FALSE;
2677 return v_event;
2678 }
2679
2680 void
restore_v_event(dict_T * v_event,save_v_event_T * sve)2681 restore_v_event(dict_T *v_event, save_v_event_T *sve)
2682 {
2683 dict_free_contents(v_event);
2684 if (sve->sve_did_save)
2685 v_event->dv_hashtab = sve->sve_hashtab;
2686 else
2687 hash_init(&v_event->dv_hashtab);
2688 }
2689 #endif
2690
2691 /*
2692 * Fires a ModeChanged autocmd
2693 */
2694 void
trigger_modechanged()2695 trigger_modechanged()
2696 {
2697 #ifdef FEAT_EVAL
2698 dict_T *v_event;
2699 typval_T rettv;
2700 typval_T tv[2];
2701 char_u *pat_pre;
2702 char_u *pat;
2703 save_v_event_T save_v_event;
2704
2705 if (!has_modechanged())
2706 return;
2707
2708 tv[0].v_type = VAR_NUMBER;
2709 tv[0].vval.v_number = 1; // get full mode
2710 tv[1].v_type = VAR_UNKNOWN;
2711 f_mode(tv, &rettv);
2712 if (STRCMP(rettv.vval.v_string, last_mode) == 0)
2713 {
2714 vim_free(rettv.vval.v_string);
2715 return;
2716 }
2717
2718 v_event = get_v_event(&save_v_event);
2719 (void)dict_add_string(v_event, "new_mode", rettv.vval.v_string);
2720 (void)dict_add_string(v_event, "old_mode", last_mode);
2721 dict_set_items_ro(v_event);
2722
2723 // concatenate modes in format "old_mode:new_mode"
2724 pat_pre = concat_str(last_mode, (char_u*)":");
2725 pat = concat_str(pat_pre, rettv.vval.v_string);
2726 vim_free(pat_pre);
2727
2728 apply_autocmds(EVENT_MODECHANGED, pat, NULL, FALSE, curbuf);
2729 STRCPY(last_mode, rettv.vval.v_string);
2730
2731 vim_free(pat);
2732 restore_v_event(v_event, &save_v_event);
2733 vim_free(rettv.vval.v_string);
2734 #endif
2735 }
2736