blob: 58337c9f65a21e71fba4f0f3577ead69dd5e79b3 [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
Bram Moolenaar93a10962022-06-16 11:42:09 +0100175 if (rettv_list_alloc(rettv) == FAIL)
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200176 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
Bram Moolenaar9198de32022-08-27 21:30:03 +0100467 timer_start(timer);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100468 return timer;
469}
470
471/*
Bram Moolenaar9198de32022-08-27 21:30:03 +0100472 * (Re)start a timer.
473 */
474 void
475timer_start(timer_T *timer)
476{
477 profile_setlimit(timer->tr_interval, &timer->tr_due);
478 timer->tr_paused = FALSE;
479}
480
481/*
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100482 * Invoke the callback of "timer".
483 */
484 static void
485timer_callback(timer_T *timer)
486{
487 typval_T rettv;
488 typval_T argv[2];
489
Bram Moolenaar9b334d52022-05-06 14:59:04 +0100490#ifdef FEAT_JOB_CHANNEL
491 if (ch_log_active())
492 {
493 callback_T *cb = &timer->tr_callback;
494
495 ch_log(NULL, "invoking timer callback %s",
496 cb->cb_partial != NULL ? cb->cb_partial->pt_name : cb->cb_name);
497 }
498#endif
499
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100500 argv[0].v_type = VAR_NUMBER;
501 argv[0].vval.v_number = (varnumber_T)timer->tr_id;
502 argv[1].v_type = VAR_UNKNOWN;
503
Bram Moolenaar745b9382022-01-27 13:55:35 +0000504 rettv.v_type = VAR_UNKNOWN;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100505 call_callback(&timer->tr_callback, -1, &rettv, 1, argv);
506 clear_tv(&rettv);
Bram Moolenaar9b334d52022-05-06 14:59:04 +0100507
508#ifdef FEAT_JOB_CHANNEL
509 ch_log(NULL, "timer callback finished");
510#endif
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100511}
512
513/*
514 * Call timers that are due.
515 * Return the time in msec until the next timer is due.
516 * Returns -1 if there are no pending timers.
517 */
518 long
519check_due_timer(void)
520{
521 timer_T *timer;
522 timer_T *timer_next;
523 long this_due;
524 long next_due = -1;
525 proftime_T now;
526 int did_one = FALSE;
527 int need_update_screen = FALSE;
528 long current_id = last_timer_id;
529
Bram Moolenaar48d0ac72022-01-07 20:40:08 +0000530 // Don't run any timers while exiting, dealing with an error or at the
531 // debug prompt.
532 if (exiting || aborting() || debug_mode)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100533 return next_due;
534
535 profile_start(&now);
536 for (timer = first_timer; timer != NULL && !got_int; timer = timer_next)
537 {
538 timer_next = timer->tr_next;
539
540 if (timer->tr_id == -1 || timer->tr_firing || timer->tr_paused)
541 continue;
542 this_due = proftime_time_left(&timer->tr_due, &now);
543 if (this_due <= 1)
544 {
545 // Save and restore a lot of flags, because the timer fires while
546 // waiting for a character, which might be halfway a command.
547 int save_timer_busy = timer_busy;
548 int save_vgetc_busy = vgetc_busy;
549 int save_did_emsg = did_emsg;
Bram Moolenaar88c89c72021-08-14 14:01:05 +0200550 int prev_uncaught_emsg = uncaught_emsg;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100551 int save_called_emsg = called_emsg;
552 int save_must_redraw = must_redraw;
553 int save_trylevel = trylevel;
554 int save_did_throw = did_throw;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100555 int save_need_rethrow = need_rethrow;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100556 int save_ex_pressedreturn = get_pressedreturn();
557 int save_may_garbage_collect = may_garbage_collect;
558 except_T *save_current_exception = current_exception;
559 vimvars_save_T vvsave;
560
561 // Create a scope for running the timer callback, ignoring most of
562 // the current scope, such as being inside a try/catch.
563 timer_busy = timer_busy > 0 || vgetc_busy > 0;
564 vgetc_busy = 0;
565 called_emsg = 0;
566 did_emsg = FALSE;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100567 must_redraw = 0;
568 trylevel = 0;
569 did_throw = FALSE;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100570 need_rethrow = FALSE;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100571 current_exception = NULL;
572 may_garbage_collect = FALSE;
573 save_vimvars(&vvsave);
574
Bram Moolenaar22286892020-11-05 20:50:51 +0100575 // Invoke the callback.
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100576 timer->tr_firing = TRUE;
577 timer_callback(timer);
578 timer->tr_firing = FALSE;
579
Bram Moolenaar22286892020-11-05 20:50:51 +0100580 // Restore stuff.
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100581 timer_next = timer->tr_next;
582 did_one = TRUE;
583 timer_busy = save_timer_busy;
584 vgetc_busy = save_vgetc_busy;
Bram Moolenaar88c89c72021-08-14 14:01:05 +0200585 if (uncaught_emsg > prev_uncaught_emsg)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100586 ++timer->tr_emsg_count;
587 did_emsg = save_did_emsg;
588 called_emsg = save_called_emsg;
589 trylevel = save_trylevel;
590 did_throw = save_did_throw;
Bram Moolenaara0f7f732021-01-20 22:22:49 +0100591 need_rethrow = save_need_rethrow;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100592 current_exception = save_current_exception;
593 restore_vimvars(&vvsave);
594 if (must_redraw != 0)
595 need_update_screen = TRUE;
596 must_redraw = must_redraw > save_must_redraw
597 ? must_redraw : save_must_redraw;
598 set_pressedreturn(save_ex_pressedreturn);
599 may_garbage_collect = save_may_garbage_collect;
600
601 // Only fire the timer again if it repeats and stop_timer() wasn't
602 // called while inside the callback (tr_id == -1).
603 if (timer->tr_repeat != 0 && timer->tr_id != -1
604 && timer->tr_emsg_count < 3)
605 {
606 profile_setlimit(timer->tr_interval, &timer->tr_due);
607 this_due = proftime_time_left(&timer->tr_due, &now);
608 if (this_due < 1)
609 this_due = 1;
610 if (timer->tr_repeat > 0)
611 --timer->tr_repeat;
612 }
613 else
614 {
615 this_due = -1;
Bram Moolenaar9198de32022-08-27 21:30:03 +0100616 if (timer->tr_keep)
617 timer->tr_paused = TRUE;
618 else
619 {
620 remove_timer(timer);
621 free_timer(timer);
622 }
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100623 }
624 }
625 if (this_due > 0 && (next_due == -1 || next_due > this_due))
626 next_due = this_due;
627 }
628
629 if (did_one)
Bram Moolenaare5050712021-12-09 10:51:05 +0000630 redraw_after_callback(need_update_screen, FALSE);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100631
632#ifdef FEAT_BEVAL_TERM
633 if (bevalexpr_due_set)
634 {
635 this_due = proftime_time_left(&bevalexpr_due, &now);
636 if (this_due <= 1)
637 {
638 bevalexpr_due_set = FALSE;
639 if (balloonEval == NULL)
640 {
641 balloonEval = ALLOC_CLEAR_ONE(BalloonEval);
642 balloonEvalForTerm = TRUE;
643 }
644 if (balloonEval != NULL)
645 {
646 general_beval_cb(balloonEval, 0);
647 setcursor();
648 out_flush();
649 }
650 }
651 else if (next_due == -1 || next_due > this_due)
652 next_due = this_due;
653 }
654#endif
655#ifdef FEAT_TERMINAL
656 // Some terminal windows may need their buffer updated.
657 next_due = term_check_timers(next_due, &now);
658#endif
659
660 return current_id != last_timer_id ? 1 : next_due;
661}
662
663/*
664 * Find a timer by ID. Returns NULL if not found;
665 */
666 static timer_T *
667find_timer(long id)
668{
669 timer_T *timer;
670
671 if (id >= 0)
672 {
Bram Moolenaar00d253e2020-04-06 22:13:01 +0200673 FOR_ALL_TIMERS(timer)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100674 if (timer->tr_id == id)
675 return timer;
676 }
677 return NULL;
678}
679
680
681/*
682 * Stop a timer and delete it.
683 */
684 void
685stop_timer(timer_T *timer)
686{
687 if (timer->tr_firing)
688 // Free the timer after the callback returns.
689 timer->tr_id = -1;
690 else
691 {
692 remove_timer(timer);
693 free_timer(timer);
694 }
695}
696
697 static void
698stop_all_timers(void)
699{
700 timer_T *timer;
701 timer_T *timer_next;
702
703 for (timer = first_timer; timer != NULL; timer = timer_next)
704 {
705 timer_next = timer->tr_next;
706 stop_timer(timer);
707 }
708}
709
710 static void
711add_timer_info(typval_T *rettv, timer_T *timer)
712{
713 list_T *list = rettv->vval.v_list;
714 dict_T *dict = dict_alloc();
715 dictitem_T *di;
716 long remaining;
717 proftime_T now;
718
719 if (dict == NULL)
720 return;
721 list_append_dict(list, dict);
722
723 dict_add_number(dict, "id", timer->tr_id);
724 dict_add_number(dict, "time", (long)timer->tr_interval);
725
726 profile_start(&now);
727 remaining = proftime_time_left(&timer->tr_due, &now);
728 dict_add_number(dict, "remaining", (long)remaining);
729
730 dict_add_number(dict, "repeat",
Bram Moolenaar95b2dd02021-12-09 18:42:57 +0000731 (long)(timer->tr_repeat < 0 ? -1
732 : timer->tr_repeat + (timer->tr_firing ? 0 : 1)));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100733 dict_add_number(dict, "paused", (long)(timer->tr_paused));
734
735 di = dictitem_alloc((char_u *)"callback");
736 if (di != NULL)
737 {
738 if (dict_add(dict, di) == FAIL)
739 vim_free(di);
740 else
741 put_callback(&timer->tr_callback, &di->di_tv);
742 }
743}
744
745 static void
746add_timer_info_all(typval_T *rettv)
747{
748 timer_T *timer;
749
Bram Moolenaar00d253e2020-04-06 22:13:01 +0200750 FOR_ALL_TIMERS(timer)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100751 if (timer->tr_id != -1)
752 add_timer_info(rettv, timer);
753}
754
755/*
756 * Mark references in partials of timers.
757 */
758 int
759set_ref_in_timer(int copyID)
760{
761 int abort = FALSE;
762 timer_T *timer;
763 typval_T tv;
764
765 for (timer = first_timer; !abort && timer != NULL; timer = timer->tr_next)
766 {
767 if (timer->tr_callback.cb_partial != NULL)
768 {
769 tv.v_type = VAR_PARTIAL;
770 tv.vval.v_partial = timer->tr_callback.cb_partial;
771 }
772 else
773 {
774 tv.v_type = VAR_FUNC;
775 tv.vval.v_string = timer->tr_callback.cb_name;
776 }
777 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
778 }
779 return abort;
780}
781
782# if defined(EXITFREE) || defined(PROTO)
783 void
784timer_free_all()
785{
786 timer_T *timer;
787
788 while (first_timer != NULL)
789 {
790 timer = first_timer;
791 remove_timer(timer);
792 free_timer(timer);
793 }
794}
795# endif
796
797/*
798 * "timer_info([timer])" function
799 */
800 void
801f_timer_info(typval_T *argvars, typval_T *rettv)
802{
803 timer_T *timer = NULL;
804
Bram Moolenaar93a10962022-06-16 11:42:09 +0100805 if (rettv_list_alloc(rettv) == FAIL)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100806 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200807
Yegappan Lakshmanan8deb2b32022-09-02 15:15:27 +0100808 if (check_for_opt_number_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200809 return;
810
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100811 if (argvars[0].v_type != VAR_UNKNOWN)
812 {
Yegappan Lakshmanan8deb2b32022-09-02 15:15:27 +0100813 timer = find_timer((int)tv_get_number(&argvars[0]));
814 if (timer != NULL)
815 add_timer_info(rettv, timer);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100816 }
817 else
818 add_timer_info_all(rettv);
819}
820
821/*
822 * "timer_pause(timer, paused)" function
823 */
824 void
825f_timer_pause(typval_T *argvars, typval_T *rettv UNUSED)
826{
827 timer_T *timer = NULL;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +0200828
829 if (in_vim9script()
830 && (check_for_number_arg(argvars, 0) == FAIL
831 || check_for_bool_arg(argvars, 1) == FAIL))
832 return;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100833
834 if (argvars[0].v_type != VAR_NUMBER)
Bram Moolenaare29a27f2021-07-20 21:07:36 +0200835 emsg(_(e_number_expected));
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100836 else
837 {
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +0200838 int paused = (int)tv_get_bool(&argvars[1]);
Bram Moolenaar9198de32022-08-27 21:30:03 +0100839
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100840 timer = find_timer((int)tv_get_number(&argvars[0]));
841 if (timer != NULL)
842 timer->tr_paused = paused;
843 }
844}
845
846/*
847 * "timer_start(time, callback [, options])" function
848 */
849 void
850f_timer_start(typval_T *argvars, typval_T *rettv)
851{
Yegappan Lakshmanan7973de32021-07-24 16:16:15 +0200852 long msec;
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100853 timer_T *timer;
854 int repeat = 0;
855 callback_T callback;
856 dict_T *dict;
857
858 rettv->vval.v_number = -1;
859 if (check_secure())
860 return;
Yegappan Lakshmanan7973de32021-07-24 16:16:15 +0200861
862 if (in_vim9script()
863 && (check_for_number_arg(argvars, 0) == FAIL
864 || check_for_opt_dict_arg(argvars, 2) == FAIL))
865 return;
866
867 msec = (long)tv_get_number(&argvars[0]);
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100868 if (argvars[2].v_type != VAR_UNKNOWN)
869 {
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +0100870 if (check_for_nonnull_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100871 return;
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +0100872
873 dict = argvars[2].vval.v_dict;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +0100874 if (dict_has_key(dict, "repeat"))
Bram Moolenaard61efa52022-07-23 09:52:04 +0100875 repeat = dict_get_number(dict, "repeat");
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100876 }
877
878 callback = get_callback(&argvars[1]);
879 if (callback.cb_name == NULL)
880 return;
Bram Moolenaar745b9382022-01-27 13:55:35 +0000881 if (in_vim9script() && *callback.cb_name == NUL)
882 {
883 // empty callback is not useful for a timer
884 emsg(_(e_invalid_callback_argument));
885 free_callback(&callback);
886 return;
887 }
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100888
889 timer = create_timer(msec, repeat);
890 if (timer == NULL)
891 free_callback(&callback);
892 else
893 {
894 set_callback(&timer->tr_callback, &callback);
895 rettv->vval.v_number = (varnumber_T)timer->tr_id;
896 }
897}
898
899/*
900 * "timer_stop(timer)" function
901 */
902 void
903f_timer_stop(typval_T *argvars, typval_T *rettv UNUSED)
904{
905 timer_T *timer;
906
Yegappan Lakshmanan8deb2b32022-09-02 15:15:27 +0100907 if (check_for_number_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200908 return;
909
Bram Moolenaar0a8fed62020-02-14 13:22:17 +0100910 timer = find_timer((int)tv_get_number(&argvars[0]));
911 if (timer != NULL)
912 stop_timer(timer);
913}
914
915/*
916 * "timer_stopall()" function
917 */
918 void
919f_timer_stopall(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
920{
921 stop_all_timers();
922}
923
924# endif // FEAT_TIMERS
925
926# if defined(STARTUPTIME) || defined(PROTO)
927static struct timeval prev_timeval;
928
929# ifdef MSWIN
930/*
931 * Windows doesn't have gettimeofday(), although it does have struct timeval.
932 */
933 static int
934gettimeofday(struct timeval *tv, char *dummy UNUSED)
935{
936 long t = clock();
937 tv->tv_sec = t / CLOCKS_PER_SEC;
938 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
939 return 0;
940}
941# endif
942
943/*
944 * Save the previous time before doing something that could nest.
945 * set "*tv_rel" to the time elapsed so far.
946 */
947 void
948time_push(void *tv_rel, void *tv_start)
949{
950 *((struct timeval *)tv_rel) = prev_timeval;
951 gettimeofday(&prev_timeval, NULL);
952 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
953 - ((struct timeval *)tv_rel)->tv_usec;
954 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
955 - ((struct timeval *)tv_rel)->tv_sec;
956 if (((struct timeval *)tv_rel)->tv_usec < 0)
957 {
958 ((struct timeval *)tv_rel)->tv_usec += 1000000;
959 --((struct timeval *)tv_rel)->tv_sec;
960 }
961 *(struct timeval *)tv_start = prev_timeval;
962}
963
964/*
965 * Compute the previous time after doing something that could nest.
966 * Subtract "*tp" from prev_timeval;
967 * Note: The arguments are (void *) to avoid trouble with systems that don't
968 * have struct timeval.
969 */
970 void
971time_pop(
972 void *tp) // actually (struct timeval *)
973{
974 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
975 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
976 if (prev_timeval.tv_usec < 0)
977 {
978 prev_timeval.tv_usec += 1000000;
979 --prev_timeval.tv_sec;
980 }
981}
982
983 static void
984time_diff(struct timeval *then, struct timeval *now)
985{
986 long usec;
987 long msec;
988
989 usec = now->tv_usec - then->tv_usec;
990 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
991 usec = usec % 1000L;
992 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
993}
994
995 void
996time_msg(
997 char *mesg,
998 void *tv_start) // only for do_source: start time; actually
999 // (struct timeval *)
1000{
1001 static struct timeval start;
1002 struct timeval now;
1003
1004 if (time_fd != NULL)
1005 {
1006 if (strstr(mesg, "STARTING") != NULL)
1007 {
1008 gettimeofday(&start, NULL);
1009 prev_timeval = start;
1010 fprintf(time_fd, "\n\ntimes in msec\n");
1011 fprintf(time_fd, " clock self+sourced self: sourced script\n");
1012 fprintf(time_fd, " clock elapsed: other lines\n\n");
1013 }
1014 gettimeofday(&now, NULL);
1015 time_diff(&start, &now);
1016 if (((struct timeval *)tv_start) != NULL)
1017 {
1018 fprintf(time_fd, " ");
1019 time_diff(((struct timeval *)tv_start), &now);
1020 }
1021 fprintf(time_fd, " ");
1022 time_diff(&prev_timeval, &now);
1023 prev_timeval = now;
1024 fprintf(time_fd, ": %s\n", mesg);
1025 }
1026}
1027# endif // STARTUPTIME
1028#endif // FEAT_EVAL
1029
1030#if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
1031/*
1032 * Read 8 bytes from "fd" and turn them into a time_T, MSB first.
1033 * Returns -1 when encountering EOF.
1034 */
1035 time_T
1036get8ctime(FILE *fd)
1037{
1038 int c;
1039 time_T n = 0;
1040 int i;
1041
1042 for (i = 0; i < 8; ++i)
1043 {
1044 c = getc(fd);
1045 if (c == EOF) return -1;
1046 n = (n << 8) + c;
1047 }
1048 return n;
1049}
1050
Bram Moolenaar0a8fed62020-02-14 13:22:17 +01001051/*
1052 * Write time_T to file "fd" in 8 bytes.
1053 * Returns FAIL when the write failed.
1054 */
1055 int
1056put_time(FILE *fd, time_T the_time)
1057{
1058 char_u buf[8];
1059
1060 time_to_bytes(the_time, buf);
1061 return fwrite(buf, (size_t)8, (size_t)1, fd) == 1 ? OK : FAIL;
1062}
1063
1064/*
1065 * Write time_T to "buf[8]".
1066 */
1067 void
1068time_to_bytes(time_T the_time, char_u *buf)
1069{
1070 int c;
1071 int i;
1072 int bi = 0;
1073 time_T wtime = the_time;
1074
1075 // time_T can be up to 8 bytes in size, more than long_u, thus we
1076 // can't use put_bytes() here.
1077 // Another problem is that ">>" may do an arithmetic shift that keeps the
1078 // sign. This happens for large values of wtime. A cast to long_u may
1079 // truncate if time_T is 8 bytes. So only use a cast when it is 4 bytes,
1080 // it's safe to assume that long_u is 4 bytes or more and when using 8
1081 // bytes the top bit won't be set.
1082 for (i = 7; i >= 0; --i)
1083 {
1084 if (i + 1 > (int)sizeof(time_T))
1085 // ">>" doesn't work well when shifting more bits than avail
1086 buf[bi++] = 0;
1087 else
1088 {
K.Takatac351dc12022-01-24 11:24:08 +00001089# if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
Bram Moolenaar0a8fed62020-02-14 13:22:17 +01001090 c = (int)(wtime >> (i * 8));
K.Takatac351dc12022-01-24 11:24:08 +00001091# else
Bram Moolenaar0a8fed62020-02-14 13:22:17 +01001092 c = (int)((long_u)wtime >> (i * 8));
K.Takatac351dc12022-01-24 11:24:08 +00001093# endif
Bram Moolenaar0a8fed62020-02-14 13:22:17 +01001094 buf[bi++] = c;
1095 }
1096 }
1097}
1098
Bram Moolenaar0a8fed62020-02-14 13:22:17 +01001099#endif
1100
1101/*
1102 * Put timestamp "tt" in "buf[buflen]" in a nice format.
1103 */
1104 void
1105add_time(char_u *buf, size_t buflen, time_t tt)
1106{
1107#ifdef HAVE_STRFTIME
1108 struct tm tmval;
1109 struct tm *curtime;
1110
1111 if (vim_time() - tt >= 100)
1112 {
1113 curtime = vim_localtime(&tt, &tmval);
1114 if (vim_time() - tt < (60L * 60L * 12L))
1115 // within 12 hours
1116 (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
1117 else
1118 // longer ago
1119 (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime);
1120 }
1121 else
1122#endif
1123 {
1124 long seconds = (long)(vim_time() - tt);
1125
1126 vim_snprintf((char *)buf, buflen,
1127 NGETTEXT("%ld second ago", "%ld seconds ago", seconds),
1128 seconds);
1129 }
1130}