blob: 020f78dd0e8e278d10d22f41a460af5a1ddc9598 [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 {
Bram Moolenaar7e935772022-01-20 14:25:57 +000096 // xgettext:no-c-format
Bram Moolenaar0a8fed62020-02-14 13:22:17 +010097 (void)strftime(buf, sizeof(buf) - 1, _("%a %b %d %H:%M:%S %Y"),
98 curtime);
99# ifdef MSWIN
100 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
101 {
102 char_u *to_free = NULL;
103 int len;
104
105 acp_to_enc((char_u *)buf, (int)strlen(buf), &to_free, &len);
106 if (to_free != NULL)
107 {
108 STRCPY(buf, to_free);
109 vim_free(to_free);
110 }
111 }
112# endif
113 }
114#else
115 STRCPY(buf, "(unknown)");
116#endif
117 if (add_newline)
118 STRCAT(buf, "\n");
119 return buf;
120}
121
122#if defined(FEAT_EVAL) || defined(PROTO)
123
124#if defined(MACOS_X)
125# include <time.h> // for time_t
126#endif
127
128/*
129 * "localtime()" function
130 */
131 void
132f_localtime(typval_T *argvars UNUSED, typval_T *rettv)
133{
134 rettv->vval.v_number = (varnumber_T)time(NULL);
135}
136
137# if defined(FEAT_RELTIME)
138/*
139 * Convert a List to proftime_T.
140 * Return FAIL when there is something wrong.
141 */
142 static int
143list2proftime(typval_T *arg, proftime_T *tm)
144{
145 long n1, n2;
146 int error = FALSE;
147
148 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
149 || arg->vval.v_list->lv_len != 2)
150 return FAIL;
151 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
152 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
153# ifdef MSWIN
154 tm->HighPart = n1;
155 tm->LowPart = n2;
156# else
157 tm->tv_sec = n1;
158 tm->tv_usec = n2;
159# endif
160 return error ? FAIL : OK;
161}
162# endif // FEAT_RELTIME
163
164/*
165 * "reltime()" function
166 */
167 void
168f_reltime(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
169{
170# ifdef FEAT_RELTIME
171 proftime_T res;
172 proftime_T start;
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200173 long n1, n2;
174
175 if (rettv_list_alloc(rettv) != OK)
176 return;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100177
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200178 if (in_vim9script()
179 && (check_for_opt_list_arg(argvars, 0) == FAIL
180 || (argvars[0].v_type != VAR_UNKNOWN
181 && check_for_opt_list_arg(argvars, 1) == FAIL)))
182 return;
183
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100184 if (argvars[0].v_type == VAR_UNKNOWN)
185 {
186 // No arguments: get current time.
187 profile_start(&res);
188 }
189 else if (argvars[1].v_type == VAR_UNKNOWN)
190 {
191 if (list2proftime(&argvars[0], &res) == FAIL)
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200192 {
193 if (in_vim9script())
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000194 emsg(_(e_invalid_argument));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100195 return;
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200196 }
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100197 profile_end(&res);
198 }
199 else
200 {
201 // Two arguments: compute the difference.
202 if (list2proftime(&argvars[0], &start) == FAIL
203 || list2proftime(&argvars[1], &res) == FAIL)
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200204 {
205 if (in_vim9script())
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000206 emsg(_(e_invalid_argument));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100207 return;
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200208 }
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100209 profile_sub(&res, &start);
210 }
211
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100212# ifdef MSWIN
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200213 n1 = res.HighPart;
214 n2 = res.LowPart;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100215# else
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200216 n1 = res.tv_sec;
217 n2 = res.tv_usec;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100218# endif
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200219 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
220 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100221# endif
222}
223
224# ifdef FEAT_FLOAT
225/*
226 * "reltimefloat()" function
227 */
228 void
229f_reltimefloat(typval_T *argvars UNUSED, typval_T *rettv)
230{
231# ifdef FEAT_RELTIME
232 proftime_T tm;
233# endif
234
235 rettv->v_type = VAR_FLOAT;
236 rettv->vval.v_float = 0;
237# ifdef FEAT_RELTIME
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200238 if (in_vim9script() && check_for_list_arg(argvars, 0) == FAIL)
239 return;
240
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100241 if (list2proftime(&argvars[0], &tm) == OK)
242 rettv->vval.v_float = profile_float(&tm);
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200243 else if (in_vim9script())
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000244 emsg(_(e_invalid_argument));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100245# endif
246}
247# endif
248
249/*
250 * "reltimestr()" function
251 */
252 void
253f_reltimestr(typval_T *argvars UNUSED, typval_T *rettv)
254{
255# ifdef FEAT_RELTIME
256 proftime_T tm;
257# endif
258
259 rettv->v_type = VAR_STRING;
260 rettv->vval.v_string = NULL;
261# ifdef FEAT_RELTIME
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200262 if (in_vim9script() && check_for_list_arg(argvars, 0) == FAIL)
263 return;
264
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100265 if (list2proftime(&argvars[0], &tm) == OK)
266 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
Bram Moolenaarc816a2c2021-07-14 21:00:41 +0200267 else if (in_vim9script())
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000268 emsg(_(e_invalid_argument));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100269# endif
270}
271
272# if defined(HAVE_STRFTIME) || defined(PROTO)
273/*
274 * "strftime({format}[, {time}])" function
275 */
276 void
277f_strftime(typval_T *argvars, typval_T *rettv)
278{
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100279 struct tm tmval;
280 struct tm *curtime;
281 time_t seconds;
282 char_u *p;
283
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200284 if (in_vim9script()
285 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +0200286 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200287 return;
288
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100289 rettv->v_type = VAR_STRING;
290
291 p = tv_get_string(&argvars[0]);
292 if (argvars[1].v_type == VAR_UNKNOWN)
293 seconds = time(NULL);
294 else
295 seconds = (time_t)tv_get_number(&argvars[1]);
296 curtime = vim_localtime(&seconds, &tmval);
297 // MSVC returns NULL for an invalid value of seconds.
298 if (curtime == NULL)
299 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
300 else
301 {
K.Takata2c4a1d02021-05-28 15:49:34 +0200302# ifdef MSWIN
303 WCHAR result_buf[256];
304 WCHAR *wp;
305
306 wp = enc_to_utf16(p, NULL);
307 if (wp != NULL)
K.Takataeeec2542021-06-02 13:28:16 +0200308 (void)wcsftime(result_buf, ARRAY_LENGTH(result_buf), wp, curtime);
K.Takata2c4a1d02021-05-28 15:49:34 +0200309 else
310 result_buf[0] = NUL;
311 rettv->vval.v_string = utf16_to_enc(result_buf, NULL);
312 vim_free(wp);
313# else
314 char_u result_buf[256];
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100315 vimconv_T conv;
316 char_u *enc;
317
318 conv.vc_type = CONV_NONE;
319 enc = enc_locale();
320 convert_setup(&conv, p_enc, enc);
321 if (conv.vc_type != CONV_NONE)
322 p = string_convert(&conv, p, NULL);
323 if (p != NULL)
324 (void)strftime((char *)result_buf, sizeof(result_buf),
325 (char *)p, curtime);
326 else
327 result_buf[0] = NUL;
328
329 if (conv.vc_type != CONV_NONE)
330 vim_free(p);
331 convert_setup(&conv, enc, p_enc);
332 if (conv.vc_type != CONV_NONE)
333 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
334 else
335 rettv->vval.v_string = vim_strsave(result_buf);
336
337 // Release conversion descriptors
338 convert_setup(&conv, NULL, NULL);
339 vim_free(enc);
K.Takata2c4a1d02021-05-28 15:49:34 +0200340# endif
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100341 }
342}
343# endif
344
345# if defined(HAVE_STRPTIME) || defined(PROTO)
346/*
347 * "strptime({format}, {timestring})" function
348 */
349 void
350f_strptime(typval_T *argvars, typval_T *rettv)
351{
352 struct tm tmval;
353 char_u *fmt;
354 char_u *str;
355 vimconv_T conv;
356 char_u *enc;
357
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200358 if (in_vim9script()
359 && (check_for_string_arg(argvars, 0) == FAIL
360 || check_for_string_arg(argvars, 1) == FAIL))
361 return;
362
Bram Moolenaara80faa82020-04-12 19:37:17 +0200363 CLEAR_FIELD(tmval);
Bram Moolenaarea1233f2020-06-10 16:54:13 +0200364 tmval.tm_isdst = -1;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100365 fmt = tv_get_string(&argvars[0]);
366 str = tv_get_string(&argvars[1]);
367
368 conv.vc_type = CONV_NONE;
369 enc = enc_locale();
370 convert_setup(&conv, p_enc, enc);
371 if (conv.vc_type != CONV_NONE)
372 fmt = string_convert(&conv, fmt, NULL);
373 if (fmt == NULL
374 || strptime((char *)str, (char *)fmt, &tmval) == NULL
375 || (rettv->vval.v_number = mktime(&tmval)) == -1)
376 rettv->vval.v_number = 0;
377
378 if (conv.vc_type != CONV_NONE)
379 vim_free(fmt);
380 convert_setup(&conv, NULL, NULL);
381 vim_free(enc);
382}
383# endif
384
385# if defined(FEAT_TIMERS) || defined(PROTO)
386static timer_T *first_timer = NULL;
387static long last_timer_id = 0;
388
389/*
390 * Return time left until "due". Negative if past "due".
391 */
392 long
393proftime_time_left(proftime_T *due, proftime_T *now)
394{
395# ifdef MSWIN
396 LARGE_INTEGER fr;
397
398 if (now->QuadPart > due->QuadPart)
399 return 0;
400 QueryPerformanceFrequency(&fr);
401 return (long)(((double)(due->QuadPart - now->QuadPart)
402 / (double)fr.QuadPart) * 1000);
403# else
404 if (now->tv_sec > due->tv_sec)
405 return 0;
406 return (due->tv_sec - now->tv_sec) * 1000
407 + (due->tv_usec - now->tv_usec) / 1000;
408# endif
409}
410
411/*
412 * Insert a timer in the list of timers.
413 */
414 static void
415insert_timer(timer_T *timer)
416{
417 timer->tr_next = first_timer;
418 timer->tr_prev = NULL;
419 if (first_timer != NULL)
420 first_timer->tr_prev = timer;
421 first_timer = timer;
422 did_add_timer = TRUE;
423}
424
425/*
426 * Take a timer out of the list of timers.
427 */
428 static void
429remove_timer(timer_T *timer)
430{
431 if (timer->tr_prev == NULL)
432 first_timer = timer->tr_next;
433 else
434 timer->tr_prev->tr_next = timer->tr_next;
435 if (timer->tr_next != NULL)
436 timer->tr_next->tr_prev = timer->tr_prev;
437}
438
439 static void
440free_timer(timer_T *timer)
441{
442 free_callback(&timer->tr_callback);
443 vim_free(timer);
444}
445
446/*
447 * Create a timer and return it. NULL if out of memory.
448 * Caller should set the callback.
449 */
450 timer_T *
451create_timer(long msec, int repeat)
452{
453 timer_T *timer = ALLOC_CLEAR_ONE(timer_T);
454 long prev_id = last_timer_id;
455
456 if (timer == NULL)
457 return NULL;
458 if (++last_timer_id <= prev_id)
459 // Overflow! Might cause duplicates...
460 last_timer_id = 0;
461 timer->tr_id = last_timer_id;
462 insert_timer(timer);
463 if (repeat != 0)
464 timer->tr_repeat = repeat - 1;
465 timer->tr_interval = msec;
466
467 profile_setlimit(msec, &timer->tr_due);
468 return timer;
469}
470
471/*
472 * Invoke the callback of "timer".
473 */
474 static void
475timer_callback(timer_T *timer)
476{
477 typval_T rettv;
478 typval_T argv[2];
479
480 argv[0].v_type = VAR_NUMBER;
481 argv[0].vval.v_number = (varnumber_T)timer->tr_id;
482 argv[1].v_type = VAR_UNKNOWN;
483
484 call_callback(&timer->tr_callback, -1, &rettv, 1, argv);
485 clear_tv(&rettv);
486}
487
488/*
489 * Call timers that are due.
490 * Return the time in msec until the next timer is due.
491 * Returns -1 if there are no pending timers.
492 */
493 long
494check_due_timer(void)
495{
496 timer_T *timer;
497 timer_T *timer_next;
498 long this_due;
499 long next_due = -1;
500 proftime_T now;
501 int did_one = FALSE;
502 int need_update_screen = FALSE;
503 long current_id = last_timer_id;
504
Bram Moolenaar48d0ac72022-01-07 20:40:08 +0000505 // Don't run any timers while exiting, dealing with an error or at the
506 // debug prompt.
507 if (exiting || aborting() || debug_mode)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100508 return next_due;
509
510 profile_start(&now);
511 for (timer = first_timer; timer != NULL && !got_int; timer = timer_next)
512 {
513 timer_next = timer->tr_next;
514
515 if (timer->tr_id == -1 || timer->tr_firing || timer->tr_paused)
516 continue;
517 this_due = proftime_time_left(&timer->tr_due, &now);
518 if (this_due <= 1)
519 {
520 // Save and restore a lot of flags, because the timer fires while
521 // waiting for a character, which might be halfway a command.
522 int save_timer_busy = timer_busy;
523 int save_vgetc_busy = vgetc_busy;
524 int save_did_emsg = did_emsg;
Bram Moolenaar88c89c72021-08-14 14:01:05 +0200525 int prev_uncaught_emsg = uncaught_emsg;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100526 int save_called_emsg = called_emsg;
527 int save_must_redraw = must_redraw;
528 int save_trylevel = trylevel;
529 int save_did_throw = did_throw;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100530 int save_need_rethrow = need_rethrow;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100531 int save_ex_pressedreturn = get_pressedreturn();
532 int save_may_garbage_collect = may_garbage_collect;
533 except_T *save_current_exception = current_exception;
534 vimvars_save_T vvsave;
535
536 // Create a scope for running the timer callback, ignoring most of
537 // the current scope, such as being inside a try/catch.
538 timer_busy = timer_busy > 0 || vgetc_busy > 0;
539 vgetc_busy = 0;
540 called_emsg = 0;
541 did_emsg = FALSE;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100542 must_redraw = 0;
543 trylevel = 0;
544 did_throw = FALSE;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100545 need_rethrow = FALSE;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100546 current_exception = NULL;
547 may_garbage_collect = FALSE;
548 save_vimvars(&vvsave);
549
Bram Moolenaar22286892020-11-05 20:50:51 +0100550 // Invoke the callback.
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100551 timer->tr_firing = TRUE;
552 timer_callback(timer);
553 timer->tr_firing = FALSE;
554
Bram Moolenaar22286892020-11-05 20:50:51 +0100555 // Restore stuff.
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100556 timer_next = timer->tr_next;
557 did_one = TRUE;
558 timer_busy = save_timer_busy;
559 vgetc_busy = save_vgetc_busy;
Bram Moolenaar88c89c72021-08-14 14:01:05 +0200560 if (uncaught_emsg > prev_uncaught_emsg)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100561 ++timer->tr_emsg_count;
562 did_emsg = save_did_emsg;
563 called_emsg = save_called_emsg;
564 trylevel = save_trylevel;
565 did_throw = save_did_throw;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100566 need_rethrow = save_need_rethrow;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100567 current_exception = save_current_exception;
568 restore_vimvars(&vvsave);
569 if (must_redraw != 0)
570 need_update_screen = TRUE;
571 must_redraw = must_redraw > save_must_redraw
572 ? must_redraw : save_must_redraw;
573 set_pressedreturn(save_ex_pressedreturn);
574 may_garbage_collect = save_may_garbage_collect;
575
576 // Only fire the timer again if it repeats and stop_timer() wasn't
577 // called while inside the callback (tr_id == -1).
578 if (timer->tr_repeat != 0 && timer->tr_id != -1
579 && timer->tr_emsg_count < 3)
580 {
581 profile_setlimit(timer->tr_interval, &timer->tr_due);
582 this_due = proftime_time_left(&timer->tr_due, &now);
583 if (this_due < 1)
584 this_due = 1;
585 if (timer->tr_repeat > 0)
586 --timer->tr_repeat;
587 }
588 else
589 {
590 this_due = -1;
591 remove_timer(timer);
592 free_timer(timer);
593 }
594 }
595 if (this_due > 0 && (next_due == -1 || next_due > this_due))
596 next_due = this_due;
597 }
598
599 if (did_one)
Bram Moolenaare5050712021-12-09 10:51:05 +0000600 redraw_after_callback(need_update_screen, FALSE);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100601
602#ifdef FEAT_BEVAL_TERM
603 if (bevalexpr_due_set)
604 {
605 this_due = proftime_time_left(&bevalexpr_due, &now);
606 if (this_due <= 1)
607 {
608 bevalexpr_due_set = FALSE;
609 if (balloonEval == NULL)
610 {
611 balloonEval = ALLOC_CLEAR_ONE(BalloonEval);
612 balloonEvalForTerm = TRUE;
613 }
614 if (balloonEval != NULL)
615 {
616 general_beval_cb(balloonEval, 0);
617 setcursor();
618 out_flush();
619 }
620 }
621 else if (next_due == -1 || next_due > this_due)
622 next_due = this_due;
623 }
624#endif
625#ifdef FEAT_TERMINAL
626 // Some terminal windows may need their buffer updated.
627 next_due = term_check_timers(next_due, &now);
628#endif
629
630 return current_id != last_timer_id ? 1 : next_due;
631}
632
633/*
634 * Find a timer by ID. Returns NULL if not found;
635 */
636 static timer_T *
637find_timer(long id)
638{
639 timer_T *timer;
640
641 if (id >= 0)
642 {
Bram Moolenaar00d253e2020-04-06 22:13:01 +0200643 FOR_ALL_TIMERS(timer)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100644 if (timer->tr_id == id)
645 return timer;
646 }
647 return NULL;
648}
649
650
651/*
652 * Stop a timer and delete it.
653 */
654 void
655stop_timer(timer_T *timer)
656{
657 if (timer->tr_firing)
658 // Free the timer after the callback returns.
659 timer->tr_id = -1;
660 else
661 {
662 remove_timer(timer);
663 free_timer(timer);
664 }
665}
666
667 static void
668stop_all_timers(void)
669{
670 timer_T *timer;
671 timer_T *timer_next;
672
673 for (timer = first_timer; timer != NULL; timer = timer_next)
674 {
675 timer_next = timer->tr_next;
676 stop_timer(timer);
677 }
678}
679
680 static void
681add_timer_info(typval_T *rettv, timer_T *timer)
682{
683 list_T *list = rettv->vval.v_list;
684 dict_T *dict = dict_alloc();
685 dictitem_T *di;
686 long remaining;
687 proftime_T now;
688
689 if (dict == NULL)
690 return;
691 list_append_dict(list, dict);
692
693 dict_add_number(dict, "id", timer->tr_id);
694 dict_add_number(dict, "time", (long)timer->tr_interval);
695
696 profile_start(&now);
697 remaining = proftime_time_left(&timer->tr_due, &now);
698 dict_add_number(dict, "remaining", (long)remaining);
699
700 dict_add_number(dict, "repeat",
Bram Moolenaar95b2dd02021-12-09 18:42:57 +0000701 (long)(timer->tr_repeat < 0 ? -1
702 : timer->tr_repeat + (timer->tr_firing ? 0 : 1)));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100703 dict_add_number(dict, "paused", (long)(timer->tr_paused));
704
705 di = dictitem_alloc((char_u *)"callback");
706 if (di != NULL)
707 {
708 if (dict_add(dict, di) == FAIL)
709 vim_free(di);
710 else
711 put_callback(&timer->tr_callback, &di->di_tv);
712 }
713}
714
715 static void
716add_timer_info_all(typval_T *rettv)
717{
718 timer_T *timer;
719
Bram Moolenaar00d253e2020-04-06 22:13:01 +0200720 FOR_ALL_TIMERS(timer)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100721 if (timer->tr_id != -1)
722 add_timer_info(rettv, timer);
723}
724
725/*
726 * Mark references in partials of timers.
727 */
728 int
729set_ref_in_timer(int copyID)
730{
731 int abort = FALSE;
732 timer_T *timer;
733 typval_T tv;
734
735 for (timer = first_timer; !abort && timer != NULL; timer = timer->tr_next)
736 {
737 if (timer->tr_callback.cb_partial != NULL)
738 {
739 tv.v_type = VAR_PARTIAL;
740 tv.vval.v_partial = timer->tr_callback.cb_partial;
741 }
742 else
743 {
744 tv.v_type = VAR_FUNC;
745 tv.vval.v_string = timer->tr_callback.cb_name;
746 }
747 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
748 }
749 return abort;
750}
751
752# if defined(EXITFREE) || defined(PROTO)
753 void
754timer_free_all()
755{
756 timer_T *timer;
757
758 while (first_timer != NULL)
759 {
760 timer = first_timer;
761 remove_timer(timer);
762 free_timer(timer);
763 }
764}
765# endif
766
767/*
768 * "timer_info([timer])" function
769 */
770 void
771f_timer_info(typval_T *argvars, typval_T *rettv)
772{
773 timer_T *timer = NULL;
774
775 if (rettv_list_alloc(rettv) != OK)
776 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200777
778 if (in_vim9script() && check_for_opt_number_arg(argvars, 0) == FAIL)
779 return;
780
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100781 if (argvars[0].v_type != VAR_UNKNOWN)
782 {
783 if (argvars[0].v_type != VAR_NUMBER)
Bram Moolenaare29a27f2021-07-20 21:07:36 +0200784 emsg(_(e_number_expected));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100785 else
786 {
787 timer = find_timer((int)tv_get_number(&argvars[0]));
788 if (timer != NULL)
789 add_timer_info(rettv, timer);
790 }
791 }
792 else
793 add_timer_info_all(rettv);
794}
795
796/*
797 * "timer_pause(timer, paused)" function
798 */
799 void
800f_timer_pause(typval_T *argvars, typval_T *rettv UNUSED)
801{
802 timer_T *timer = NULL;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +0200803
804 if (in_vim9script()
805 && (check_for_number_arg(argvars, 0) == FAIL
806 || check_for_bool_arg(argvars, 1) == FAIL))
807 return;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100808
809 if (argvars[0].v_type != VAR_NUMBER)
Bram Moolenaare29a27f2021-07-20 21:07:36 +0200810 emsg(_(e_number_expected));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100811 else
812 {
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +0200813 int paused = (int)tv_get_bool(&argvars[1]);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100814 timer = find_timer((int)tv_get_number(&argvars[0]));
815 if (timer != NULL)
816 timer->tr_paused = paused;
817 }
818}
819
820/*
821 * "timer_start(time, callback [, options])" function
822 */
823 void
824f_timer_start(typval_T *argvars, typval_T *rettv)
825{
Yegappan Lakshmanan7973de32021-07-24 16:16:15 +0200826 long msec;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100827 timer_T *timer;
828 int repeat = 0;
829 callback_T callback;
830 dict_T *dict;
831
832 rettv->vval.v_number = -1;
833 if (check_secure())
834 return;
Yegappan Lakshmanan7973de32021-07-24 16:16:15 +0200835
836 if (in_vim9script()
837 && (check_for_number_arg(argvars, 0) == FAIL
838 || check_for_opt_dict_arg(argvars, 2) == FAIL))
839 return;
840
841 msec = (long)tv_get_number(&argvars[0]);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100842 if (argvars[2].v_type != VAR_UNKNOWN)
843 {
844 if (argvars[2].v_type != VAR_DICT
845 || (dict = argvars[2].vval.v_dict) == NULL)
846 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000847 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[2]));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100848 return;
849 }
850 if (dict_find(dict, (char_u *)"repeat", -1) != NULL)
851 repeat = dict_get_number(dict, (char_u *)"repeat");
852 }
853
854 callback = get_callback(&argvars[1]);
855 if (callback.cb_name == NULL)
856 return;
857
858 timer = create_timer(msec, repeat);
859 if (timer == NULL)
860 free_callback(&callback);
861 else
862 {
863 set_callback(&timer->tr_callback, &callback);
864 rettv->vval.v_number = (varnumber_T)timer->tr_id;
865 }
866}
867
868/*
869 * "timer_stop(timer)" function
870 */
871 void
872f_timer_stop(typval_T *argvars, typval_T *rettv UNUSED)
873{
874 timer_T *timer;
875
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200876 if (in_vim9script() && check_for_number_arg(argvars, 0) == FAIL)
877 return;
878
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100879 if (argvars[0].v_type != VAR_NUMBER)
880 {
Bram Moolenaare29a27f2021-07-20 21:07:36 +0200881 emsg(_(e_number_expected));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100882 return;
883 }
884 timer = find_timer((int)tv_get_number(&argvars[0]));
885 if (timer != NULL)
886 stop_timer(timer);
887}
888
889/*
890 * "timer_stopall()" function
891 */
892 void
893f_timer_stopall(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
894{
895 stop_all_timers();
896}
897
898# endif // FEAT_TIMERS
899
900# if defined(STARTUPTIME) || defined(PROTO)
901static struct timeval prev_timeval;
902
903# ifdef MSWIN
904/*
905 * Windows doesn't have gettimeofday(), although it does have struct timeval.
906 */
907 static int
908gettimeofday(struct timeval *tv, char *dummy UNUSED)
909{
910 long t = clock();
911 tv->tv_sec = t / CLOCKS_PER_SEC;
912 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
913 return 0;
914}
915# endif
916
917/*
918 * Save the previous time before doing something that could nest.
919 * set "*tv_rel" to the time elapsed so far.
920 */
921 void
922time_push(void *tv_rel, void *tv_start)
923{
924 *((struct timeval *)tv_rel) = prev_timeval;
925 gettimeofday(&prev_timeval, NULL);
926 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
927 - ((struct timeval *)tv_rel)->tv_usec;
928 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
929 - ((struct timeval *)tv_rel)->tv_sec;
930 if (((struct timeval *)tv_rel)->tv_usec < 0)
931 {
932 ((struct timeval *)tv_rel)->tv_usec += 1000000;
933 --((struct timeval *)tv_rel)->tv_sec;
934 }
935 *(struct timeval *)tv_start = prev_timeval;
936}
937
938/*
939 * Compute the previous time after doing something that could nest.
940 * Subtract "*tp" from prev_timeval;
941 * Note: The arguments are (void *) to avoid trouble with systems that don't
942 * have struct timeval.
943 */
944 void
945time_pop(
946 void *tp) // actually (struct timeval *)
947{
948 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
949 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
950 if (prev_timeval.tv_usec < 0)
951 {
952 prev_timeval.tv_usec += 1000000;
953 --prev_timeval.tv_sec;
954 }
955}
956
957 static void
958time_diff(struct timeval *then, struct timeval *now)
959{
960 long usec;
961 long msec;
962
963 usec = now->tv_usec - then->tv_usec;
964 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
965 usec = usec % 1000L;
966 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
967}
968
969 void
970time_msg(
971 char *mesg,
972 void *tv_start) // only for do_source: start time; actually
973 // (struct timeval *)
974{
975 static struct timeval start;
976 struct timeval now;
977
978 if (time_fd != NULL)
979 {
980 if (strstr(mesg, "STARTING") != NULL)
981 {
982 gettimeofday(&start, NULL);
983 prev_timeval = start;
984 fprintf(time_fd, "\n\ntimes in msec\n");
985 fprintf(time_fd, " clock self+sourced self: sourced script\n");
986 fprintf(time_fd, " clock elapsed: other lines\n\n");
987 }
988 gettimeofday(&now, NULL);
989 time_diff(&start, &now);
990 if (((struct timeval *)tv_start) != NULL)
991 {
992 fprintf(time_fd, " ");
993 time_diff(((struct timeval *)tv_start), &now);
994 }
995 fprintf(time_fd, " ");
996 time_diff(&prev_timeval, &now);
997 prev_timeval = now;
998 fprintf(time_fd, ": %s\n", mesg);
999 }
1000}
1001# endif // STARTUPTIME
1002#endif // FEAT_EVAL
1003
1004#if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
1005/*
1006 * Read 8 bytes from "fd" and turn them into a time_T, MSB first.
1007 * Returns -1 when encountering EOF.
1008 */
1009 time_T
1010get8ctime(FILE *fd)
1011{
1012 int c;
1013 time_T n = 0;
1014 int i;
1015
1016 for (i = 0; i < 8; ++i)
1017 {
1018 c = getc(fd);
1019 if (c == EOF) return -1;
1020 n = (n << 8) + c;
1021 }
1022 return n;
1023}
1024
1025#ifdef _MSC_VER
1026# if (_MSC_VER <= 1200)
1027// This line is required for VC6 without the service pack. Also see the
1028// matching #pragma below.
1029 # pragma optimize("", off)
1030# endif
1031#endif
1032
1033/*
1034 * Write time_T to file "fd" in 8 bytes.
1035 * Returns FAIL when the write failed.
1036 */
1037 int
1038put_time(FILE *fd, time_T the_time)
1039{
1040 char_u buf[8];
1041
1042 time_to_bytes(the_time, buf);
1043 return fwrite(buf, (size_t)8, (size_t)1, fd) == 1 ? OK : FAIL;
1044}
1045
1046/*
1047 * Write time_T to "buf[8]".
1048 */
1049 void
1050time_to_bytes(time_T the_time, char_u *buf)
1051{
1052 int c;
1053 int i;
1054 int bi = 0;
1055 time_T wtime = the_time;
1056
1057 // time_T can be up to 8 bytes in size, more than long_u, thus we
1058 // can't use put_bytes() here.
1059 // Another problem is that ">>" may do an arithmetic shift that keeps the
1060 // sign. This happens for large values of wtime. A cast to long_u may
1061 // truncate if time_T is 8 bytes. So only use a cast when it is 4 bytes,
1062 // it's safe to assume that long_u is 4 bytes or more and when using 8
1063 // bytes the top bit won't be set.
1064 for (i = 7; i >= 0; --i)
1065 {
1066 if (i + 1 > (int)sizeof(time_T))
1067 // ">>" doesn't work well when shifting more bits than avail
1068 buf[bi++] = 0;
1069 else
1070 {
1071#if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
1072 c = (int)(wtime >> (i * 8));
1073#else
1074 c = (int)((long_u)wtime >> (i * 8));
1075#endif
1076 buf[bi++] = c;
1077 }
1078 }
1079}
1080
1081#ifdef _MSC_VER
1082# if (_MSC_VER <= 1200)
1083 # pragma optimize("", on)
1084# endif
1085#endif
1086
1087#endif
1088
1089/*
1090 * Put timestamp "tt" in "buf[buflen]" in a nice format.
1091 */
1092 void
1093add_time(char_u *buf, size_t buflen, time_t tt)
1094{
1095#ifdef HAVE_STRFTIME
1096 struct tm tmval;
1097 struct tm *curtime;
1098
1099 if (vim_time() - tt >= 100)
1100 {
1101 curtime = vim_localtime(&tt, &tmval);
1102 if (vim_time() - tt < (60L * 60L * 12L))
1103 // within 12 hours
1104 (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
1105 else
1106 // longer ago
1107 (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime);
1108 }
1109 else
1110#endif
1111 {
1112 long seconds = (long)(vim_time() - tt);
1113
1114 vim_snprintf((char *)buf, buflen,
1115 NGETTEXT("%ld second ago", "%ld seconds ago", seconds),
1116 seconds);
1117 }
1118}