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 && (State & CMDLINE) == 0)
856 {
857 // Redrawing was postponed, do it now.
858 update_screen(0);
859 setcursor(); // put cursor back where it belongs
860 }
861 continue;
862 }
863 if (n > 0) // found a termcode: adjust length
864 len = n;
865 if (len == 0) // nothing typed yet
866 continue;
867
868 // Handle modifier and/or special key code.
869 n = buf[0];
870 if (n == K_SPECIAL)
871 {
872 n = TO_SPECIAL(buf[1], buf[2]);
873 if (buf[1] == KS_MODIFIER
874 || n == K_IGNORE
875 || (is_mouse_key(n) && n != K_LEFTMOUSE)
876 #ifdef FEAT_GUI
877 || n == K_VER_SCROLLBAR
878 || n == K_HOR_SCROLLBAR
879 #endif
880 )
881 {
882 if (buf[1] == KS_MODIFIER)
883 mod_mask = buf[2];
884 len -= 3;
885 if (len > 0)
886 mch_memmove(buf, buf + 3, (size_t)len);
887 continue;
888 }
889 break;
890 }
891 if (has_mbyte)
892 {
893 if (MB_BYTE2LEN(n) > len)
894 continue; // more bytes to get
895 buf[len >= buflen ? buflen - 1 : len] = NUL;
896 n = (*mb_ptr2char)(buf);
897 }
898 #ifdef UNIX
899 if (n == intr_char)
900 n = ESC;
901 #endif
902 break;
903 }
904 vim_free(buf);
905
906 mapped_ctrl_c = save_mapped_ctrl_c;
907 return n;
908 }
909
910 /*
911 * Get a number from the user.
912 * When "mouse_used" is not NULL allow using the mouse.
913 */
914 int
get_number(int colon,int * mouse_used)915 get_number(
916 int colon, // allow colon to abort
917 int *mouse_used)
918 {
919 int n = 0;
920 int c;
921 int typed = 0;
922
923 if (mouse_used != NULL)
924 *mouse_used = FALSE;
925
926 // When not printing messages, the user won't know what to type, return a
927 // zero (as if CR was hit).
928 if (msg_silent != 0)
929 return 0;
930
931 #ifdef USE_ON_FLY_SCROLL
932 dont_scroll = TRUE; // disallow scrolling here
933 #endif
934 ++no_mapping;
935 ++allow_keys; // no mapping here, but recognize keys
936 for (;;)
937 {
938 windgoto(msg_row, msg_col);
939 c = safe_vgetc();
940 if (VIM_ISDIGIT(c))
941 {
942 n = n * 10 + c - '0';
943 msg_putchar(c);
944 ++typed;
945 }
946 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
947 {
948 if (typed > 0)
949 {
950 msg_puts("\b \b");
951 --typed;
952 }
953 n /= 10;
954 }
955 else if (mouse_used != NULL && c == K_LEFTMOUSE)
956 {
957 *mouse_used = TRUE;
958 n = mouse_row + 1;
959 break;
960 }
961 else if (n == 0 && c == ':' && colon)
962 {
963 stuffcharReadbuff(':');
964 if (!exmode_active)
965 cmdline_row = msg_row;
966 skip_redraw = TRUE; // skip redraw once
967 do_redraw = FALSE;
968 break;
969 }
970 else if (c == Ctrl_C || c == ESC || c == 'q')
971 {
972 n = 0;
973 break;
974 }
975 else if (c == CAR || c == NL )
976 break;
977 }
978 --no_mapping;
979 --allow_keys;
980 return n;
981 }
982
983 /*
984 * Ask the user to enter a number.
985 * When "mouse_used" is not NULL allow using the mouse and in that case return
986 * the line number.
987 */
988 int
prompt_for_number(int * mouse_used)989 prompt_for_number(int *mouse_used)
990 {
991 int i;
992 int save_cmdline_row;
993 int save_State;
994
995 // When using ":silent" assume that <CR> was entered.
996 if (mouse_used != NULL)
997 msg_puts(_("Type number and <Enter> or click with the mouse (q or empty cancels): "));
998 else
999 msg_puts(_("Type number and <Enter> (q or empty cancels): "));
1000
1001 // Set the state such that text can be selected/copied/pasted and we still
1002 // get mouse events. redraw_after_callback() will not redraw if cmdline_row
1003 // is zero.
1004 save_cmdline_row = cmdline_row;
1005 cmdline_row = 0;
1006 save_State = State;
1007 State = CMDLINE;
1008 // May show different mouse shape.
1009 setmouse();
1010
1011 i = get_number(TRUE, mouse_used);
1012 if (KeyTyped)
1013 {
1014 // don't call wait_return() now
1015 if (msg_row > 0)
1016 cmdline_row = msg_row - 1;
1017 need_wait_return = FALSE;
1018 msg_didany = FALSE;
1019 msg_didout = FALSE;
1020 }
1021 else
1022 cmdline_row = save_cmdline_row;
1023 State = save_State;
1024 // May need to restore mouse shape.
1025 setmouse();
1026
1027 return i;
1028 }
1029
1030 void
msgmore(long n)1031 msgmore(long n)
1032 {
1033 long pn;
1034
1035 if (global_busy // no messages now, wait until global is finished
1036 || !messaging()) // 'lazyredraw' set, don't do messages now
1037 return;
1038
1039 // We don't want to overwrite another important message, but do overwrite
1040 // a previous "more lines" or "fewer lines" message, so that "5dd" and
1041 // then "put" reports the last action.
1042 if (keep_msg != NULL && !keep_msg_more)
1043 return;
1044
1045 if (n > 0)
1046 pn = n;
1047 else
1048 pn = -n;
1049
1050 if (pn > p_report)
1051 {
1052 if (n > 0)
1053 vim_snprintf(msg_buf, MSG_BUF_LEN,
1054 NGETTEXT("%ld more line", "%ld more lines", pn), pn);
1055 else
1056 vim_snprintf(msg_buf, MSG_BUF_LEN,
1057 NGETTEXT("%ld line less", "%ld fewer lines", pn), pn);
1058 if (got_int)
1059 vim_strcat((char_u *)msg_buf, (char_u *)_(" (Interrupted)"),
1060 MSG_BUF_LEN);
1061 if (msg(msg_buf))
1062 {
1063 set_keep_msg((char_u *)msg_buf, 0);
1064 keep_msg_more = TRUE;
1065 }
1066 }
1067 }
1068
1069 /*
1070 * flush map and typeahead buffers and give a warning for an error
1071 */
1072 void
beep_flush(void)1073 beep_flush(void)
1074 {
1075 if (emsg_silent == 0)
1076 {
1077 flush_buffers(FLUSH_MINIMAL);
1078 vim_beep(BO_ERROR);
1079 }
1080 }
1081
1082 /*
1083 * Give a warning for an error.
1084 */
1085 void
vim_beep(unsigned val)1086 vim_beep(
1087 unsigned val) // one of the BO_ values, e.g., BO_OPER
1088 {
1089 #ifdef FEAT_EVAL
1090 called_vim_beep = TRUE;
1091 #endif
1092
1093 if (emsg_silent == 0 && !in_assert_fails)
1094 {
1095 if (!((bo_flags & val) || (bo_flags & BO_ALL)))
1096 {
1097 #ifdef ELAPSED_FUNC
1098 static int did_init = FALSE;
1099 static elapsed_T start_tv;
1100
1101 // Only beep once per half a second, otherwise a sequence of beeps
1102 // would freeze Vim.
1103 if (!did_init || ELAPSED_FUNC(start_tv) > 500)
1104 {
1105 did_init = TRUE;
1106 ELAPSED_INIT(start_tv);
1107 #endif
1108 if (p_vb
1109 #ifdef FEAT_GUI
1110 // While the GUI is starting up the termcap is set for
1111 // the GUI but the output still goes to a terminal.
1112 && !(gui.in_use && gui.starting)
1113 #endif
1114 )
1115 {
1116 out_str_cf(T_VB);
1117 #ifdef FEAT_VTP
1118 // No restore color information, refresh the screen.
1119 if (has_vtp_working() != 0
1120 # ifdef FEAT_TERMGUICOLORS
1121 && (p_tgc || (!p_tgc && t_colors >= 256))
1122 # endif
1123 )
1124 {
1125 redraw_later(CLEAR);
1126 update_screen(0);
1127 redrawcmd();
1128 }
1129 #endif
1130 }
1131 else
1132 out_char(BELL);
1133 #ifdef ELAPSED_FUNC
1134 }
1135 #endif
1136 }
1137
1138 // When 'debug' contains "beep" produce a message. If we are sourcing
1139 // a script or executing a function give the user a hint where the beep
1140 // comes from.
1141 if (vim_strchr(p_debug, 'e') != NULL)
1142 {
1143 msg_source(HL_ATTR(HLF_W));
1144 msg_attr(_("Beep!"), HL_ATTR(HLF_W));
1145 }
1146 }
1147 }
1148
1149 /*
1150 * To get the "real" home directory:
1151 * - get value of $HOME
1152 * For Unix:
1153 * - go to that directory
1154 * - do mch_dirname() to get the real name of that directory.
1155 * This also works with mounts and links.
1156 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
1157 * For Windows:
1158 * This code is duplicated in init_homedir() in dosinst.c. Keep in sync!
1159 */
1160 void
init_homedir(void)1161 init_homedir(void)
1162 {
1163 char_u *var;
1164
1165 // In case we are called a second time (when 'encoding' changes).
1166 VIM_CLEAR(homedir);
1167
1168 #ifdef VMS
1169 var = mch_getenv((char_u *)"SYS$LOGIN");
1170 #else
1171 var = mch_getenv((char_u *)"HOME");
1172 #endif
1173
1174 #ifdef MSWIN
1175 /*
1176 * Typically, $HOME is not defined on Windows, unless the user has
1177 * specifically defined it for Vim's sake. However, on Windows NT
1178 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
1179 * each user. Try constructing $HOME from these.
1180 */
1181 if (var == NULL || *var == NUL)
1182 {
1183 char_u *homedrive, *homepath;
1184
1185 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
1186 homepath = mch_getenv((char_u *)"HOMEPATH");
1187 if (homepath == NULL || *homepath == NUL)
1188 homepath = (char_u *)"\\";
1189 if (homedrive != NULL
1190 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
1191 {
1192 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
1193 if (NameBuff[0] != NUL)
1194 var = NameBuff;
1195 }
1196 }
1197
1198 if (var == NULL)
1199 var = mch_getenv((char_u *)"USERPROFILE");
1200
1201 /*
1202 * Weird but true: $HOME may contain an indirect reference to another
1203 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
1204 * when $HOME is being set.
1205 */
1206 if (var != NULL && *var == '%')
1207 {
1208 char_u *p;
1209 char_u *exp;
1210
1211 p = vim_strchr(var + 1, '%');
1212 if (p != NULL)
1213 {
1214 vim_strncpy(NameBuff, var + 1, p - (var + 1));
1215 exp = mch_getenv(NameBuff);
1216 if (exp != NULL && *exp != NUL
1217 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
1218 {
1219 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
1220 var = NameBuff;
1221 }
1222 }
1223 }
1224
1225 if (var != NULL && *var == NUL) // empty is same as not set
1226 var = NULL;
1227
1228 if (enc_utf8 && var != NULL)
1229 {
1230 int len;
1231 char_u *pp = NULL;
1232
1233 // Convert from active codepage to UTF-8. Other conversions are
1234 // not done, because they would fail for non-ASCII characters.
1235 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
1236 if (pp != NULL)
1237 {
1238 homedir = pp;
1239 return;
1240 }
1241 }
1242
1243 /*
1244 * Default home dir is C:/
1245 * Best assumption we can make in such a situation.
1246 */
1247 if (var == NULL)
1248 var = (char_u *)"C:/";
1249 #endif
1250
1251 if (var != NULL)
1252 {
1253 #ifdef UNIX
1254 /*
1255 * Change to the directory and get the actual path. This resolves
1256 * links. Don't do it when we can't return.
1257 */
1258 if (mch_dirname(NameBuff, MAXPATHL) == OK
1259 && mch_chdir((char *)NameBuff) == 0)
1260 {
1261 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
1262 var = IObuff;
1263 if (mch_chdir((char *)NameBuff) != 0)
1264 emsg(_(e_prev_dir));
1265 }
1266 #endif
1267 homedir = vim_strsave(var);
1268 }
1269 }
1270
1271 #if defined(EXITFREE) || defined(PROTO)
1272 void
free_homedir(void)1273 free_homedir(void)
1274 {
1275 vim_free(homedir);
1276 }
1277
1278 void
free_users(void)1279 free_users(void)
1280 {
1281 ga_clear_strings(&ga_users);
1282 }
1283 #endif
1284
1285 /*
1286 * Call expand_env() and store the result in an allocated string.
1287 * This is not very memory efficient, this expects the result to be freed
1288 * again soon.
1289 */
1290 char_u *
expand_env_save(char_u * src)1291 expand_env_save(char_u *src)
1292 {
1293 return expand_env_save_opt(src, FALSE);
1294 }
1295
1296 /*
1297 * Idem, but when "one" is TRUE handle the string as one file name, only
1298 * expand "~" at the start.
1299 */
1300 char_u *
expand_env_save_opt(char_u * src,int one)1301 expand_env_save_opt(char_u *src, int one)
1302 {
1303 char_u *p;
1304
1305 p = alloc(MAXPATHL);
1306 if (p != NULL)
1307 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
1308 return p;
1309 }
1310
1311 /*
1312 * Expand environment variable with path name.
1313 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
1314 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
1315 * If anything fails no expansion is done and dst equals src.
1316 */
1317 void
expand_env(char_u * src,char_u * dst,int dstlen)1318 expand_env(
1319 char_u *src, // input string e.g. "$HOME/vim.hlp"
1320 char_u *dst, // where to put the result
1321 int dstlen) // maximum length of the result
1322 {
1323 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
1324 }
1325
1326 void
expand_env_esc(char_u * srcp,char_u * dst,int dstlen,int esc,int one,char_u * startstr)1327 expand_env_esc(
1328 char_u *srcp, // input string e.g. "$HOME/vim.hlp"
1329 char_u *dst, // where to put the result
1330 int dstlen, // maximum length of the result
1331 int esc, // escape spaces in expanded variables
1332 int one, // "srcp" is one file name
1333 char_u *startstr) // start again after this (can be NULL)
1334 {
1335 char_u *src;
1336 char_u *tail;
1337 int c;
1338 char_u *var;
1339 int copy_char;
1340 int mustfree; // var was allocated, need to free it later
1341 int at_start = TRUE; // at start of a name
1342 int startstr_len = 0;
1343
1344 if (startstr != NULL)
1345 startstr_len = (int)STRLEN(startstr);
1346
1347 src = skipwhite(srcp);
1348 --dstlen; // leave one char space for "\,"
1349 while (*src && dstlen > 0)
1350 {
1351 #ifdef FEAT_EVAL
1352 // Skip over `=expr`.
1353 if (src[0] == '`' && src[1] == '=')
1354 {
1355 size_t len;
1356
1357 var = src;
1358 src += 2;
1359 (void)skip_expr(&src, NULL);
1360 if (*src == '`')
1361 ++src;
1362 len = src - var;
1363 if (len > (size_t)dstlen)
1364 len = dstlen;
1365 vim_strncpy(dst, var, len);
1366 dst += len;
1367 dstlen -= (int)len;
1368 continue;
1369 }
1370 #endif
1371 copy_char = TRUE;
1372 if ((*src == '$'
1373 #ifdef VMS
1374 && at_start
1375 #endif
1376 )
1377 #if defined(MSWIN)
1378 || *src == '%'
1379 #endif
1380 || (*src == '~' && at_start))
1381 {
1382 mustfree = FALSE;
1383
1384 /*
1385 * The variable name is copied into dst temporarily, because it may
1386 * be a string in read-only memory and a NUL needs to be appended.
1387 */
1388 if (*src != '~') // environment var
1389 {
1390 tail = src + 1;
1391 var = dst;
1392 c = dstlen - 1;
1393
1394 #ifdef UNIX
1395 // Unix has ${var-name} type environment vars
1396 if (*tail == '{' && !vim_isIDc('{'))
1397 {
1398 tail++; // ignore '{'
1399 while (c-- > 0 && *tail && *tail != '}')
1400 *var++ = *tail++;
1401 }
1402 else
1403 #endif
1404 {
1405 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
1406 #if defined(MSWIN)
1407 || (*src == '%' && *tail != '%')
1408 #endif
1409 ))
1410 *var++ = *tail++;
1411 }
1412
1413 #if defined(MSWIN) || defined(UNIX)
1414 # ifdef UNIX
1415 if (src[1] == '{' && *tail != '}')
1416 # else
1417 if (*src == '%' && *tail != '%')
1418 # endif
1419 var = NULL;
1420 else
1421 {
1422 # ifdef UNIX
1423 if (src[1] == '{')
1424 # else
1425 if (*src == '%')
1426 #endif
1427 ++tail;
1428 #endif
1429 *var = NUL;
1430 var = vim_getenv(dst, &mustfree);
1431 #if defined(MSWIN) || defined(UNIX)
1432 }
1433 #endif
1434 }
1435 // home directory
1436 else if ( src[1] == NUL
1437 || vim_ispathsep(src[1])
1438 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
1439 {
1440 var = homedir;
1441 tail = src + 1;
1442 }
1443 else // user directory
1444 {
1445 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
1446 /*
1447 * Copy ~user to dst[], so we can put a NUL after it.
1448 */
1449 tail = src;
1450 var = dst;
1451 c = dstlen - 1;
1452 while ( c-- > 0
1453 && *tail
1454 && vim_isfilec(*tail)
1455 && !vim_ispathsep(*tail))
1456 *var++ = *tail++;
1457 *var = NUL;
1458 # ifdef UNIX
1459 /*
1460 * If the system supports getpwnam(), use it.
1461 * Otherwise, or if getpwnam() fails, the shell is used to
1462 * expand ~user. This is slower and may fail if the shell
1463 * does not support ~user (old versions of /bin/sh).
1464 */
1465 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
1466 {
1467 // Note: memory allocated by getpwnam() is never freed.
1468 // Calling endpwent() apparently doesn't help.
1469 struct passwd *pw = (*dst == NUL)
1470 ? NULL : getpwnam((char *)dst + 1);
1471
1472 var = (pw == NULL) ? NULL : (char_u *)pw->pw_dir;
1473 }
1474 if (var == NULL)
1475 # endif
1476 {
1477 expand_T xpc;
1478
1479 ExpandInit(&xpc);
1480 xpc.xp_context = EXPAND_FILES;
1481 var = ExpandOne(&xpc, dst, NULL,
1482 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
1483 mustfree = TRUE;
1484 }
1485
1486 # else // !UNIX, thus VMS
1487 /*
1488 * USER_HOME is a comma-separated list of
1489 * directories to search for the user account in.
1490 */
1491 {
1492 char_u test[MAXPATHL], paths[MAXPATHL];
1493 char_u *path, *next_path, *ptr;
1494 stat_T st;
1495
1496 STRCPY(paths, USER_HOME);
1497 next_path = paths;
1498 while (*next_path)
1499 {
1500 for (path = next_path; *next_path && *next_path != ',';
1501 next_path++);
1502 if (*next_path)
1503 *next_path++ = NUL;
1504 STRCPY(test, path);
1505 STRCAT(test, "/");
1506 STRCAT(test, dst + 1);
1507 if (mch_stat(test, &st) == 0)
1508 {
1509 var = alloc(STRLEN(test) + 1);
1510 STRCPY(var, test);
1511 mustfree = TRUE;
1512 break;
1513 }
1514 }
1515 }
1516 # endif // UNIX
1517 #else
1518 // cannot expand user's home directory, so don't try
1519 var = NULL;
1520 tail = (char_u *)""; // for gcc
1521 #endif // UNIX || VMS
1522 }
1523
1524 #ifdef BACKSLASH_IN_FILENAME
1525 // If 'shellslash' is set change backslashes to forward slashes.
1526 // Can't use slash_adjust(), p_ssl may be set temporarily.
1527 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
1528 {
1529 char_u *p = vim_strsave(var);
1530
1531 if (p != NULL)
1532 {
1533 if (mustfree)
1534 vim_free(var);
1535 var = p;
1536 mustfree = TRUE;
1537 forward_slash(var);
1538 }
1539 }
1540 #endif
1541
1542 // If "var" contains white space, escape it with a backslash.
1543 // Required for ":e ~/tt" when $HOME includes a space.
1544 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
1545 {
1546 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
1547
1548 if (p != NULL)
1549 {
1550 if (mustfree)
1551 vim_free(var);
1552 var = p;
1553 mustfree = TRUE;
1554 }
1555 }
1556
1557 if (var != NULL && *var != NUL
1558 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
1559 {
1560 STRCPY(dst, var);
1561 dstlen -= (int)STRLEN(var);
1562 c = (int)STRLEN(var);
1563 // if var[] ends in a path separator and tail[] starts
1564 // with it, skip a character
1565 if (*var != NUL && after_pathsep(dst, dst + c)
1566 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
1567 && dst[-1] != ':'
1568 #endif
1569 && vim_ispathsep(*tail))
1570 ++tail;
1571 dst += c;
1572 src = tail;
1573 copy_char = FALSE;
1574 }
1575 if (mustfree)
1576 vim_free(var);
1577 }
1578
1579 if (copy_char) // copy at least one char
1580 {
1581 /*
1582 * Recognize the start of a new name, for '~'.
1583 * Don't do this when "one" is TRUE, to avoid expanding "~" in
1584 * ":edit foo ~ foo".
1585 */
1586 at_start = FALSE;
1587 if (src[0] == '\\' && src[1] != NUL)
1588 {
1589 *dst++ = *src++;
1590 --dstlen;
1591 }
1592 else if ((src[0] == ' ' || src[0] == ',') && !one)
1593 at_start = TRUE;
1594 if (dstlen > 0)
1595 {
1596 *dst++ = *src++;
1597 --dstlen;
1598
1599 if (startstr != NULL && src - startstr_len >= srcp
1600 && STRNCMP(src - startstr_len, startstr,
1601 startstr_len) == 0)
1602 at_start = TRUE;
1603 }
1604 }
1605
1606 }
1607 *dst = NUL;
1608 }
1609
1610 /*
1611 * If the string between "p" and "pend" ends in "name/", return "pend" minus
1612 * the length of "name/". Otherwise return "pend".
1613 */
1614 static char_u *
remove_tail(char_u * p,char_u * pend,char_u * name)1615 remove_tail(char_u *p, char_u *pend, char_u *name)
1616 {
1617 int len = (int)STRLEN(name) + 1;
1618 char_u *newend = pend - len;
1619
1620 if (newend >= p
1621 && fnamencmp(newend, name, len - 1) == 0
1622 && (newend == p || after_pathsep(p, newend)))
1623 return newend;
1624 return pend;
1625 }
1626
1627 /*
1628 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
1629 * Return NULL if not, return its name in allocated memory otherwise.
1630 */
1631 static char_u *
vim_version_dir(char_u * vimdir)1632 vim_version_dir(char_u *vimdir)
1633 {
1634 char_u *p;
1635
1636 if (vimdir == NULL || *vimdir == NUL)
1637 return NULL;
1638 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
1639 if (p != NULL && mch_isdir(p))
1640 return p;
1641 vim_free(p);
1642 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
1643 if (p != NULL && mch_isdir(p))
1644 return p;
1645 vim_free(p);
1646 return NULL;
1647 }
1648
1649 /*
1650 * Vim's version of getenv().
1651 * Special handling of $HOME, $VIM and $VIMRUNTIME.
1652 * Also does ACP to 'enc' conversion for Win32.
1653 * "mustfree" is set to TRUE when returned is allocated, it must be
1654 * initialized to FALSE by the caller.
1655 */
1656 char_u *
vim_getenv(char_u * name,int * mustfree)1657 vim_getenv(char_u *name, int *mustfree)
1658 {
1659 char_u *p = NULL;
1660 char_u *pend;
1661 int vimruntime;
1662 #ifdef MSWIN
1663 WCHAR *wn, *wp;
1664
1665 // use "C:/" when $HOME is not set
1666 if (STRCMP(name, "HOME") == 0)
1667 return homedir;
1668
1669 // Use Wide function
1670 wn = enc_to_utf16(name, NULL);
1671 if (wn == NULL)
1672 return NULL;
1673
1674 wp = _wgetenv(wn);
1675 vim_free(wn);
1676
1677 if (wp != NULL && *wp == NUL) // empty is the same as not set
1678 wp = NULL;
1679
1680 if (wp != NULL)
1681 {
1682 p = utf16_to_enc(wp, NULL);
1683 if (p == NULL)
1684 return NULL;
1685
1686 *mustfree = TRUE;
1687 return p;
1688 }
1689 #else
1690 p = mch_getenv(name);
1691 if (p != NULL && *p == NUL) // empty is the same as not set
1692 p = NULL;
1693
1694 if (p != NULL)
1695 return p;
1696
1697 # ifdef __HAIKU__
1698 // special handling for user settings directory...
1699 if (STRCMP(name, "BE_USER_SETTINGS") == 0)
1700 {
1701 static char userSettingsPath[MAXPATHL];
1702
1703 if (find_directory(B_USER_SETTINGS_DIRECTORY, 0, false,
1704 userSettingsPath, MAXPATHL) == B_OK)
1705 return (char_u *)userSettingsPath;
1706 else
1707 return NULL;
1708 }
1709 # endif
1710 #endif
1711
1712 // handling $VIMRUNTIME and $VIM is below, bail out if it's another name.
1713 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
1714 if (!vimruntime && STRCMP(name, "VIM") != 0)
1715 return NULL;
1716
1717 /*
1718 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
1719 * Don't do this when default_vimruntime_dir is non-empty.
1720 */
1721 if (vimruntime
1722 #ifdef HAVE_PATHDEF
1723 && *default_vimruntime_dir == NUL
1724 #endif
1725 )
1726 {
1727 #ifdef MSWIN
1728 // Use Wide function
1729 wp = _wgetenv(L"VIM");
1730 if (wp != NULL && *wp == NUL) // empty is the same as not set
1731 wp = NULL;
1732 if (wp != NULL)
1733 {
1734 char_u *q = utf16_to_enc(wp, NULL);
1735 if (q != NULL)
1736 {
1737 p = vim_version_dir(q);
1738 *mustfree = TRUE;
1739 if (p == NULL)
1740 p = q;
1741 }
1742 }
1743 #else
1744 p = mch_getenv((char_u *)"VIM");
1745 if (p != NULL && *p == NUL) // empty is the same as not set
1746 p = NULL;
1747 if (p != NULL)
1748 {
1749 p = vim_version_dir(p);
1750 if (p != NULL)
1751 *mustfree = TRUE;
1752 else
1753 p = mch_getenv((char_u *)"VIM");
1754 }
1755 #endif
1756 }
1757
1758 /*
1759 * When expanding $VIM or $VIMRUNTIME fails, try using:
1760 * - the directory name from 'helpfile' (unless it contains '$')
1761 * - the executable name from argv[0]
1762 */
1763 if (p == NULL)
1764 {
1765 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
1766 p = p_hf;
1767 #ifdef USE_EXE_NAME
1768 /*
1769 * Use the name of the executable, obtained from argv[0].
1770 */
1771 else
1772 p = exe_name;
1773 #endif
1774 if (p != NULL)
1775 {
1776 // remove the file name
1777 pend = gettail(p);
1778
1779 // remove "doc/" from 'helpfile', if present
1780 if (p == p_hf)
1781 pend = remove_tail(p, pend, (char_u *)"doc");
1782
1783 #ifdef USE_EXE_NAME
1784 # ifdef MACOS_X
1785 // remove "MacOS" from exe_name and add "Resources/vim"
1786 if (p == exe_name)
1787 {
1788 char_u *pend1;
1789 char_u *pnew;
1790
1791 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
1792 if (pend1 != pend)
1793 {
1794 pnew = alloc(pend1 - p + 15);
1795 if (pnew != NULL)
1796 {
1797 STRNCPY(pnew, p, (pend1 - p));
1798 STRCPY(pnew + (pend1 - p), "Resources/vim");
1799 p = pnew;
1800 pend = p + STRLEN(p);
1801 }
1802 }
1803 }
1804 # endif
1805 // remove "src/" from exe_name, if present
1806 if (p == exe_name)
1807 pend = remove_tail(p, pend, (char_u *)"src");
1808 #endif
1809
1810 // for $VIM, remove "runtime/" or "vim54/", if present
1811 if (!vimruntime)
1812 {
1813 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
1814 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
1815 }
1816
1817 // remove trailing path separator
1818 if (pend > p && after_pathsep(p, pend))
1819 --pend;
1820
1821 #ifdef MACOS_X
1822 if (p == exe_name || p == p_hf)
1823 #endif
1824 // check that the result is a directory name
1825 p = vim_strnsave(p, pend - p);
1826
1827 if (p != NULL && !mch_isdir(p))
1828 VIM_CLEAR(p);
1829 else
1830 {
1831 #ifdef USE_EXE_NAME
1832 // may add "/vim54" or "/runtime" if it exists
1833 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
1834 {
1835 vim_free(p);
1836 p = pend;
1837 }
1838 #endif
1839 *mustfree = TRUE;
1840 }
1841 }
1842 }
1843
1844 #ifdef HAVE_PATHDEF
1845 // When there is a pathdef.c file we can use default_vim_dir and
1846 // default_vimruntime_dir
1847 if (p == NULL)
1848 {
1849 // Only use default_vimruntime_dir when it is not empty
1850 if (vimruntime && *default_vimruntime_dir != NUL)
1851 {
1852 p = default_vimruntime_dir;
1853 *mustfree = FALSE;
1854 }
1855 else if (*default_vim_dir != NUL)
1856 {
1857 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
1858 *mustfree = TRUE;
1859 else
1860 {
1861 p = default_vim_dir;
1862 *mustfree = FALSE;
1863 }
1864 }
1865 }
1866 #endif
1867
1868 /*
1869 * Set the environment variable, so that the new value can be found fast
1870 * next time, and others can also use it (e.g. Perl).
1871 */
1872 if (p != NULL)
1873 {
1874 if (vimruntime)
1875 {
1876 vim_setenv((char_u *)"VIMRUNTIME", p);
1877 didset_vimruntime = TRUE;
1878 }
1879 else
1880 {
1881 vim_setenv((char_u *)"VIM", p);
1882 didset_vim = TRUE;
1883 }
1884 }
1885 return p;
1886 }
1887
1888 #if defined(FEAT_EVAL) || defined(PROTO)
1889 void
vim_unsetenv(char_u * var)1890 vim_unsetenv(char_u *var)
1891 {
1892 #ifdef HAVE_UNSETENV
1893 unsetenv((char *)var);
1894 #else
1895 vim_setenv(var, (char_u *)"");
1896 #endif
1897 }
1898 #endif
1899
1900
1901 /*
1902 * Set environment variable "name" and take care of side effects.
1903 */
1904 void
vim_setenv_ext(char_u * name,char_u * val)1905 vim_setenv_ext(char_u *name, char_u *val)
1906 {
1907 vim_setenv(name, val);
1908 if (STRICMP(name, "HOME") == 0)
1909 init_homedir();
1910 else if (didset_vim && STRICMP(name, "VIM") == 0)
1911 didset_vim = FALSE;
1912 else if (didset_vimruntime
1913 && STRICMP(name, "VIMRUNTIME") == 0)
1914 didset_vimruntime = FALSE;
1915 }
1916
1917 /*
1918 * Our portable version of setenv.
1919 */
1920 void
vim_setenv(char_u * name,char_u * val)1921 vim_setenv(char_u *name, char_u *val)
1922 {
1923 #ifdef HAVE_SETENV
1924 mch_setenv((char *)name, (char *)val, 1);
1925 #else
1926 char_u *envbuf;
1927
1928 /*
1929 * Putenv does not copy the string, it has to remain
1930 * valid. The allocated memory will never be freed.
1931 */
1932 envbuf = alloc(STRLEN(name) + STRLEN(val) + 2);
1933 if (envbuf != NULL)
1934 {
1935 sprintf((char *)envbuf, "%s=%s", name, val);
1936 putenv((char *)envbuf);
1937 }
1938 #endif
1939 #ifdef FEAT_GETTEXT
1940 /*
1941 * When setting $VIMRUNTIME adjust the directory to find message
1942 * translations to $VIMRUNTIME/lang.
1943 */
1944 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
1945 {
1946 char_u *buf = concat_str(val, (char_u *)"/lang");
1947
1948 if (buf != NULL)
1949 {
1950 bindtextdomain(VIMPACKAGE, (char *)buf);
1951 vim_free(buf);
1952 }
1953 }
1954 #endif
1955 }
1956
1957 /*
1958 * Function given to ExpandGeneric() to obtain an environment variable name.
1959 */
1960 char_u *
get_env_name(expand_T * xp UNUSED,int idx)1961 get_env_name(
1962 expand_T *xp UNUSED,
1963 int idx)
1964 {
1965 # if defined(AMIGA)
1966 /*
1967 * No environ[] on the Amiga.
1968 */
1969 return NULL;
1970 # else
1971 # ifndef __WIN32__
1972 // Borland C++ 5.2 has this in a header file.
1973 extern char **environ;
1974 # endif
1975 # define ENVNAMELEN 100
1976 static char_u name[ENVNAMELEN];
1977 char_u *str;
1978 int n;
1979
1980 str = (char_u *)environ[idx];
1981 if (str == NULL)
1982 return NULL;
1983
1984 for (n = 0; n < ENVNAMELEN - 1; ++n)
1985 {
1986 if (str[n] == '=' || str[n] == NUL)
1987 break;
1988 name[n] = str[n];
1989 }
1990 name[n] = NUL;
1991 return name;
1992 # endif
1993 }
1994
1995 /*
1996 * Add a user name to the list of users in ga_users.
1997 * Do nothing if user name is NULL or empty.
1998 */
1999 static void
add_user(char_u * user,int need_copy)2000 add_user(char_u *user, int need_copy)
2001 {
2002 char_u *user_copy = (user != NULL && need_copy)
2003 ? vim_strsave(user) : user;
2004
2005 if (user_copy == NULL || *user_copy == NUL || ga_grow(&ga_users, 1) == FAIL)
2006 {
2007 if (need_copy)
2008 vim_free(user);
2009 return;
2010 }
2011 ((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user_copy;
2012 }
2013
2014 /*
2015 * Find all user names for user completion.
2016 * Done only once and then cached.
2017 */
2018 static void
init_users(void)2019 init_users(void)
2020 {
2021 static int lazy_init_done = FALSE;
2022
2023 if (lazy_init_done)
2024 return;
2025
2026 lazy_init_done = TRUE;
2027 ga_init2(&ga_users, sizeof(char_u *), 20);
2028
2029 # if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
2030 {
2031 struct passwd* pw;
2032
2033 setpwent();
2034 while ((pw = getpwent()) != NULL)
2035 add_user((char_u *)pw->pw_name, TRUE);
2036 endpwent();
2037 }
2038 # elif defined(MSWIN)
2039 {
2040 DWORD nusers = 0, ntotal = 0, i;
2041 PUSER_INFO_0 uinfo;
2042
2043 if (NetUserEnum(NULL, 0, 0, (LPBYTE *) &uinfo, MAX_PREFERRED_LENGTH,
2044 &nusers, &ntotal, NULL) == NERR_Success)
2045 {
2046 for (i = 0; i < nusers; i++)
2047 add_user(utf16_to_enc(uinfo[i].usri0_name, NULL), FALSE);
2048
2049 NetApiBufferFree(uinfo);
2050 }
2051 }
2052 # endif
2053 # if defined(HAVE_GETPWNAM)
2054 {
2055 char_u *user_env = mch_getenv((char_u *)"USER");
2056
2057 // The $USER environment variable may be a valid remote user name (NIS,
2058 // LDAP) not already listed by getpwent(), as getpwent() only lists
2059 // local user names. If $USER is not already listed, check whether it
2060 // is a valid remote user name using getpwnam() and if it is, add it to
2061 // the list of user names.
2062
2063 if (user_env != NULL && *user_env != NUL)
2064 {
2065 int i;
2066
2067 for (i = 0; i < ga_users.ga_len; i++)
2068 {
2069 char_u *local_user = ((char_u **)ga_users.ga_data)[i];
2070
2071 if (STRCMP(local_user, user_env) == 0)
2072 break;
2073 }
2074
2075 if (i == ga_users.ga_len)
2076 {
2077 struct passwd *pw = getpwnam((char *)user_env);
2078
2079 if (pw != NULL)
2080 add_user((char_u *)pw->pw_name, TRUE);
2081 }
2082 }
2083 }
2084 # endif
2085 }
2086
2087 /*
2088 * Function given to ExpandGeneric() to obtain an user names.
2089 */
2090 char_u*
get_users(expand_T * xp UNUSED,int idx)2091 get_users(expand_T *xp UNUSED, int idx)
2092 {
2093 init_users();
2094 if (idx < ga_users.ga_len)
2095 return ((char_u **)ga_users.ga_data)[idx];
2096 return NULL;
2097 }
2098
2099 /*
2100 * Check whether name matches a user name. Return:
2101 * 0 if name does not match any user name.
2102 * 1 if name partially matches the beginning of a user name.
2103 * 2 is name fully matches a user name.
2104 */
2105 int
match_user(char_u * name)2106 match_user(char_u *name)
2107 {
2108 int i;
2109 int n = (int)STRLEN(name);
2110 int result = 0;
2111
2112 init_users();
2113 for (i = 0; i < ga_users.ga_len; i++)
2114 {
2115 if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
2116 return 2; // full match
2117 if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
2118 result = 1; // partial match
2119 }
2120 return result;
2121 }
2122
2123 static void
prepare_to_exit(void)2124 prepare_to_exit(void)
2125 {
2126 #if defined(SIGHUP) && defined(SIG_IGN)
2127 // Ignore SIGHUP, because a dropped connection causes a read error, which
2128 // makes Vim exit and then handling SIGHUP causes various reentrance
2129 // problems.
2130 signal(SIGHUP, SIG_IGN);
2131 #endif
2132
2133 #ifdef FEAT_GUI
2134 if (gui.in_use)
2135 {
2136 gui.dying = TRUE;
2137 out_trash(); // trash any pending output
2138 }
2139 else
2140 #endif
2141 {
2142 windgoto((int)Rows - 1, 0);
2143
2144 /*
2145 * Switch terminal mode back now, so messages end up on the "normal"
2146 * screen (if there are two screens).
2147 */
2148 settmode(TMODE_COOK);
2149 stoptermcap();
2150 out_flush();
2151 }
2152 }
2153
2154 /*
2155 * Preserve files and exit.
2156 * When called IObuff must contain a message.
2157 * NOTE: This may be called from deathtrap() in a signal handler, avoid unsafe
2158 * functions, such as allocating memory.
2159 */
2160 void
preserve_exit(void)2161 preserve_exit(void)
2162 {
2163 buf_T *buf;
2164
2165 prepare_to_exit();
2166
2167 // Setting this will prevent free() calls. That avoids calling free()
2168 // recursively when free() was invoked with a bad pointer.
2169 really_exiting = TRUE;
2170
2171 out_str(IObuff);
2172 screen_start(); // don't know where cursor is now
2173 out_flush();
2174
2175 ml_close_notmod(); // close all not-modified buffers
2176
2177 FOR_ALL_BUFFERS(buf)
2178 {
2179 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
2180 {
2181 OUT_STR("Vim: preserving files...\r\n");
2182 screen_start(); // don't know where cursor is now
2183 out_flush();
2184 ml_sync_all(FALSE, FALSE); // preserve all swap files
2185 break;
2186 }
2187 }
2188
2189 ml_close_all(FALSE); // close all memfiles, without deleting
2190
2191 OUT_STR("Vim: Finished.\r\n");
2192
2193 getout(1);
2194 }
2195
2196 /*
2197 * Check for CTRL-C pressed, but only once in a while.
2198 * Should be used instead of ui_breakcheck() for functions that check for
2199 * each line in the file. Calling ui_breakcheck() each time takes too much
2200 * time, because it can be a system call.
2201 */
2202
2203 #ifndef BREAKCHECK_SKIP
2204 # define BREAKCHECK_SKIP 1000
2205 #endif
2206
2207 static int breakcheck_count = 0;
2208
2209 void
line_breakcheck(void)2210 line_breakcheck(void)
2211 {
2212 if (++breakcheck_count >= BREAKCHECK_SKIP)
2213 {
2214 breakcheck_count = 0;
2215 ui_breakcheck();
2216 }
2217 }
2218
2219 /*
2220 * Like line_breakcheck() but check 10 times less often.
2221 */
2222 void
fast_breakcheck(void)2223 fast_breakcheck(void)
2224 {
2225 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
2226 {
2227 breakcheck_count = 0;
2228 ui_breakcheck();
2229 }
2230 }
2231
2232 /*
2233 * Like line_breakcheck() but check 100 times less often.
2234 */
2235 void
veryfast_breakcheck(void)2236 veryfast_breakcheck(void)
2237 {
2238 if (++breakcheck_count >= BREAKCHECK_SKIP * 100)
2239 {
2240 breakcheck_count = 0;
2241 ui_breakcheck();
2242 }
2243 }
2244
2245 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) \
2246 || (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
2247 || defined(PROTO)
2248
2249 #ifndef SEEK_SET
2250 # define SEEK_SET 0
2251 #endif
2252 #ifndef SEEK_END
2253 # define SEEK_END 2
2254 #endif
2255
2256 /*
2257 * Get the stdout of an external command.
2258 * If "ret_len" is NULL replace NUL characters with NL. When "ret_len" is not
2259 * NULL store the length there.
2260 * Returns an allocated string, or NULL for error.
2261 */
2262 char_u *
get_cmd_output(char_u * cmd,char_u * infile,int flags,int * ret_len)2263 get_cmd_output(
2264 char_u *cmd,
2265 char_u *infile, // optional input file name
2266 int flags, // can be SHELL_SILENT
2267 int *ret_len)
2268 {
2269 char_u *tempname;
2270 char_u *command;
2271 char_u *buffer = NULL;
2272 int len;
2273 int i = 0;
2274 FILE *fd;
2275
2276 if (check_restricted() || check_secure())
2277 return NULL;
2278
2279 // get a name for the temp file
2280 if ((tempname = vim_tempname('o', FALSE)) == NULL)
2281 {
2282 emsg(_(e_notmp));
2283 return NULL;
2284 }
2285
2286 // Add the redirection stuff
2287 command = make_filter_cmd(cmd, infile, tempname);
2288 if (command == NULL)
2289 goto done;
2290
2291 /*
2292 * Call the shell to execute the command (errors are ignored).
2293 * Don't check timestamps here.
2294 */
2295 ++no_check_timestamps;
2296 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
2297 --no_check_timestamps;
2298
2299 vim_free(command);
2300
2301 /*
2302 * read the names from the file into memory
2303 */
2304 # ifdef VMS
2305 // created temporary file is not always readable as binary
2306 fd = mch_fopen((char *)tempname, "r");
2307 # else
2308 fd = mch_fopen((char *)tempname, READBIN);
2309 # endif
2310
2311 if (fd == NULL)
2312 {
2313 semsg(_(e_notopen), tempname);
2314 goto done;
2315 }
2316
2317 fseek(fd, 0L, SEEK_END);
2318 len = ftell(fd); // get size of temp file
2319 fseek(fd, 0L, SEEK_SET);
2320
2321 buffer = alloc(len + 1);
2322 if (buffer != NULL)
2323 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
2324 fclose(fd);
2325 mch_remove(tempname);
2326 if (buffer == NULL)
2327 goto done;
2328 #ifdef VMS
2329 len = i; // VMS doesn't give us what we asked for...
2330 #endif
2331 if (i != len)
2332 {
2333 semsg(_(e_notread), tempname);
2334 VIM_CLEAR(buffer);
2335 }
2336 else if (ret_len == NULL)
2337 {
2338 // Change NUL into SOH, otherwise the string is truncated.
2339 for (i = 0; i < len; ++i)
2340 if (buffer[i] == NUL)
2341 buffer[i] = 1;
2342
2343 buffer[len] = NUL; // make sure the buffer is terminated
2344 }
2345 else
2346 *ret_len = len;
2347
2348 done:
2349 vim_free(tempname);
2350 return buffer;
2351 }
2352
2353 # if defined(FEAT_EVAL) || defined(PROTO)
2354
2355 static void
get_cmd_output_as_rettv(typval_T * argvars,typval_T * rettv,int retlist)2356 get_cmd_output_as_rettv(
2357 typval_T *argvars,
2358 typval_T *rettv,
2359 int retlist)
2360 {
2361 char_u *res = NULL;
2362 char_u *p;
2363 char_u *infile = NULL;
2364 int err = FALSE;
2365 FILE *fd;
2366 list_T *list = NULL;
2367 int flags = SHELL_SILENT;
2368
2369 rettv->v_type = VAR_STRING;
2370 rettv->vval.v_string = NULL;
2371 if (check_restricted() || check_secure())
2372 goto errret;
2373
2374 if (in_vim9script()
2375 && (check_for_string_arg(argvars, 0) == FAIL
2376 || check_for_opt_string_or_number_or_list_arg(argvars, 1) == FAIL))
2377 return;
2378
2379 if (argvars[1].v_type != VAR_UNKNOWN)
2380 {
2381 /*
2382 * Write the text to a temp file, to be used for input of the shell
2383 * command.
2384 */
2385 if ((infile = vim_tempname('i', TRUE)) == NULL)
2386 {
2387 emsg(_(e_notmp));
2388 goto errret;
2389 }
2390
2391 fd = mch_fopen((char *)infile, WRITEBIN);
2392 if (fd == NULL)
2393 {
2394 semsg(_(e_notopen), infile);
2395 goto errret;
2396 }
2397 if (argvars[1].v_type == VAR_NUMBER)
2398 {
2399 linenr_T lnum;
2400 buf_T *buf;
2401
2402 buf = buflist_findnr(argvars[1].vval.v_number);
2403 if (buf == NULL)
2404 {
2405 semsg(_(e_nobufnr), argvars[1].vval.v_number);
2406 fclose(fd);
2407 goto errret;
2408 }
2409
2410 for (lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++)
2411 {
2412 for (p = ml_get_buf(buf, lnum, FALSE); *p != NUL; ++p)
2413 if (putc(*p == '\n' ? NUL : *p, fd) == EOF)
2414 {
2415 err = TRUE;
2416 break;
2417 }
2418 if (putc(NL, fd) == EOF)
2419 {
2420 err = TRUE;
2421 break;
2422 }
2423 }
2424 }
2425 else if (argvars[1].v_type == VAR_LIST)
2426 {
2427 if (write_list(fd, argvars[1].vval.v_list, TRUE) == FAIL)
2428 err = TRUE;
2429 }
2430 else
2431 {
2432 size_t len;
2433 char_u buf[NUMBUFLEN];
2434
2435 p = tv_get_string_buf_chk(&argvars[1], buf);
2436 if (p == NULL)
2437 {
2438 fclose(fd);
2439 goto errret; // type error; errmsg already given
2440 }
2441 len = STRLEN(p);
2442 if (len > 0 && fwrite(p, len, 1, fd) != 1)
2443 err = TRUE;
2444 }
2445 if (fclose(fd) != 0)
2446 err = TRUE;
2447 if (err)
2448 {
2449 emsg(_("E677: Error writing temp file"));
2450 goto errret;
2451 }
2452 }
2453
2454 // Omit SHELL_COOKED when invoked with ":silent". Avoids that the shell
2455 // echoes typeahead, that messes up the display.
2456 if (!msg_silent)
2457 flags += SHELL_COOKED;
2458
2459 if (retlist)
2460 {
2461 int len;
2462 listitem_T *li;
2463 char_u *s = NULL;
2464 char_u *start;
2465 char_u *end;
2466 int i;
2467
2468 res = get_cmd_output(tv_get_string(&argvars[0]), infile, flags, &len);
2469 if (res == NULL)
2470 goto errret;
2471
2472 list = list_alloc();
2473 if (list == NULL)
2474 goto errret;
2475
2476 for (i = 0; i < len; ++i)
2477 {
2478 start = res + i;
2479 while (i < len && res[i] != NL)
2480 ++i;
2481 end = res + i;
2482
2483 s = alloc(end - start + 1);
2484 if (s == NULL)
2485 goto errret;
2486
2487 for (p = s; start < end; ++p, ++start)
2488 *p = *start == NUL ? NL : *start;
2489 *p = NUL;
2490
2491 li = listitem_alloc();
2492 if (li == NULL)
2493 {
2494 vim_free(s);
2495 goto errret;
2496 }
2497 li->li_tv.v_type = VAR_STRING;
2498 li->li_tv.v_lock = 0;
2499 li->li_tv.vval.v_string = s;
2500 list_append(list, li);
2501 }
2502
2503 rettv_list_set(rettv, list);
2504 list = NULL;
2505 }
2506 else
2507 {
2508 res = get_cmd_output(tv_get_string(&argvars[0]), infile, flags, NULL);
2509 #ifdef USE_CRNL
2510 // translate <CR><NL> into <NL>
2511 if (res != NULL)
2512 {
2513 char_u *s, *d;
2514
2515 d = res;
2516 for (s = res; *s; ++s)
2517 {
2518 if (s[0] == CAR && s[1] == NL)
2519 ++s;
2520 *d++ = *s;
2521 }
2522 *d = NUL;
2523 }
2524 #endif
2525 rettv->vval.v_string = res;
2526 res = NULL;
2527 }
2528
2529 errret:
2530 if (infile != NULL)
2531 {
2532 mch_remove(infile);
2533 vim_free(infile);
2534 }
2535 if (res != NULL)
2536 vim_free(res);
2537 if (list != NULL)
2538 list_free(list);
2539 }
2540
2541 /*
2542 * "system()" function
2543 */
2544 void
f_system(typval_T * argvars,typval_T * rettv)2545 f_system(typval_T *argvars, typval_T *rettv)
2546 {
2547 get_cmd_output_as_rettv(argvars, rettv, FALSE);
2548 }
2549
2550 /*
2551 * "systemlist()" function
2552 */
2553 void
f_systemlist(typval_T * argvars,typval_T * rettv)2554 f_systemlist(typval_T *argvars, typval_T *rettv)
2555 {
2556 get_cmd_output_as_rettv(argvars, rettv, TRUE);
2557 }
2558 # endif // FEAT_EVAL
2559
2560 #endif
2561
2562 /*
2563 * Return TRUE when need to go to Insert mode because of 'insertmode'.
2564 * Don't do this when still processing a command or a mapping.
2565 * Don't do this when inside a ":normal" command.
2566 */
2567 int
goto_im(void)2568 goto_im(void)
2569 {
2570 return (p_im && stuff_empty() && typebuf_typed());
2571 }
2572
2573 /*
2574 * Returns the isolated name of the shell in allocated memory:
2575 * - Skip beyond any path. E.g., "/usr/bin/csh -f" -> "csh -f".
2576 * - Remove any argument. E.g., "csh -f" -> "csh".
2577 * But don't allow a space in the path, so that this works:
2578 * "/usr/bin/csh --rcfile ~/.cshrc"
2579 * But don't do that for Windows, it's common to have a space in the path.
2580 * Returns NULL when out of memory.
2581 */
2582 char_u *
get_isolated_shell_name(void)2583 get_isolated_shell_name(void)
2584 {
2585 char_u *p;
2586
2587 #ifdef MSWIN
2588 p = gettail(p_sh);
2589 p = vim_strnsave(p, skiptowhite(p) - p);
2590 #else
2591 p = skiptowhite(p_sh);
2592 if (*p == NUL)
2593 {
2594 // No white space, use the tail.
2595 p = vim_strsave(gettail(p_sh));
2596 }
2597 else
2598 {
2599 char_u *p1, *p2;
2600
2601 // Find the last path separator before the space.
2602 p1 = p_sh;
2603 for (p2 = p_sh; p2 < p; MB_PTR_ADV(p2))
2604 if (vim_ispathsep(*p2))
2605 p1 = p2 + 1;
2606 p = vim_strnsave(p1, p - p1);
2607 }
2608 #endif
2609 return p;
2610 }
2611
2612 /*
2613 * Check if the "://" of a URL is at the pointer, return URL_SLASH.
2614 * Also check for ":\\", which MS Internet Explorer accepts, return
2615 * URL_BACKSLASH.
2616 */
2617 int
path_is_url(char_u * p)2618 path_is_url(char_u *p)
2619 {
2620 if (STRNCMP(p, "://", (size_t)3) == 0)
2621 return URL_SLASH;
2622 else if (STRNCMP(p, ":\\\\", (size_t)3) == 0)
2623 return URL_BACKSLASH;
2624 return 0;
2625 }
2626
2627 /*
2628 * Check if "fname" starts with "name://" or "name:\\".
2629 * Return URL_SLASH for "name://", URL_BACKSLASH for "name:\\".
2630 * Return zero otherwise.
2631 */
2632 int
path_with_url(char_u * fname)2633 path_with_url(char_u *fname)
2634 {
2635 char_u *p;
2636
2637 // We accept alphabetic characters and a dash in scheme part.
2638 // RFC 3986 allows for more, but it increases the risk of matching
2639 // non-URL text.
2640
2641 // first character must be alpha
2642 if (!isalpha(*fname))
2643 return 0;
2644
2645 // check body: alpha or dash
2646 for (p = fname + 1; (isalpha(*p) || (*p == '-')); ++p)
2647 ;
2648
2649 // check last char is not a dash
2650 if (p[-1] == '-')
2651 return 0;
2652
2653 // "://" or ":\\" must follow
2654 return path_is_url(p);
2655 }
2656
2657 #if defined(FEAT_EVAL) || defined(PROTO)
2658 /*
2659 * Return the dictionary of v:event.
2660 * Save and clear the value in case it already has items.
2661 */
2662 dict_T *
get_v_event(save_v_event_T * sve)2663 get_v_event(save_v_event_T *sve)
2664 {
2665 dict_T *v_event = get_vim_var_dict(VV_EVENT);
2666
2667 if (v_event->dv_hashtab.ht_used > 0)
2668 {
2669 // recursive use of v:event, save, make empty and restore later
2670 sve->sve_did_save = TRUE;
2671 sve->sve_hashtab = v_event->dv_hashtab;
2672 hash_init(&v_event->dv_hashtab);
2673 }
2674 else
2675 sve->sve_did_save = FALSE;
2676 return v_event;
2677 }
2678
2679 void
restore_v_event(dict_T * v_event,save_v_event_T * sve)2680 restore_v_event(dict_T *v_event, save_v_event_T *sve)
2681 {
2682 dict_free_contents(v_event);
2683 if (sve->sve_did_save)
2684 v_event->dv_hashtab = sve->sve_hashtab;
2685 else
2686 hash_init(&v_event->dv_hashtab);
2687 }
2688 #endif
2689
2690 /*
2691 * Fires a ModeChanged autocmd
2692 */
2693 void
trigger_modechanged()2694 trigger_modechanged()
2695 {
2696 #ifdef FEAT_EVAL
2697 dict_T *v_event;
2698 typval_T rettv;
2699 typval_T tv[2];
2700 char_u *pat_pre;
2701 char_u *pat;
2702 save_v_event_T save_v_event;
2703
2704 if (!has_modechanged())
2705 return;
2706
2707 tv[0].v_type = VAR_NUMBER;
2708 tv[0].vval.v_number = 1; // get full mode
2709 tv[1].v_type = VAR_UNKNOWN;
2710 f_mode(tv, &rettv);
2711 if (STRCMP(rettv.vval.v_string, last_mode) == 0)
2712 {
2713 vim_free(rettv.vval.v_string);
2714 return;
2715 }
2716
2717 v_event = get_v_event(&save_v_event);
2718 (void)dict_add_string(v_event, "new_mode", rettv.vval.v_string);
2719 (void)dict_add_string(v_event, "old_mode", last_mode);
2720 dict_set_items_ro(v_event);
2721
2722 // concatenate modes in format "old_mode:new_mode"
2723 pat_pre = concat_str(last_mode, (char_u*)":");
2724 pat = concat_str(pat_pre, rettv.vval.v_string);
2725 vim_free(pat_pre);
2726
2727 apply_autocmds(EVENT_MODECHANGED, pat, NULL, FALSE, curbuf);
2728 STRCPY(last_mode, rettv.vval.v_string);
2729
2730 vim_free(pat);
2731 restore_v_event(v_event, &save_v_event);
2732 vim_free(rettv.vval.v_string);
2733 #endif
2734 }
2735