blob: bf6801f679695d3b9091e119a7e96060274bcc0d [file] [log] [blame]
Bram Moolenaar0a8fed62020-02-14 13:22:17 +01001/* 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)
21static char tz_cache[64];
22#endif
23
Bram Moolenaar00d253e2020-04-06 22:13:01 +020024#define FOR_ALL_TIMERS(t) \
25 for ((t) = first_timer; (t) != NULL; (t) = (t)->tr_next)
26
Bram Moolenaar0a8fed62020-02-14 13:22:17 +010027/*
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 *
38vim_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
66vim_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 *
83get_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
131f_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
142list2proftime(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
167f_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
215f_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
234f_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
253f_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
308f_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 vim_memset(&tmval, NUL, sizeof(tmval));
317 fmt = tv_get_string(&argvars[0]);
318 str = tv_get_string(&argvars[1]);
319
320 conv.vc_type = CONV_NONE;
321 enc = enc_locale();
322 convert_setup(&conv, p_enc, enc);
323 if (conv.vc_type != CONV_NONE)
324 fmt = string_convert(&conv, fmt, NULL);
325 if (fmt == NULL
326 || strptime((char *)str, (char *)fmt, &tmval) == NULL
327 || (rettv->vval.v_number = mktime(&tmval)) == -1)
328 rettv->vval.v_number = 0;
329
330 if (conv.vc_type != CONV_NONE)
331 vim_free(fmt);
332 convert_setup(&conv, NULL, NULL);
333 vim_free(enc);
334}
335# endif
336
337# if defined(FEAT_TIMERS) || defined(PROTO)
338static timer_T *first_timer = NULL;
339static long last_timer_id = 0;
340
341/*
342 * Return time left until "due". Negative if past "due".
343 */
344 long
345proftime_time_left(proftime_T *due, proftime_T *now)
346{
347# ifdef MSWIN
348 LARGE_INTEGER fr;
349
350 if (now->QuadPart > due->QuadPart)
351 return 0;
352 QueryPerformanceFrequency(&fr);
353 return (long)(((double)(due->QuadPart - now->QuadPart)
354 / (double)fr.QuadPart) * 1000);
355# else
356 if (now->tv_sec > due->tv_sec)
357 return 0;
358 return (due->tv_sec - now->tv_sec) * 1000
359 + (due->tv_usec - now->tv_usec) / 1000;
360# endif
361}
362
363/*
364 * Insert a timer in the list of timers.
365 */
366 static void
367insert_timer(timer_T *timer)
368{
369 timer->tr_next = first_timer;
370 timer->tr_prev = NULL;
371 if (first_timer != NULL)
372 first_timer->tr_prev = timer;
373 first_timer = timer;
374 did_add_timer = TRUE;
375}
376
377/*
378 * Take a timer out of the list of timers.
379 */
380 static void
381remove_timer(timer_T *timer)
382{
383 if (timer->tr_prev == NULL)
384 first_timer = timer->tr_next;
385 else
386 timer->tr_prev->tr_next = timer->tr_next;
387 if (timer->tr_next != NULL)
388 timer->tr_next->tr_prev = timer->tr_prev;
389}
390
391 static void
392free_timer(timer_T *timer)
393{
394 free_callback(&timer->tr_callback);
395 vim_free(timer);
396}
397
398/*
399 * Create a timer and return it. NULL if out of memory.
400 * Caller should set the callback.
401 */
402 timer_T *
403create_timer(long msec, int repeat)
404{
405 timer_T *timer = ALLOC_CLEAR_ONE(timer_T);
406 long prev_id = last_timer_id;
407
408 if (timer == NULL)
409 return NULL;
410 if (++last_timer_id <= prev_id)
411 // Overflow! Might cause duplicates...
412 last_timer_id = 0;
413 timer->tr_id = last_timer_id;
414 insert_timer(timer);
415 if (repeat != 0)
416 timer->tr_repeat = repeat - 1;
417 timer->tr_interval = msec;
418
419 profile_setlimit(msec, &timer->tr_due);
420 return timer;
421}
422
423/*
424 * Invoke the callback of "timer".
425 */
426 static void
427timer_callback(timer_T *timer)
428{
429 typval_T rettv;
430 typval_T argv[2];
431
432 argv[0].v_type = VAR_NUMBER;
433 argv[0].vval.v_number = (varnumber_T)timer->tr_id;
434 argv[1].v_type = VAR_UNKNOWN;
435
436 call_callback(&timer->tr_callback, -1, &rettv, 1, argv);
437 clear_tv(&rettv);
438}
439
440/*
441 * Call timers that are due.
442 * Return the time in msec until the next timer is due.
443 * Returns -1 if there are no pending timers.
444 */
445 long
446check_due_timer(void)
447{
448 timer_T *timer;
449 timer_T *timer_next;
450 long this_due;
451 long next_due = -1;
452 proftime_T now;
453 int did_one = FALSE;
454 int need_update_screen = FALSE;
455 long current_id = last_timer_id;
456
457 // Don't run any timers while exiting or dealing with an error.
458 if (exiting || aborting())
459 return next_due;
460
461 profile_start(&now);
462 for (timer = first_timer; timer != NULL && !got_int; timer = timer_next)
463 {
464 timer_next = timer->tr_next;
465
466 if (timer->tr_id == -1 || timer->tr_firing || timer->tr_paused)
467 continue;
468 this_due = proftime_time_left(&timer->tr_due, &now);
469 if (this_due <= 1)
470 {
471 // Save and restore a lot of flags, because the timer fires while
472 // waiting for a character, which might be halfway a command.
473 int save_timer_busy = timer_busy;
474 int save_vgetc_busy = vgetc_busy;
475 int save_did_emsg = did_emsg;
476 int save_called_emsg = called_emsg;
477 int save_must_redraw = must_redraw;
478 int save_trylevel = trylevel;
479 int save_did_throw = did_throw;
480 int save_ex_pressedreturn = get_pressedreturn();
481 int save_may_garbage_collect = may_garbage_collect;
482 except_T *save_current_exception = current_exception;
483 vimvars_save_T vvsave;
484
485 // Create a scope for running the timer callback, ignoring most of
486 // the current scope, such as being inside a try/catch.
487 timer_busy = timer_busy > 0 || vgetc_busy > 0;
488 vgetc_busy = 0;
489 called_emsg = 0;
490 did_emsg = FALSE;
491 did_uncaught_emsg = FALSE;
492 must_redraw = 0;
493 trylevel = 0;
494 did_throw = FALSE;
495 current_exception = NULL;
496 may_garbage_collect = FALSE;
497 save_vimvars(&vvsave);
498
499 timer->tr_firing = TRUE;
500 timer_callback(timer);
501 timer->tr_firing = FALSE;
502
503 timer_next = timer->tr_next;
504 did_one = TRUE;
505 timer_busy = save_timer_busy;
506 vgetc_busy = save_vgetc_busy;
507 if (did_uncaught_emsg)
508 ++timer->tr_emsg_count;
509 did_emsg = save_did_emsg;
510 called_emsg = save_called_emsg;
511 trylevel = save_trylevel;
512 did_throw = save_did_throw;
513 current_exception = save_current_exception;
514 restore_vimvars(&vvsave);
515 if (must_redraw != 0)
516 need_update_screen = TRUE;
517 must_redraw = must_redraw > save_must_redraw
518 ? must_redraw : save_must_redraw;
519 set_pressedreturn(save_ex_pressedreturn);
520 may_garbage_collect = save_may_garbage_collect;
521
522 // Only fire the timer again if it repeats and stop_timer() wasn't
523 // called while inside the callback (tr_id == -1).
524 if (timer->tr_repeat != 0 && timer->tr_id != -1
525 && timer->tr_emsg_count < 3)
526 {
527 profile_setlimit(timer->tr_interval, &timer->tr_due);
528 this_due = proftime_time_left(&timer->tr_due, &now);
529 if (this_due < 1)
530 this_due = 1;
531 if (timer->tr_repeat > 0)
532 --timer->tr_repeat;
533 }
534 else
535 {
536 this_due = -1;
537 remove_timer(timer);
538 free_timer(timer);
539 }
540 }
541 if (this_due > 0 && (next_due == -1 || next_due > this_due))
542 next_due = this_due;
543 }
544
545 if (did_one)
546 redraw_after_callback(need_update_screen);
547
548#ifdef FEAT_BEVAL_TERM
549 if (bevalexpr_due_set)
550 {
551 this_due = proftime_time_left(&bevalexpr_due, &now);
552 if (this_due <= 1)
553 {
554 bevalexpr_due_set = FALSE;
555 if (balloonEval == NULL)
556 {
557 balloonEval = ALLOC_CLEAR_ONE(BalloonEval);
558 balloonEvalForTerm = TRUE;
559 }
560 if (balloonEval != NULL)
561 {
562 general_beval_cb(balloonEval, 0);
563 setcursor();
564 out_flush();
565 }
566 }
567 else if (next_due == -1 || next_due > this_due)
568 next_due = this_due;
569 }
570#endif
571#ifdef FEAT_TERMINAL
572 // Some terminal windows may need their buffer updated.
573 next_due = term_check_timers(next_due, &now);
574#endif
575
576 return current_id != last_timer_id ? 1 : next_due;
577}
578
579/*
580 * Find a timer by ID. Returns NULL if not found;
581 */
582 static timer_T *
583find_timer(long id)
584{
585 timer_T *timer;
586
587 if (id >= 0)
588 {
Bram Moolenaar00d253e2020-04-06 22:13:01 +0200589 FOR_ALL_TIMERS(timer)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100590 if (timer->tr_id == id)
591 return timer;
592 }
593 return NULL;
594}
595
596
597/*
598 * Stop a timer and delete it.
599 */
600 void
601stop_timer(timer_T *timer)
602{
603 if (timer->tr_firing)
604 // Free the timer after the callback returns.
605 timer->tr_id = -1;
606 else
607 {
608 remove_timer(timer);
609 free_timer(timer);
610 }
611}
612
613 static void
614stop_all_timers(void)
615{
616 timer_T *timer;
617 timer_T *timer_next;
618
619 for (timer = first_timer; timer != NULL; timer = timer_next)
620 {
621 timer_next = timer->tr_next;
622 stop_timer(timer);
623 }
624}
625
626 static void
627add_timer_info(typval_T *rettv, timer_T *timer)
628{
629 list_T *list = rettv->vval.v_list;
630 dict_T *dict = dict_alloc();
631 dictitem_T *di;
632 long remaining;
633 proftime_T now;
634
635 if (dict == NULL)
636 return;
637 list_append_dict(list, dict);
638
639 dict_add_number(dict, "id", timer->tr_id);
640 dict_add_number(dict, "time", (long)timer->tr_interval);
641
642 profile_start(&now);
643 remaining = proftime_time_left(&timer->tr_due, &now);
644 dict_add_number(dict, "remaining", (long)remaining);
645
646 dict_add_number(dict, "repeat",
647 (long)(timer->tr_repeat < 0 ? -1 : timer->tr_repeat + 1));
648 dict_add_number(dict, "paused", (long)(timer->tr_paused));
649
650 di = dictitem_alloc((char_u *)"callback");
651 if (di != NULL)
652 {
653 if (dict_add(dict, di) == FAIL)
654 vim_free(di);
655 else
656 put_callback(&timer->tr_callback, &di->di_tv);
657 }
658}
659
660 static void
661add_timer_info_all(typval_T *rettv)
662{
663 timer_T *timer;
664
Bram Moolenaar00d253e2020-04-06 22:13:01 +0200665 FOR_ALL_TIMERS(timer)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100666 if (timer->tr_id != -1)
667 add_timer_info(rettv, timer);
668}
669
670/*
671 * Mark references in partials of timers.
672 */
673 int
674set_ref_in_timer(int copyID)
675{
676 int abort = FALSE;
677 timer_T *timer;
678 typval_T tv;
679
680 for (timer = first_timer; !abort && timer != NULL; timer = timer->tr_next)
681 {
682 if (timer->tr_callback.cb_partial != NULL)
683 {
684 tv.v_type = VAR_PARTIAL;
685 tv.vval.v_partial = timer->tr_callback.cb_partial;
686 }
687 else
688 {
689 tv.v_type = VAR_FUNC;
690 tv.vval.v_string = timer->tr_callback.cb_name;
691 }
692 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
693 }
694 return abort;
695}
696
697# if defined(EXITFREE) || defined(PROTO)
698 void
699timer_free_all()
700{
701 timer_T *timer;
702
703 while (first_timer != NULL)
704 {
705 timer = first_timer;
706 remove_timer(timer);
707 free_timer(timer);
708 }
709}
710# endif
711
712/*
713 * "timer_info([timer])" function
714 */
715 void
716f_timer_info(typval_T *argvars, typval_T *rettv)
717{
718 timer_T *timer = NULL;
719
720 if (rettv_list_alloc(rettv) != OK)
721 return;
722 if (argvars[0].v_type != VAR_UNKNOWN)
723 {
724 if (argvars[0].v_type != VAR_NUMBER)
725 emsg(_(e_number_exp));
726 else
727 {
728 timer = find_timer((int)tv_get_number(&argvars[0]));
729 if (timer != NULL)
730 add_timer_info(rettv, timer);
731 }
732 }
733 else
734 add_timer_info_all(rettv);
735}
736
737/*
738 * "timer_pause(timer, paused)" function
739 */
740 void
741f_timer_pause(typval_T *argvars, typval_T *rettv UNUSED)
742{
743 timer_T *timer = NULL;
744 int paused = (int)tv_get_number(&argvars[1]);
745
746 if (argvars[0].v_type != VAR_NUMBER)
747 emsg(_(e_number_exp));
748 else
749 {
750 timer = find_timer((int)tv_get_number(&argvars[0]));
751 if (timer != NULL)
752 timer->tr_paused = paused;
753 }
754}
755
756/*
757 * "timer_start(time, callback [, options])" function
758 */
759 void
760f_timer_start(typval_T *argvars, typval_T *rettv)
761{
762 long msec = (long)tv_get_number(&argvars[0]);
763 timer_T *timer;
764 int repeat = 0;
765 callback_T callback;
766 dict_T *dict;
767
768 rettv->vval.v_number = -1;
769 if (check_secure())
770 return;
771 if (argvars[2].v_type != VAR_UNKNOWN)
772 {
773 if (argvars[2].v_type != VAR_DICT
774 || (dict = argvars[2].vval.v_dict) == NULL)
775 {
776 semsg(_(e_invarg2), tv_get_string(&argvars[2]));
777 return;
778 }
779 if (dict_find(dict, (char_u *)"repeat", -1) != NULL)
780 repeat = dict_get_number(dict, (char_u *)"repeat");
781 }
782
783 callback = get_callback(&argvars[1]);
784 if (callback.cb_name == NULL)
785 return;
786
787 timer = create_timer(msec, repeat);
788 if (timer == NULL)
789 free_callback(&callback);
790 else
791 {
792 set_callback(&timer->tr_callback, &callback);
793 rettv->vval.v_number = (varnumber_T)timer->tr_id;
794 }
795}
796
797/*
798 * "timer_stop(timer)" function
799 */
800 void
801f_timer_stop(typval_T *argvars, typval_T *rettv UNUSED)
802{
803 timer_T *timer;
804
805 if (argvars[0].v_type != VAR_NUMBER)
806 {
807 emsg(_(e_number_exp));
808 return;
809 }
810 timer = find_timer((int)tv_get_number(&argvars[0]));
811 if (timer != NULL)
812 stop_timer(timer);
813}
814
815/*
816 * "timer_stopall()" function
817 */
818 void
819f_timer_stopall(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
820{
821 stop_all_timers();
822}
823
824# endif // FEAT_TIMERS
825
826# if defined(STARTUPTIME) || defined(PROTO)
827static struct timeval prev_timeval;
828
829# ifdef MSWIN
830/*
831 * Windows doesn't have gettimeofday(), although it does have struct timeval.
832 */
833 static int
834gettimeofday(struct timeval *tv, char *dummy UNUSED)
835{
836 long t = clock();
837 tv->tv_sec = t / CLOCKS_PER_SEC;
838 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
839 return 0;
840}
841# endif
842
843/*
844 * Save the previous time before doing something that could nest.
845 * set "*tv_rel" to the time elapsed so far.
846 */
847 void
848time_push(void *tv_rel, void *tv_start)
849{
850 *((struct timeval *)tv_rel) = prev_timeval;
851 gettimeofday(&prev_timeval, NULL);
852 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
853 - ((struct timeval *)tv_rel)->tv_usec;
854 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
855 - ((struct timeval *)tv_rel)->tv_sec;
856 if (((struct timeval *)tv_rel)->tv_usec < 0)
857 {
858 ((struct timeval *)tv_rel)->tv_usec += 1000000;
859 --((struct timeval *)tv_rel)->tv_sec;
860 }
861 *(struct timeval *)tv_start = prev_timeval;
862}
863
864/*
865 * Compute the previous time after doing something that could nest.
866 * Subtract "*tp" from prev_timeval;
867 * Note: The arguments are (void *) to avoid trouble with systems that don't
868 * have struct timeval.
869 */
870 void
871time_pop(
872 void *tp) // actually (struct timeval *)
873{
874 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
875 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
876 if (prev_timeval.tv_usec < 0)
877 {
878 prev_timeval.tv_usec += 1000000;
879 --prev_timeval.tv_sec;
880 }
881}
882
883 static void
884time_diff(struct timeval *then, struct timeval *now)
885{
886 long usec;
887 long msec;
888
889 usec = now->tv_usec - then->tv_usec;
890 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
891 usec = usec % 1000L;
892 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
893}
894
895 void
896time_msg(
897 char *mesg,
898 void *tv_start) // only for do_source: start time; actually
899 // (struct timeval *)
900{
901 static struct timeval start;
902 struct timeval now;
903
904 if (time_fd != NULL)
905 {
906 if (strstr(mesg, "STARTING") != NULL)
907 {
908 gettimeofday(&start, NULL);
909 prev_timeval = start;
910 fprintf(time_fd, "\n\ntimes in msec\n");
911 fprintf(time_fd, " clock self+sourced self: sourced script\n");
912 fprintf(time_fd, " clock elapsed: other lines\n\n");
913 }
914 gettimeofday(&now, NULL);
915 time_diff(&start, &now);
916 if (((struct timeval *)tv_start) != NULL)
917 {
918 fprintf(time_fd, " ");
919 time_diff(((struct timeval *)tv_start), &now);
920 }
921 fprintf(time_fd, " ");
922 time_diff(&prev_timeval, &now);
923 prev_timeval = now;
924 fprintf(time_fd, ": %s\n", mesg);
925 }
926}
927# endif // STARTUPTIME
928#endif // FEAT_EVAL
929
930#if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
931/*
932 * Read 8 bytes from "fd" and turn them into a time_T, MSB first.
933 * Returns -1 when encountering EOF.
934 */
935 time_T
936get8ctime(FILE *fd)
937{
938 int c;
939 time_T n = 0;
940 int i;
941
942 for (i = 0; i < 8; ++i)
943 {
944 c = getc(fd);
945 if (c == EOF) return -1;
946 n = (n << 8) + c;
947 }
948 return n;
949}
950
951#ifdef _MSC_VER
952# if (_MSC_VER <= 1200)
953// This line is required for VC6 without the service pack. Also see the
954// matching #pragma below.
955 # pragma optimize("", off)
956# endif
957#endif
958
959/*
960 * Write time_T to file "fd" in 8 bytes.
961 * Returns FAIL when the write failed.
962 */
963 int
964put_time(FILE *fd, time_T the_time)
965{
966 char_u buf[8];
967
968 time_to_bytes(the_time, buf);
969 return fwrite(buf, (size_t)8, (size_t)1, fd) == 1 ? OK : FAIL;
970}
971
972/*
973 * Write time_T to "buf[8]".
974 */
975 void
976time_to_bytes(time_T the_time, char_u *buf)
977{
978 int c;
979 int i;
980 int bi = 0;
981 time_T wtime = the_time;
982
983 // time_T can be up to 8 bytes in size, more than long_u, thus we
984 // can't use put_bytes() here.
985 // Another problem is that ">>" may do an arithmetic shift that keeps the
986 // sign. This happens for large values of wtime. A cast to long_u may
987 // truncate if time_T is 8 bytes. So only use a cast when it is 4 bytes,
988 // it's safe to assume that long_u is 4 bytes or more and when using 8
989 // bytes the top bit won't be set.
990 for (i = 7; i >= 0; --i)
991 {
992 if (i + 1 > (int)sizeof(time_T))
993 // ">>" doesn't work well when shifting more bits than avail
994 buf[bi++] = 0;
995 else
996 {
997#if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
998 c = (int)(wtime >> (i * 8));
999#else
1000 c = (int)((long_u)wtime >> (i * 8));
1001#endif
1002 buf[bi++] = c;
1003 }
1004 }
1005}
1006
1007#ifdef _MSC_VER
1008# if (_MSC_VER <= 1200)
1009 # pragma optimize("", on)
1010# endif
1011#endif
1012
1013#endif
1014
1015/*
1016 * Put timestamp "tt" in "buf[buflen]" in a nice format.
1017 */
1018 void
1019add_time(char_u *buf, size_t buflen, time_t tt)
1020{
1021#ifdef HAVE_STRFTIME
1022 struct tm tmval;
1023 struct tm *curtime;
1024
1025 if (vim_time() - tt >= 100)
1026 {
1027 curtime = vim_localtime(&tt, &tmval);
1028 if (vim_time() - tt < (60L * 60L * 12L))
1029 // within 12 hours
1030 (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
1031 else
1032 // longer ago
1033 (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime);
1034 }
1035 else
1036#endif
1037 {
1038 long seconds = (long)(vim_time() - tt);
1039
1040 vim_snprintf((char *)buf, buflen,
1041 NGETTEXT("%ld second ago", "%ld seconds ago", seconds),
1042 seconds);
1043 }
1044}