blob: 796fc58c96ff3d03c08f1f48fff1cc141d3c8170 [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;
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200172 long n1, n2;
173
174 if (rettv_list_alloc(rettv) != OK)
175 return;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100176
177 if (argvars[0].v_type == VAR_UNKNOWN)
178 {
179 // No arguments: get current time.
180 profile_start(&res);
181 }
182 else if (argvars[1].v_type == VAR_UNKNOWN)
183 {
184 if (list2proftime(&argvars[0], &res) == FAIL)
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200185 {
186 if (in_vim9script())
187 emsg(_(e_invarg));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100188 return;
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200189 }
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100190 profile_end(&res);
191 }
192 else
193 {
194 // Two arguments: compute the difference.
195 if (list2proftime(&argvars[0], &start) == FAIL
196 || list2proftime(&argvars[1], &res) == FAIL)
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200197 {
198 if (in_vim9script())
199 emsg(_(e_invarg));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100200 return;
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200201 }
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100202 profile_sub(&res, &start);
203 }
204
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100205# ifdef MSWIN
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200206 n1 = res.HighPart;
207 n2 = res.LowPart;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100208# else
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200209 n1 = res.tv_sec;
210 n2 = res.tv_usec;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100211# endif
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200212 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
213 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100214# endif
215}
216
217# ifdef FEAT_FLOAT
218/*
219 * "reltimefloat()" function
220 */
221 void
222f_reltimefloat(typval_T *argvars UNUSED, typval_T *rettv)
223{
224# ifdef FEAT_RELTIME
225 proftime_T tm;
226# endif
227
228 rettv->v_type = VAR_FLOAT;
229 rettv->vval.v_float = 0;
230# ifdef FEAT_RELTIME
231 if (list2proftime(&argvars[0], &tm) == OK)
232 rettv->vval.v_float = profile_float(&tm);
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200233 else if (in_vim9script())
234 emsg(_(e_invarg));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100235# endif
236}
237# endif
238
239/*
240 * "reltimestr()" function
241 */
242 void
243f_reltimestr(typval_T *argvars UNUSED, typval_T *rettv)
244{
245# ifdef FEAT_RELTIME
246 proftime_T tm;
247# endif
248
249 rettv->v_type = VAR_STRING;
250 rettv->vval.v_string = NULL;
251# ifdef FEAT_RELTIME
252 if (list2proftime(&argvars[0], &tm) == OK)
253 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200254 else if (in_vim9script())
255 emsg(_(e_invarg));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100256# endif
257}
258
259# if defined(HAVE_STRFTIME) || defined(PROTO)
260/*
261 * "strftime({format}[, {time}])" function
262 */
263 void
264f_strftime(typval_T *argvars, typval_T *rettv)
265{
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100266 struct tm tmval;
267 struct tm *curtime;
268 time_t seconds;
269 char_u *p;
270
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200271 if (in_vim9script()
272 && (check_for_string_arg(argvars, 0) == FAIL
273 || (argvars[1].v_type != VAR_UNKNOWN
274 && check_for_number_arg(argvars, 1) == FAIL)))
275 return;
276
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100277 rettv->v_type = VAR_STRING;
278
279 p = tv_get_string(&argvars[0]);
280 if (argvars[1].v_type == VAR_UNKNOWN)
281 seconds = time(NULL);
282 else
283 seconds = (time_t)tv_get_number(&argvars[1]);
284 curtime = vim_localtime(&seconds, &tmval);
285 // MSVC returns NULL for an invalid value of seconds.
286 if (curtime == NULL)
287 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
288 else
289 {
K.Takata2c4a1d02021-05-28 15:49:34 +0200290# ifdef MSWIN
291 WCHAR result_buf[256];
292 WCHAR *wp;
293
294 wp = enc_to_utf16(p, NULL);
295 if (wp != NULL)
K.Takataeeec2542021-06-02 13:28:16 +0200296 (void)wcsftime(result_buf, ARRAY_LENGTH(result_buf), wp, curtime);
K.Takata2c4a1d02021-05-28 15:49:34 +0200297 else
298 result_buf[0] = NUL;
299 rettv->vval.v_string = utf16_to_enc(result_buf, NULL);
300 vim_free(wp);
301# else
302 char_u result_buf[256];
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100303 vimconv_T conv;
304 char_u *enc;
305
306 conv.vc_type = CONV_NONE;
307 enc = enc_locale();
308 convert_setup(&conv, p_enc, enc);
309 if (conv.vc_type != CONV_NONE)
310 p = string_convert(&conv, p, NULL);
311 if (p != NULL)
312 (void)strftime((char *)result_buf, sizeof(result_buf),
313 (char *)p, curtime);
314 else
315 result_buf[0] = NUL;
316
317 if (conv.vc_type != CONV_NONE)
318 vim_free(p);
319 convert_setup(&conv, enc, p_enc);
320 if (conv.vc_type != CONV_NONE)
321 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
322 else
323 rettv->vval.v_string = vim_strsave(result_buf);
324
325 // Release conversion descriptors
326 convert_setup(&conv, NULL, NULL);
327 vim_free(enc);
K.Takata2c4a1d02021-05-28 15:49:34 +0200328# endif
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100329 }
330}
331# endif
332
333# if defined(HAVE_STRPTIME) || defined(PROTO)
334/*
335 * "strptime({format}, {timestring})" function
336 */
337 void
338f_strptime(typval_T *argvars, typval_T *rettv)
339{
340 struct tm tmval;
341 char_u *fmt;
342 char_u *str;
343 vimconv_T conv;
344 char_u *enc;
345
Bram Moolenaara80faa82020-04-12 19:37:17 +0200346 CLEAR_FIELD(tmval);
Bram Moolenaarea1233f2020-06-10 16:54:13 +0200347 tmval.tm_isdst = -1;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100348 fmt = tv_get_string(&argvars[0]);
349 str = tv_get_string(&argvars[1]);
350
351 conv.vc_type = CONV_NONE;
352 enc = enc_locale();
353 convert_setup(&conv, p_enc, enc);
354 if (conv.vc_type != CONV_NONE)
355 fmt = string_convert(&conv, fmt, NULL);
356 if (fmt == NULL
357 || strptime((char *)str, (char *)fmt, &tmval) == NULL
358 || (rettv->vval.v_number = mktime(&tmval)) == -1)
359 rettv->vval.v_number = 0;
360
361 if (conv.vc_type != CONV_NONE)
362 vim_free(fmt);
363 convert_setup(&conv, NULL, NULL);
364 vim_free(enc);
365}
366# endif
367
368# if defined(FEAT_TIMERS) || defined(PROTO)
369static timer_T *first_timer = NULL;
370static long last_timer_id = 0;
371
372/*
373 * Return time left until "due". Negative if past "due".
374 */
375 long
376proftime_time_left(proftime_T *due, proftime_T *now)
377{
378# ifdef MSWIN
379 LARGE_INTEGER fr;
380
381 if (now->QuadPart > due->QuadPart)
382 return 0;
383 QueryPerformanceFrequency(&fr);
384 return (long)(((double)(due->QuadPart - now->QuadPart)
385 / (double)fr.QuadPart) * 1000);
386# else
387 if (now->tv_sec > due->tv_sec)
388 return 0;
389 return (due->tv_sec - now->tv_sec) * 1000
390 + (due->tv_usec - now->tv_usec) / 1000;
391# endif
392}
393
394/*
395 * Insert a timer in the list of timers.
396 */
397 static void
398insert_timer(timer_T *timer)
399{
400 timer->tr_next = first_timer;
401 timer->tr_prev = NULL;
402 if (first_timer != NULL)
403 first_timer->tr_prev = timer;
404 first_timer = timer;
405 did_add_timer = TRUE;
406}
407
408/*
409 * Take a timer out of the list of timers.
410 */
411 static void
412remove_timer(timer_T *timer)
413{
414 if (timer->tr_prev == NULL)
415 first_timer = timer->tr_next;
416 else
417 timer->tr_prev->tr_next = timer->tr_next;
418 if (timer->tr_next != NULL)
419 timer->tr_next->tr_prev = timer->tr_prev;
420}
421
422 static void
423free_timer(timer_T *timer)
424{
425 free_callback(&timer->tr_callback);
426 vim_free(timer);
427}
428
429/*
430 * Create a timer and return it. NULL if out of memory.
431 * Caller should set the callback.
432 */
433 timer_T *
434create_timer(long msec, int repeat)
435{
436 timer_T *timer = ALLOC_CLEAR_ONE(timer_T);
437 long prev_id = last_timer_id;
438
439 if (timer == NULL)
440 return NULL;
441 if (++last_timer_id <= prev_id)
442 // Overflow! Might cause duplicates...
443 last_timer_id = 0;
444 timer->tr_id = last_timer_id;
445 insert_timer(timer);
446 if (repeat != 0)
447 timer->tr_repeat = repeat - 1;
448 timer->tr_interval = msec;
449
450 profile_setlimit(msec, &timer->tr_due);
451 return timer;
452}
453
454/*
455 * Invoke the callback of "timer".
456 */
457 static void
458timer_callback(timer_T *timer)
459{
460 typval_T rettv;
461 typval_T argv[2];
462
463 argv[0].v_type = VAR_NUMBER;
464 argv[0].vval.v_number = (varnumber_T)timer->tr_id;
465 argv[1].v_type = VAR_UNKNOWN;
466
467 call_callback(&timer->tr_callback, -1, &rettv, 1, argv);
468 clear_tv(&rettv);
469}
470
471/*
472 * Call timers that are due.
473 * Return the time in msec until the next timer is due.
474 * Returns -1 if there are no pending timers.
475 */
476 long
477check_due_timer(void)
478{
479 timer_T *timer;
480 timer_T *timer_next;
481 long this_due;
482 long next_due = -1;
483 proftime_T now;
484 int did_one = FALSE;
485 int need_update_screen = FALSE;
486 long current_id = last_timer_id;
487
488 // Don't run any timers while exiting or dealing with an error.
489 if (exiting || aborting())
490 return next_due;
491
492 profile_start(&now);
493 for (timer = first_timer; timer != NULL && !got_int; timer = timer_next)
494 {
495 timer_next = timer->tr_next;
496
497 if (timer->tr_id == -1 || timer->tr_firing || timer->tr_paused)
498 continue;
499 this_due = proftime_time_left(&timer->tr_due, &now);
500 if (this_due <= 1)
501 {
502 // Save and restore a lot of flags, because the timer fires while
503 // waiting for a character, which might be halfway a command.
504 int save_timer_busy = timer_busy;
505 int save_vgetc_busy = vgetc_busy;
506 int save_did_emsg = did_emsg;
507 int save_called_emsg = called_emsg;
508 int save_must_redraw = must_redraw;
509 int save_trylevel = trylevel;
510 int save_did_throw = did_throw;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100511 int save_need_rethrow = need_rethrow;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100512 int save_ex_pressedreturn = get_pressedreturn();
513 int save_may_garbage_collect = may_garbage_collect;
514 except_T *save_current_exception = current_exception;
515 vimvars_save_T vvsave;
516
517 // Create a scope for running the timer callback, ignoring most of
518 // the current scope, such as being inside a try/catch.
519 timer_busy = timer_busy > 0 || vgetc_busy > 0;
520 vgetc_busy = 0;
521 called_emsg = 0;
522 did_emsg = FALSE;
523 did_uncaught_emsg = FALSE;
524 must_redraw = 0;
525 trylevel = 0;
526 did_throw = FALSE;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100527 need_rethrow = FALSE;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100528 current_exception = NULL;
529 may_garbage_collect = FALSE;
530 save_vimvars(&vvsave);
531
Bram Moolenaar22286892020-11-05 20:50:51 +0100532 // Invoke the callback.
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100533 timer->tr_firing = TRUE;
534 timer_callback(timer);
535 timer->tr_firing = FALSE;
536
Bram Moolenaar22286892020-11-05 20:50:51 +0100537 // Restore stuff.
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100538 timer_next = timer->tr_next;
539 did_one = TRUE;
540 timer_busy = save_timer_busy;
541 vgetc_busy = save_vgetc_busy;
542 if (did_uncaught_emsg)
543 ++timer->tr_emsg_count;
544 did_emsg = save_did_emsg;
545 called_emsg = save_called_emsg;
546 trylevel = save_trylevel;
547 did_throw = save_did_throw;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100548 need_rethrow = save_need_rethrow;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100549 current_exception = save_current_exception;
550 restore_vimvars(&vvsave);
551 if (must_redraw != 0)
552 need_update_screen = TRUE;
553 must_redraw = must_redraw > save_must_redraw
554 ? must_redraw : save_must_redraw;
555 set_pressedreturn(save_ex_pressedreturn);
556 may_garbage_collect = save_may_garbage_collect;
557
558 // Only fire the timer again if it repeats and stop_timer() wasn't
559 // called while inside the callback (tr_id == -1).
560 if (timer->tr_repeat != 0 && timer->tr_id != -1
561 && timer->tr_emsg_count < 3)
562 {
563 profile_setlimit(timer->tr_interval, &timer->tr_due);
564 this_due = proftime_time_left(&timer->tr_due, &now);
565 if (this_due < 1)
566 this_due = 1;
567 if (timer->tr_repeat > 0)
568 --timer->tr_repeat;
569 }
570 else
571 {
572 this_due = -1;
573 remove_timer(timer);
574 free_timer(timer);
575 }
576 }
577 if (this_due > 0 && (next_due == -1 || next_due > this_due))
578 next_due = this_due;
579 }
580
581 if (did_one)
582 redraw_after_callback(need_update_screen);
583
584#ifdef FEAT_BEVAL_TERM
585 if (bevalexpr_due_set)
586 {
587 this_due = proftime_time_left(&bevalexpr_due, &now);
588 if (this_due <= 1)
589 {
590 bevalexpr_due_set = FALSE;
591 if (balloonEval == NULL)
592 {
593 balloonEval = ALLOC_CLEAR_ONE(BalloonEval);
594 balloonEvalForTerm = TRUE;
595 }
596 if (balloonEval != NULL)
597 {
598 general_beval_cb(balloonEval, 0);
599 setcursor();
600 out_flush();
601 }
602 }
603 else if (next_due == -1 || next_due > this_due)
604 next_due = this_due;
605 }
606#endif
607#ifdef FEAT_TERMINAL
608 // Some terminal windows may need their buffer updated.
609 next_due = term_check_timers(next_due, &now);
610#endif
611
612 return current_id != last_timer_id ? 1 : next_due;
613}
614
615/*
616 * Find a timer by ID. Returns NULL if not found;
617 */
618 static timer_T *
619find_timer(long id)
620{
621 timer_T *timer;
622
623 if (id >= 0)
624 {
Bram Moolenaar00d253e2020-04-06 22:13:01 +0200625 FOR_ALL_TIMERS(timer)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100626 if (timer->tr_id == id)
627 return timer;
628 }
629 return NULL;
630}
631
632
633/*
634 * Stop a timer and delete it.
635 */
636 void
637stop_timer(timer_T *timer)
638{
639 if (timer->tr_firing)
640 // Free the timer after the callback returns.
641 timer->tr_id = -1;
642 else
643 {
644 remove_timer(timer);
645 free_timer(timer);
646 }
647}
648
649 static void
650stop_all_timers(void)
651{
652 timer_T *timer;
653 timer_T *timer_next;
654
655 for (timer = first_timer; timer != NULL; timer = timer_next)
656 {
657 timer_next = timer->tr_next;
658 stop_timer(timer);
659 }
660}
661
662 static void
663add_timer_info(typval_T *rettv, timer_T *timer)
664{
665 list_T *list = rettv->vval.v_list;
666 dict_T *dict = dict_alloc();
667 dictitem_T *di;
668 long remaining;
669 proftime_T now;
670
671 if (dict == NULL)
672 return;
673 list_append_dict(list, dict);
674
675 dict_add_number(dict, "id", timer->tr_id);
676 dict_add_number(dict, "time", (long)timer->tr_interval);
677
678 profile_start(&now);
679 remaining = proftime_time_left(&timer->tr_due, &now);
680 dict_add_number(dict, "remaining", (long)remaining);
681
682 dict_add_number(dict, "repeat",
683 (long)(timer->tr_repeat < 0 ? -1 : timer->tr_repeat + 1));
684 dict_add_number(dict, "paused", (long)(timer->tr_paused));
685
686 di = dictitem_alloc((char_u *)"callback");
687 if (di != NULL)
688 {
689 if (dict_add(dict, di) == FAIL)
690 vim_free(di);
691 else
692 put_callback(&timer->tr_callback, &di->di_tv);
693 }
694}
695
696 static void
697add_timer_info_all(typval_T *rettv)
698{
699 timer_T *timer;
700
Bram Moolenaar00d253e2020-04-06 22:13:01 +0200701 FOR_ALL_TIMERS(timer)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100702 if (timer->tr_id != -1)
703 add_timer_info(rettv, timer);
704}
705
706/*
707 * Mark references in partials of timers.
708 */
709 int
710set_ref_in_timer(int copyID)
711{
712 int abort = FALSE;
713 timer_T *timer;
714 typval_T tv;
715
716 for (timer = first_timer; !abort && timer != NULL; timer = timer->tr_next)
717 {
718 if (timer->tr_callback.cb_partial != NULL)
719 {
720 tv.v_type = VAR_PARTIAL;
721 tv.vval.v_partial = timer->tr_callback.cb_partial;
722 }
723 else
724 {
725 tv.v_type = VAR_FUNC;
726 tv.vval.v_string = timer->tr_callback.cb_name;
727 }
728 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
729 }
730 return abort;
731}
732
733# if defined(EXITFREE) || defined(PROTO)
734 void
735timer_free_all()
736{
737 timer_T *timer;
738
739 while (first_timer != NULL)
740 {
741 timer = first_timer;
742 remove_timer(timer);
743 free_timer(timer);
744 }
745}
746# endif
747
748/*
749 * "timer_info([timer])" function
750 */
751 void
752f_timer_info(typval_T *argvars, typval_T *rettv)
753{
754 timer_T *timer = NULL;
755
756 if (rettv_list_alloc(rettv) != OK)
757 return;
758 if (argvars[0].v_type != VAR_UNKNOWN)
759 {
760 if (argvars[0].v_type != VAR_NUMBER)
761 emsg(_(e_number_exp));
762 else
763 {
764 timer = find_timer((int)tv_get_number(&argvars[0]));
765 if (timer != NULL)
766 add_timer_info(rettv, timer);
767 }
768 }
769 else
770 add_timer_info_all(rettv);
771}
772
773/*
774 * "timer_pause(timer, paused)" function
775 */
776 void
777f_timer_pause(typval_T *argvars, typval_T *rettv UNUSED)
778{
779 timer_T *timer = NULL;
Bram Moolenaar418155d2020-09-06 18:39:38 +0200780 int paused = (int)tv_get_bool(&argvars[1]);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100781
782 if (argvars[0].v_type != VAR_NUMBER)
783 emsg(_(e_number_exp));
784 else
785 {
786 timer = find_timer((int)tv_get_number(&argvars[0]));
787 if (timer != NULL)
788 timer->tr_paused = paused;
789 }
790}
791
792/*
793 * "timer_start(time, callback [, options])" function
794 */
795 void
796f_timer_start(typval_T *argvars, typval_T *rettv)
797{
798 long msec = (long)tv_get_number(&argvars[0]);
799 timer_T *timer;
800 int repeat = 0;
801 callback_T callback;
802 dict_T *dict;
803
804 rettv->vval.v_number = -1;
805 if (check_secure())
806 return;
807 if (argvars[2].v_type != VAR_UNKNOWN)
808 {
809 if (argvars[2].v_type != VAR_DICT
810 || (dict = argvars[2].vval.v_dict) == NULL)
811 {
812 semsg(_(e_invarg2), tv_get_string(&argvars[2]));
813 return;
814 }
815 if (dict_find(dict, (char_u *)"repeat", -1) != NULL)
816 repeat = dict_get_number(dict, (char_u *)"repeat");
817 }
818
819 callback = get_callback(&argvars[1]);
820 if (callback.cb_name == NULL)
821 return;
822
823 timer = create_timer(msec, repeat);
824 if (timer == NULL)
825 free_callback(&callback);
826 else
827 {
828 set_callback(&timer->tr_callback, &callback);
829 rettv->vval.v_number = (varnumber_T)timer->tr_id;
830 }
831}
832
833/*
834 * "timer_stop(timer)" function
835 */
836 void
837f_timer_stop(typval_T *argvars, typval_T *rettv UNUSED)
838{
839 timer_T *timer;
840
841 if (argvars[0].v_type != VAR_NUMBER)
842 {
843 emsg(_(e_number_exp));
844 return;
845 }
846 timer = find_timer((int)tv_get_number(&argvars[0]));
847 if (timer != NULL)
848 stop_timer(timer);
849}
850
851/*
852 * "timer_stopall()" function
853 */
854 void
855f_timer_stopall(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
856{
857 stop_all_timers();
858}
859
860# endif // FEAT_TIMERS
861
862# if defined(STARTUPTIME) || defined(PROTO)
863static struct timeval prev_timeval;
864
865# ifdef MSWIN
866/*
867 * Windows doesn't have gettimeofday(), although it does have struct timeval.
868 */
869 static int
870gettimeofday(struct timeval *tv, char *dummy UNUSED)
871{
872 long t = clock();
873 tv->tv_sec = t / CLOCKS_PER_SEC;
874 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
875 return 0;
876}
877# endif
878
879/*
880 * Save the previous time before doing something that could nest.
881 * set "*tv_rel" to the time elapsed so far.
882 */
883 void
884time_push(void *tv_rel, void *tv_start)
885{
886 *((struct timeval *)tv_rel) = prev_timeval;
887 gettimeofday(&prev_timeval, NULL);
888 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
889 - ((struct timeval *)tv_rel)->tv_usec;
890 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
891 - ((struct timeval *)tv_rel)->tv_sec;
892 if (((struct timeval *)tv_rel)->tv_usec < 0)
893 {
894 ((struct timeval *)tv_rel)->tv_usec += 1000000;
895 --((struct timeval *)tv_rel)->tv_sec;
896 }
897 *(struct timeval *)tv_start = prev_timeval;
898}
899
900/*
901 * Compute the previous time after doing something that could nest.
902 * Subtract "*tp" from prev_timeval;
903 * Note: The arguments are (void *) to avoid trouble with systems that don't
904 * have struct timeval.
905 */
906 void
907time_pop(
908 void *tp) // actually (struct timeval *)
909{
910 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
911 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
912 if (prev_timeval.tv_usec < 0)
913 {
914 prev_timeval.tv_usec += 1000000;
915 --prev_timeval.tv_sec;
916 }
917}
918
919 static void
920time_diff(struct timeval *then, struct timeval *now)
921{
922 long usec;
923 long msec;
924
925 usec = now->tv_usec - then->tv_usec;
926 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
927 usec = usec % 1000L;
928 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
929}
930
931 void
932time_msg(
933 char *mesg,
934 void *tv_start) // only for do_source: start time; actually
935 // (struct timeval *)
936{
937 static struct timeval start;
938 struct timeval now;
939
940 if (time_fd != NULL)
941 {
942 if (strstr(mesg, "STARTING") != NULL)
943 {
944 gettimeofday(&start, NULL);
945 prev_timeval = start;
946 fprintf(time_fd, "\n\ntimes in msec\n");
947 fprintf(time_fd, " clock self+sourced self: sourced script\n");
948 fprintf(time_fd, " clock elapsed: other lines\n\n");
949 }
950 gettimeofday(&now, NULL);
951 time_diff(&start, &now);
952 if (((struct timeval *)tv_start) != NULL)
953 {
954 fprintf(time_fd, " ");
955 time_diff(((struct timeval *)tv_start), &now);
956 }
957 fprintf(time_fd, " ");
958 time_diff(&prev_timeval, &now);
959 prev_timeval = now;
960 fprintf(time_fd, ": %s\n", mesg);
961 }
962}
963# endif // STARTUPTIME
964#endif // FEAT_EVAL
965
966#if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
967/*
968 * Read 8 bytes from "fd" and turn them into a time_T, MSB first.
969 * Returns -1 when encountering EOF.
970 */
971 time_T
972get8ctime(FILE *fd)
973{
974 int c;
975 time_T n = 0;
976 int i;
977
978 for (i = 0; i < 8; ++i)
979 {
980 c = getc(fd);
981 if (c == EOF) return -1;
982 n = (n << 8) + c;
983 }
984 return n;
985}
986
987#ifdef _MSC_VER
988# if (_MSC_VER <= 1200)
989// This line is required for VC6 without the service pack. Also see the
990// matching #pragma below.
991 # pragma optimize("", off)
992# endif
993#endif
994
995/*
996 * Write time_T to file "fd" in 8 bytes.
997 * Returns FAIL when the write failed.
998 */
999 int
1000put_time(FILE *fd, time_T the_time)
1001{
1002 char_u buf[8];
1003
1004 time_to_bytes(the_time, buf);
1005 return fwrite(buf, (size_t)8, (size_t)1, fd) == 1 ? OK : FAIL;
1006}
1007
1008/*
1009 * Write time_T to "buf[8]".
1010 */
1011 void
1012time_to_bytes(time_T the_time, char_u *buf)
1013{
1014 int c;
1015 int i;
1016 int bi = 0;
1017 time_T wtime = the_time;
1018
1019 // time_T can be up to 8 bytes in size, more than long_u, thus we
1020 // can't use put_bytes() here.
1021 // Another problem is that ">>" may do an arithmetic shift that keeps the
1022 // sign. This happens for large values of wtime. A cast to long_u may
1023 // truncate if time_T is 8 bytes. So only use a cast when it is 4 bytes,
1024 // it's safe to assume that long_u is 4 bytes or more and when using 8
1025 // bytes the top bit won't be set.
1026 for (i = 7; i >= 0; --i)
1027 {
1028 if (i + 1 > (int)sizeof(time_T))
1029 // ">>" doesn't work well when shifting more bits than avail
1030 buf[bi++] = 0;
1031 else
1032 {
1033#if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
1034 c = (int)(wtime >> (i * 8));
1035#else
1036 c = (int)((long_u)wtime >> (i * 8));
1037#endif
1038 buf[bi++] = c;
1039 }
1040 }
1041}
1042
1043#ifdef _MSC_VER
1044# if (_MSC_VER <= 1200)
1045 # pragma optimize("", on)
1046# endif
1047#endif
1048
1049#endif
1050
1051/*
1052 * Put timestamp "tt" in "buf[buflen]" in a nice format.
1053 */
1054 void
1055add_time(char_u *buf, size_t buflen, time_t tt)
1056{
1057#ifdef HAVE_STRFTIME
1058 struct tm tmval;
1059 struct tm *curtime;
1060
1061 if (vim_time() - tt >= 100)
1062 {
1063 curtime = vim_localtime(&tt, &tmval);
1064 if (vim_time() - tt < (60L * 60L * 12L))
1065 // within 12 hours
1066 (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
1067 else
1068 // longer ago
1069 (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime);
1070 }
1071 else
1072#endif
1073 {
1074 long seconds = (long)(vim_time() - tt);
1075
1076 vim_snprintf((char *)buf, buflen,
1077 NGETTEXT("%ld second ago", "%ld seconds ago", seconds),
1078 seconds);
1079 }
1080}