xref: /vim-8.2.3635/src/time.c (revision a0122dcd)
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  * time.c: functions related to time and timers
12  */
13 
14 #include "vim.h"
15 
16 /*
17  * Cache of the current timezone name as retrieved from TZ, or an empty string
18  * where unset, up to 64 octets long including trailing null byte.
19  */
20 #if defined(HAVE_LOCALTIME_R) && defined(HAVE_TZSET)
21 static char	tz_cache[64];
22 #endif
23 
24 #define FOR_ALL_TIMERS(t) \
25     for ((t) = first_timer; (t) != NULL; (t) = (t)->tr_next)
26 
27 /*
28  * Call either localtime(3) or localtime_r(3) from POSIX libc time.h, with the
29  * latter version preferred for reentrancy.
30  *
31  * If we use localtime_r(3) and we have tzset(3) available, check to see if the
32  * environment variable TZ has changed since the last run, and call tzset(3) to
33  * update the global timezone variables if it has.  This is because the POSIX
34  * standard doesn't require localtime_r(3) implementations to do that as it
35  * does with localtime(3), and we don't want to call tzset(3) every time.
36  */
37     static struct tm *
38 vim_localtime(
39     const time_t	*timep,		// timestamp for local representation
40     struct tm		*result UNUSED)	// pointer to caller return buffer
41 {
42 #ifdef HAVE_LOCALTIME_R
43 # ifdef HAVE_TZSET
44     char		*tz;		// pointer for TZ environment var
45 
46     tz = (char *)mch_getenv((char_u *)"TZ");
47     if (tz == NULL)
48 	tz = "";
49     if (STRNCMP(tz_cache, tz, sizeof(tz_cache) - 1) != 0)
50     {
51 	tzset();
52 	vim_strncpy((char_u *)tz_cache, (char_u *)tz, sizeof(tz_cache) - 1);
53     }
54 # endif	// HAVE_TZSET
55     return localtime_r(timep, result);
56 #else
57     return localtime(timep);
58 #endif	// HAVE_LOCALTIME_R
59 }
60 
61 /*
62  * Return the current time in seconds.  Calls time(), unless test_settime()
63  * was used.
64  */
65     time_T
66 vim_time(void)
67 {
68 # ifdef FEAT_EVAL
69     return time_for_testing == 0 ? time(NULL) : time_for_testing;
70 # else
71     return time(NULL);
72 # endif
73 }
74 
75 /*
76  * Replacement for ctime(), which is not safe to use.
77  * Requires strftime(), otherwise returns "(unknown)".
78  * If "thetime" is invalid returns "(invalid)".  Never returns NULL.
79  * When "add_newline" is TRUE add a newline like ctime() does.
80  * Uses a static buffer.
81  */
82     char *
83 get_ctime(time_t thetime, int add_newline)
84 {
85     static char buf[50];
86 #ifdef HAVE_STRFTIME
87     struct tm	tmval;
88     struct tm	*curtime;
89 
90     curtime = vim_localtime(&thetime, &tmval);
91     // MSVC returns NULL for an invalid value of seconds.
92     if (curtime == NULL)
93 	vim_strncpy((char_u *)buf, (char_u *)_("(Invalid)"), sizeof(buf) - 1);
94     else
95     {
96 	(void)strftime(buf, sizeof(buf) - 1, _("%a %b %d %H:%M:%S %Y"),
97 								    curtime);
98 # ifdef MSWIN
99 	if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
100 	{
101 	    char_u	*to_free = NULL;
102 	    int		len;
103 
104 	    acp_to_enc((char_u *)buf, (int)strlen(buf), &to_free, &len);
105 	    if (to_free != NULL)
106 	    {
107 		STRCPY(buf, to_free);
108 		vim_free(to_free);
109 	    }
110 	}
111 # endif
112     }
113 #else
114     STRCPY(buf, "(unknown)");
115 #endif
116     if (add_newline)
117 	STRCAT(buf, "\n");
118     return buf;
119 }
120 
121 #if defined(FEAT_EVAL) || defined(PROTO)
122 
123 #if defined(MACOS_X)
124 # include <time.h>	// for time_t
125 #endif
126 
127 /*
128  * "localtime()" function
129  */
130     void
131 f_localtime(typval_T *argvars UNUSED, typval_T *rettv)
132 {
133     rettv->vval.v_number = (varnumber_T)time(NULL);
134 }
135 
136 # if defined(FEAT_RELTIME)
137 /*
138  * Convert a List to proftime_T.
139  * Return FAIL when there is something wrong.
140  */
141     static int
142 list2proftime(typval_T *arg, proftime_T *tm)
143 {
144     long	n1, n2;
145     int	error = FALSE;
146 
147     if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
148 					     || arg->vval.v_list->lv_len != 2)
149 	return FAIL;
150     n1 = list_find_nr(arg->vval.v_list, 0L, &error);
151     n2 = list_find_nr(arg->vval.v_list, 1L, &error);
152 #  ifdef MSWIN
153     tm->HighPart = n1;
154     tm->LowPart = n2;
155 #  else
156     tm->tv_sec = n1;
157     tm->tv_usec = n2;
158 #  endif
159     return error ? FAIL : OK;
160 }
161 # endif // FEAT_RELTIME
162 
163 /*
164  * "reltime()" function
165  */
166     void
167 f_reltime(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
168 {
169 # ifdef FEAT_RELTIME
170     proftime_T	res;
171     proftime_T	start;
172 
173     if (argvars[0].v_type == VAR_UNKNOWN)
174     {
175 	// No arguments: get current time.
176 	profile_start(&res);
177     }
178     else if (argvars[1].v_type == VAR_UNKNOWN)
179     {
180 	if (list2proftime(&argvars[0], &res) == FAIL)
181 	    return;
182 	profile_end(&res);
183     }
184     else
185     {
186 	// Two arguments: compute the difference.
187 	if (list2proftime(&argvars[0], &start) == FAIL
188 		|| list2proftime(&argvars[1], &res) == FAIL)
189 	    return;
190 	profile_sub(&res, &start);
191     }
192 
193     if (rettv_list_alloc(rettv) == OK)
194     {
195 	long	n1, n2;
196 
197 #  ifdef MSWIN
198 	n1 = res.HighPart;
199 	n2 = res.LowPart;
200 #  else
201 	n1 = res.tv_sec;
202 	n2 = res.tv_usec;
203 #  endif
204 	list_append_number(rettv->vval.v_list, (varnumber_T)n1);
205 	list_append_number(rettv->vval.v_list, (varnumber_T)n2);
206     }
207 # endif
208 }
209 
210 # ifdef FEAT_FLOAT
211 /*
212  * "reltimefloat()" function
213  */
214     void
215 f_reltimefloat(typval_T *argvars UNUSED, typval_T *rettv)
216 {
217 #  ifdef FEAT_RELTIME
218     proftime_T	tm;
219 #  endif
220 
221     rettv->v_type = VAR_FLOAT;
222     rettv->vval.v_float = 0;
223 #  ifdef FEAT_RELTIME
224     if (list2proftime(&argvars[0], &tm) == OK)
225 	rettv->vval.v_float = profile_float(&tm);
226 #  endif
227 }
228 # endif
229 
230 /*
231  * "reltimestr()" function
232  */
233     void
234 f_reltimestr(typval_T *argvars UNUSED, typval_T *rettv)
235 {
236 # ifdef FEAT_RELTIME
237     proftime_T	tm;
238 # endif
239 
240     rettv->v_type = VAR_STRING;
241     rettv->vval.v_string = NULL;
242 # ifdef FEAT_RELTIME
243     if (list2proftime(&argvars[0], &tm) == OK)
244 	rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
245 # endif
246 }
247 
248 # if defined(HAVE_STRFTIME) || defined(PROTO)
249 /*
250  * "strftime({format}[, {time}])" function
251  */
252     void
253 f_strftime(typval_T *argvars, typval_T *rettv)
254 {
255     char_u	result_buf[256];
256     struct tm	tmval;
257     struct tm	*curtime;
258     time_t	seconds;
259     char_u	*p;
260 
261     rettv->v_type = VAR_STRING;
262 
263     p = tv_get_string(&argvars[0]);
264     if (argvars[1].v_type == VAR_UNKNOWN)
265 	seconds = time(NULL);
266     else
267 	seconds = (time_t)tv_get_number(&argvars[1]);
268     curtime = vim_localtime(&seconds, &tmval);
269     // MSVC returns NULL for an invalid value of seconds.
270     if (curtime == NULL)
271 	rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
272     else
273     {
274 	vimconv_T   conv;
275 	char_u	    *enc;
276 
277 	conv.vc_type = CONV_NONE;
278 	enc = enc_locale();
279 	convert_setup(&conv, p_enc, enc);
280 	if (conv.vc_type != CONV_NONE)
281 	    p = string_convert(&conv, p, NULL);
282 	if (p != NULL)
283 	    (void)strftime((char *)result_buf, sizeof(result_buf),
284 							  (char *)p, curtime);
285 	else
286 	    result_buf[0] = NUL;
287 
288 	if (conv.vc_type != CONV_NONE)
289 	    vim_free(p);
290 	convert_setup(&conv, enc, p_enc);
291 	if (conv.vc_type != CONV_NONE)
292 	    rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
293 	else
294 	    rettv->vval.v_string = vim_strsave(result_buf);
295 
296 	// Release conversion descriptors
297 	convert_setup(&conv, NULL, NULL);
298 	vim_free(enc);
299     }
300 }
301 # endif
302 
303 # if defined(HAVE_STRPTIME) || defined(PROTO)
304 /*
305  * "strptime({format}, {timestring})" function
306  */
307     void
308 f_strptime(typval_T *argvars, typval_T *rettv)
309 {
310     struct tm	tmval;
311     char_u	*fmt;
312     char_u	*str;
313     vimconv_T   conv;
314     char_u	*enc;
315 
316     CLEAR_FIELD(tmval);
317     tmval.tm_isdst = -1;
318     fmt = tv_get_string(&argvars[0]);
319     str = tv_get_string(&argvars[1]);
320 
321     conv.vc_type = CONV_NONE;
322     enc = enc_locale();
323     convert_setup(&conv, p_enc, enc);
324     if (conv.vc_type != CONV_NONE)
325 	fmt = string_convert(&conv, fmt, NULL);
326     if (fmt == NULL
327 	    || strptime((char *)str, (char *)fmt, &tmval) == NULL
328 	    || (rettv->vval.v_number = mktime(&tmval)) == -1)
329 	rettv->vval.v_number = 0;
330 
331     if (conv.vc_type != CONV_NONE)
332 	vim_free(fmt);
333     convert_setup(&conv, NULL, NULL);
334     vim_free(enc);
335 }
336 # endif
337 
338 # if defined(FEAT_TIMERS) || defined(PROTO)
339 static timer_T	*first_timer = NULL;
340 static long	last_timer_id = 0;
341 
342 /*
343  * Return time left until "due".  Negative if past "due".
344  */
345     long
346 proftime_time_left(proftime_T *due, proftime_T *now)
347 {
348 #  ifdef MSWIN
349     LARGE_INTEGER fr;
350 
351     if (now->QuadPart > due->QuadPart)
352 	return 0;
353     QueryPerformanceFrequency(&fr);
354     return (long)(((double)(due->QuadPart - now->QuadPart)
355 		   / (double)fr.QuadPart) * 1000);
356 #  else
357     if (now->tv_sec > due->tv_sec)
358 	return 0;
359     return (due->tv_sec - now->tv_sec) * 1000
360 	+ (due->tv_usec - now->tv_usec) / 1000;
361 #  endif
362 }
363 
364 /*
365  * Insert a timer in the list of timers.
366  */
367     static void
368 insert_timer(timer_T *timer)
369 {
370     timer->tr_next = first_timer;
371     timer->tr_prev = NULL;
372     if (first_timer != NULL)
373 	first_timer->tr_prev = timer;
374     first_timer = timer;
375     did_add_timer = TRUE;
376 }
377 
378 /*
379  * Take a timer out of the list of timers.
380  */
381     static void
382 remove_timer(timer_T *timer)
383 {
384     if (timer->tr_prev == NULL)
385 	first_timer = timer->tr_next;
386     else
387 	timer->tr_prev->tr_next = timer->tr_next;
388     if (timer->tr_next != NULL)
389 	timer->tr_next->tr_prev = timer->tr_prev;
390 }
391 
392     static void
393 free_timer(timer_T *timer)
394 {
395     free_callback(&timer->tr_callback);
396     vim_free(timer);
397 }
398 
399 /*
400  * Create a timer and return it.  NULL if out of memory.
401  * Caller should set the callback.
402  */
403     timer_T *
404 create_timer(long msec, int repeat)
405 {
406     timer_T	*timer = ALLOC_CLEAR_ONE(timer_T);
407     long	prev_id = last_timer_id;
408 
409     if (timer == NULL)
410 	return NULL;
411     if (++last_timer_id <= prev_id)
412 	// Overflow!  Might cause duplicates...
413 	last_timer_id = 0;
414     timer->tr_id = last_timer_id;
415     insert_timer(timer);
416     if (repeat != 0)
417 	timer->tr_repeat = repeat - 1;
418     timer->tr_interval = msec;
419 
420     profile_setlimit(msec, &timer->tr_due);
421     return timer;
422 }
423 
424 /*
425  * Invoke the callback of "timer".
426  */
427     static void
428 timer_callback(timer_T *timer)
429 {
430     typval_T	rettv;
431     typval_T	argv[2];
432 
433     argv[0].v_type = VAR_NUMBER;
434     argv[0].vval.v_number = (varnumber_T)timer->tr_id;
435     argv[1].v_type = VAR_UNKNOWN;
436 
437     call_callback(&timer->tr_callback, -1, &rettv, 1, argv);
438     clear_tv(&rettv);
439 }
440 
441 /*
442  * Call timers that are due.
443  * Return the time in msec until the next timer is due.
444  * Returns -1 if there are no pending timers.
445  */
446     long
447 check_due_timer(void)
448 {
449     timer_T	*timer;
450     timer_T	*timer_next;
451     long	this_due;
452     long	next_due = -1;
453     proftime_T	now;
454     int		did_one = FALSE;
455     int		need_update_screen = FALSE;
456     long	current_id = last_timer_id;
457 
458     // Don't run any timers while exiting or dealing with an error.
459     if (exiting || aborting())
460 	return next_due;
461 
462     profile_start(&now);
463     for (timer = first_timer; timer != NULL && !got_int; timer = timer_next)
464     {
465 	timer_next = timer->tr_next;
466 
467 	if (timer->tr_id == -1 || timer->tr_firing || timer->tr_paused)
468 	    continue;
469 	this_due = proftime_time_left(&timer->tr_due, &now);
470 	if (this_due <= 1)
471 	{
472 	    // Save and restore a lot of flags, because the timer fires while
473 	    // waiting for a character, which might be halfway a command.
474 	    int save_timer_busy = timer_busy;
475 	    int save_vgetc_busy = vgetc_busy;
476 	    int save_did_emsg = did_emsg;
477 	    int save_called_emsg = called_emsg;
478 	    int save_must_redraw = must_redraw;
479 	    int save_trylevel = trylevel;
480 	    int save_did_throw = did_throw;
481 	    int save_ex_pressedreturn = get_pressedreturn();
482 	    int save_may_garbage_collect = may_garbage_collect;
483 	    except_T *save_current_exception = current_exception;
484 	    vimvars_save_T vvsave;
485 
486 	    // Create a scope for running the timer callback, ignoring most of
487 	    // the current scope, such as being inside a try/catch.
488 	    timer_busy = timer_busy > 0 || vgetc_busy > 0;
489 	    vgetc_busy = 0;
490 	    called_emsg = 0;
491 	    did_emsg = FALSE;
492 	    did_uncaught_emsg = FALSE;
493 	    must_redraw = 0;
494 	    trylevel = 0;
495 	    did_throw = FALSE;
496 	    current_exception = NULL;
497 	    may_garbage_collect = FALSE;
498 	    save_vimvars(&vvsave);
499 
500 	    // Invoke the callback.
501 	    timer->tr_firing = TRUE;
502 	    timer_callback(timer);
503 	    timer->tr_firing = FALSE;
504 
505 	    // Restore stuff.
506 	    timer_next = timer->tr_next;
507 	    did_one = TRUE;
508 	    timer_busy = save_timer_busy;
509 	    vgetc_busy = save_vgetc_busy;
510 	    if (did_uncaught_emsg)
511 		++timer->tr_emsg_count;
512 	    did_emsg = save_did_emsg;
513 	    called_emsg = save_called_emsg;
514 	    trylevel = save_trylevel;
515 	    did_throw = save_did_throw;
516 	    current_exception = save_current_exception;
517 	    restore_vimvars(&vvsave);
518 	    if (must_redraw != 0)
519 		need_update_screen = TRUE;
520 	    must_redraw = must_redraw > save_must_redraw
521 					      ? must_redraw : save_must_redraw;
522 	    set_pressedreturn(save_ex_pressedreturn);
523 	    may_garbage_collect = save_may_garbage_collect;
524 
525 	    // Only fire the timer again if it repeats and stop_timer() wasn't
526 	    // called while inside the callback (tr_id == -1).
527 	    if (timer->tr_repeat != 0 && timer->tr_id != -1
528 		    && timer->tr_emsg_count < 3)
529 	    {
530 		profile_setlimit(timer->tr_interval, &timer->tr_due);
531 		this_due = proftime_time_left(&timer->tr_due, &now);
532 		if (this_due < 1)
533 		    this_due = 1;
534 		if (timer->tr_repeat > 0)
535 		    --timer->tr_repeat;
536 	    }
537 	    else
538 	    {
539 		this_due = -1;
540 		remove_timer(timer);
541 		free_timer(timer);
542 	    }
543 	}
544 	if (this_due > 0 && (next_due == -1 || next_due > this_due))
545 	    next_due = this_due;
546     }
547 
548     if (did_one)
549 	redraw_after_callback(need_update_screen);
550 
551 #ifdef FEAT_BEVAL_TERM
552     if (bevalexpr_due_set)
553     {
554 	this_due = proftime_time_left(&bevalexpr_due, &now);
555 	if (this_due <= 1)
556 	{
557 	    bevalexpr_due_set = FALSE;
558 	    if (balloonEval == NULL)
559 	    {
560 		balloonEval = ALLOC_CLEAR_ONE(BalloonEval);
561 		balloonEvalForTerm = TRUE;
562 	    }
563 	    if (balloonEval != NULL)
564 	    {
565 		general_beval_cb(balloonEval, 0);
566 		setcursor();
567 		out_flush();
568 	    }
569 	}
570 	else if (next_due == -1 || next_due > this_due)
571 	    next_due = this_due;
572     }
573 #endif
574 #ifdef FEAT_TERMINAL
575     // Some terminal windows may need their buffer updated.
576     next_due = term_check_timers(next_due, &now);
577 #endif
578 
579     return current_id != last_timer_id ? 1 : next_due;
580 }
581 
582 /*
583  * Find a timer by ID.  Returns NULL if not found;
584  */
585     static timer_T *
586 find_timer(long id)
587 {
588     timer_T *timer;
589 
590     if (id >= 0)
591     {
592 	FOR_ALL_TIMERS(timer)
593 	    if (timer->tr_id == id)
594 		return timer;
595     }
596     return NULL;
597 }
598 
599 
600 /*
601  * Stop a timer and delete it.
602  */
603     void
604 stop_timer(timer_T *timer)
605 {
606     if (timer->tr_firing)
607 	// Free the timer after the callback returns.
608 	timer->tr_id = -1;
609     else
610     {
611 	remove_timer(timer);
612 	free_timer(timer);
613     }
614 }
615 
616     static void
617 stop_all_timers(void)
618 {
619     timer_T *timer;
620     timer_T *timer_next;
621 
622     for (timer = first_timer; timer != NULL; timer = timer_next)
623     {
624 	timer_next = timer->tr_next;
625 	stop_timer(timer);
626     }
627 }
628 
629     static void
630 add_timer_info(typval_T *rettv, timer_T *timer)
631 {
632     list_T	*list = rettv->vval.v_list;
633     dict_T	*dict = dict_alloc();
634     dictitem_T	*di;
635     long	remaining;
636     proftime_T	now;
637 
638     if (dict == NULL)
639 	return;
640     list_append_dict(list, dict);
641 
642     dict_add_number(dict, "id", timer->tr_id);
643     dict_add_number(dict, "time", (long)timer->tr_interval);
644 
645     profile_start(&now);
646     remaining = proftime_time_left(&timer->tr_due, &now);
647     dict_add_number(dict, "remaining", (long)remaining);
648 
649     dict_add_number(dict, "repeat",
650 		    (long)(timer->tr_repeat < 0 ? -1 : timer->tr_repeat + 1));
651     dict_add_number(dict, "paused", (long)(timer->tr_paused));
652 
653     di = dictitem_alloc((char_u *)"callback");
654     if (di != NULL)
655     {
656 	if (dict_add(dict, di) == FAIL)
657 	    vim_free(di);
658 	else
659 	    put_callback(&timer->tr_callback, &di->di_tv);
660     }
661 }
662 
663     static void
664 add_timer_info_all(typval_T *rettv)
665 {
666     timer_T *timer;
667 
668     FOR_ALL_TIMERS(timer)
669 	if (timer->tr_id != -1)
670 	    add_timer_info(rettv, timer);
671 }
672 
673 /*
674  * Mark references in partials of timers.
675  */
676     int
677 set_ref_in_timer(int copyID)
678 {
679     int		abort = FALSE;
680     timer_T	*timer;
681     typval_T	tv;
682 
683     for (timer = first_timer; !abort && timer != NULL; timer = timer->tr_next)
684     {
685 	if (timer->tr_callback.cb_partial != NULL)
686 	{
687 	    tv.v_type = VAR_PARTIAL;
688 	    tv.vval.v_partial = timer->tr_callback.cb_partial;
689 	}
690 	else
691 	{
692 	    tv.v_type = VAR_FUNC;
693 	    tv.vval.v_string = timer->tr_callback.cb_name;
694 	}
695 	abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
696     }
697     return abort;
698 }
699 
700 # if defined(EXITFREE) || defined(PROTO)
701     void
702 timer_free_all()
703 {
704     timer_T *timer;
705 
706     while (first_timer != NULL)
707     {
708 	timer = first_timer;
709 	remove_timer(timer);
710 	free_timer(timer);
711     }
712 }
713 # endif
714 
715 /*
716  * "timer_info([timer])" function
717  */
718     void
719 f_timer_info(typval_T *argvars, typval_T *rettv)
720 {
721     timer_T *timer = NULL;
722 
723     if (rettv_list_alloc(rettv) != OK)
724 	return;
725     if (argvars[0].v_type != VAR_UNKNOWN)
726     {
727 	if (argvars[0].v_type != VAR_NUMBER)
728 	    emsg(_(e_number_exp));
729 	else
730 	{
731 	    timer = find_timer((int)tv_get_number(&argvars[0]));
732 	    if (timer != NULL)
733 		add_timer_info(rettv, timer);
734 	}
735     }
736     else
737 	add_timer_info_all(rettv);
738 }
739 
740 /*
741  * "timer_pause(timer, paused)" function
742  */
743     void
744 f_timer_pause(typval_T *argvars, typval_T *rettv UNUSED)
745 {
746     timer_T	*timer = NULL;
747     int		paused = (int)tv_get_bool(&argvars[1]);
748 
749     if (argvars[0].v_type != VAR_NUMBER)
750 	emsg(_(e_number_exp));
751     else
752     {
753 	timer = find_timer((int)tv_get_number(&argvars[0]));
754 	if (timer != NULL)
755 	    timer->tr_paused = paused;
756     }
757 }
758 
759 /*
760  * "timer_start(time, callback [, options])" function
761  */
762     void
763 f_timer_start(typval_T *argvars, typval_T *rettv)
764 {
765     long	msec = (long)tv_get_number(&argvars[0]);
766     timer_T	*timer;
767     int		repeat = 0;
768     callback_T	callback;
769     dict_T	*dict;
770 
771     rettv->vval.v_number = -1;
772     if (check_secure())
773 	return;
774     if (argvars[2].v_type != VAR_UNKNOWN)
775     {
776 	if (argvars[2].v_type != VAR_DICT
777 				   || (dict = argvars[2].vval.v_dict) == NULL)
778 	{
779 	    semsg(_(e_invarg2), tv_get_string(&argvars[2]));
780 	    return;
781 	}
782 	if (dict_find(dict, (char_u *)"repeat", -1) != NULL)
783 	    repeat = dict_get_number(dict, (char_u *)"repeat");
784     }
785 
786     callback = get_callback(&argvars[1]);
787     if (callback.cb_name == NULL)
788 	return;
789 
790     timer = create_timer(msec, repeat);
791     if (timer == NULL)
792 	free_callback(&callback);
793     else
794     {
795 	set_callback(&timer->tr_callback, &callback);
796 	rettv->vval.v_number = (varnumber_T)timer->tr_id;
797     }
798 }
799 
800 /*
801  * "timer_stop(timer)" function
802  */
803     void
804 f_timer_stop(typval_T *argvars, typval_T *rettv UNUSED)
805 {
806     timer_T *timer;
807 
808     if (argvars[0].v_type != VAR_NUMBER)
809     {
810 	emsg(_(e_number_exp));
811 	return;
812     }
813     timer = find_timer((int)tv_get_number(&argvars[0]));
814     if (timer != NULL)
815 	stop_timer(timer);
816 }
817 
818 /*
819  * "timer_stopall()" function
820  */
821     void
822 f_timer_stopall(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
823 {
824     stop_all_timers();
825 }
826 
827 # endif // FEAT_TIMERS
828 
829 # if defined(STARTUPTIME) || defined(PROTO)
830 static struct timeval	prev_timeval;
831 
832 #  ifdef MSWIN
833 /*
834  * Windows doesn't have gettimeofday(), although it does have struct timeval.
835  */
836     static int
837 gettimeofday(struct timeval *tv, char *dummy UNUSED)
838 {
839     long t = clock();
840     tv->tv_sec = t / CLOCKS_PER_SEC;
841     tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
842     return 0;
843 }
844 #  endif
845 
846 /*
847  * Save the previous time before doing something that could nest.
848  * set "*tv_rel" to the time elapsed so far.
849  */
850     void
851 time_push(void *tv_rel, void *tv_start)
852 {
853     *((struct timeval *)tv_rel) = prev_timeval;
854     gettimeofday(&prev_timeval, NULL);
855     ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
856 					- ((struct timeval *)tv_rel)->tv_usec;
857     ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
858 					 - ((struct timeval *)tv_rel)->tv_sec;
859     if (((struct timeval *)tv_rel)->tv_usec < 0)
860     {
861 	((struct timeval *)tv_rel)->tv_usec += 1000000;
862 	--((struct timeval *)tv_rel)->tv_sec;
863     }
864     *(struct timeval *)tv_start = prev_timeval;
865 }
866 
867 /*
868  * Compute the previous time after doing something that could nest.
869  * Subtract "*tp" from prev_timeval;
870  * Note: The arguments are (void *) to avoid trouble with systems that don't
871  * have struct timeval.
872  */
873     void
874 time_pop(
875     void	*tp)	// actually (struct timeval *)
876 {
877     prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
878     prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
879     if (prev_timeval.tv_usec < 0)
880     {
881 	prev_timeval.tv_usec += 1000000;
882 	--prev_timeval.tv_sec;
883     }
884 }
885 
886     static void
887 time_diff(struct timeval *then, struct timeval *now)
888 {
889     long	usec;
890     long	msec;
891 
892     usec = now->tv_usec - then->tv_usec;
893     msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
894     usec = usec % 1000L;
895     fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
896 }
897 
898     void
899 time_msg(
900     char	*mesg,
901     void	*tv_start)  // only for do_source: start time; actually
902 			    // (struct timeval *)
903 {
904     static struct timeval	start;
905     struct timeval		now;
906 
907     if (time_fd != NULL)
908     {
909 	if (strstr(mesg, "STARTING") != NULL)
910 	{
911 	    gettimeofday(&start, NULL);
912 	    prev_timeval = start;
913 	    fprintf(time_fd, "\n\ntimes in msec\n");
914 	    fprintf(time_fd, " clock   self+sourced   self:  sourced script\n");
915 	    fprintf(time_fd, " clock   elapsed:              other lines\n\n");
916 	}
917 	gettimeofday(&now, NULL);
918 	time_diff(&start, &now);
919 	if (((struct timeval *)tv_start) != NULL)
920 	{
921 	    fprintf(time_fd, "  ");
922 	    time_diff(((struct timeval *)tv_start), &now);
923 	}
924 	fprintf(time_fd, "  ");
925 	time_diff(&prev_timeval, &now);
926 	prev_timeval = now;
927 	fprintf(time_fd, ": %s\n", mesg);
928     }
929 }
930 # endif	// STARTUPTIME
931 #endif // FEAT_EVAL
932 
933 #if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
934 /*
935  * Read 8 bytes from "fd" and turn them into a time_T, MSB first.
936  * Returns -1 when encountering EOF.
937  */
938     time_T
939 get8ctime(FILE *fd)
940 {
941     int		c;
942     time_T	n = 0;
943     int		i;
944 
945     for (i = 0; i < 8; ++i)
946     {
947 	c = getc(fd);
948 	if (c == EOF) return -1;
949 	n = (n << 8) + c;
950     }
951     return n;
952 }
953 
954 #ifdef _MSC_VER
955 # if (_MSC_VER <= 1200)
956 // This line is required for VC6 without the service pack.  Also see the
957 // matching #pragma below.
958  #  pragma optimize("", off)
959 # endif
960 #endif
961 
962 /*
963  * Write time_T to file "fd" in 8 bytes.
964  * Returns FAIL when the write failed.
965  */
966     int
967 put_time(FILE *fd, time_T the_time)
968 {
969     char_u	buf[8];
970 
971     time_to_bytes(the_time, buf);
972     return fwrite(buf, (size_t)8, (size_t)1, fd) == 1 ? OK : FAIL;
973 }
974 
975 /*
976  * Write time_T to "buf[8]".
977  */
978     void
979 time_to_bytes(time_T the_time, char_u *buf)
980 {
981     int		c;
982     int		i;
983     int		bi = 0;
984     time_T	wtime = the_time;
985 
986     // time_T can be up to 8 bytes in size, more than long_u, thus we
987     // can't use put_bytes() here.
988     // Another problem is that ">>" may do an arithmetic shift that keeps the
989     // sign.  This happens for large values of wtime.  A cast to long_u may
990     // truncate if time_T is 8 bytes.  So only use a cast when it is 4 bytes,
991     // it's safe to assume that long_u is 4 bytes or more and when using 8
992     // bytes the top bit won't be set.
993     for (i = 7; i >= 0; --i)
994     {
995 	if (i + 1 > (int)sizeof(time_T))
996 	    // ">>" doesn't work well when shifting more bits than avail
997 	    buf[bi++] = 0;
998 	else
999 	{
1000 #if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
1001 	    c = (int)(wtime >> (i * 8));
1002 #else
1003 	    c = (int)((long_u)wtime >> (i * 8));
1004 #endif
1005 	    buf[bi++] = c;
1006 	}
1007     }
1008 }
1009 
1010 #ifdef _MSC_VER
1011 # if (_MSC_VER <= 1200)
1012  #  pragma optimize("", on)
1013 # endif
1014 #endif
1015 
1016 #endif
1017 
1018 /*
1019  * Put timestamp "tt" in "buf[buflen]" in a nice format.
1020  */
1021     void
1022 add_time(char_u *buf, size_t buflen, time_t tt)
1023 {
1024 #ifdef HAVE_STRFTIME
1025     struct tm	tmval;
1026     struct tm	*curtime;
1027 
1028     if (vim_time() - tt >= 100)
1029     {
1030 	curtime = vim_localtime(&tt, &tmval);
1031 	if (vim_time() - tt < (60L * 60L * 12L))
1032 	    // within 12 hours
1033 	    (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
1034 	else
1035 	    // longer ago
1036 	    (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime);
1037     }
1038     else
1039 #endif
1040     {
1041 	long seconds = (long)(vim_time() - tt);
1042 
1043 	vim_snprintf((char *)buf, buflen,
1044 		NGETTEXT("%ld second ago", "%ld seconds ago", seconds),
1045 		seconds);
1046     }
1047 }
1048