]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/cal.c
438e7f09b939f68cccef4fc36e5964a02083a5f4
[thirdparty/util-linux.git] / misc-utils / cal.c
1 /*
2 * Copyright (c) 1989, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kim Letkeman.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 /* 1999-02-01 Jean-Francois Bignolles: added option '-m' to display
38 * monday as the first day of the week.
39 * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
40 * - added Native Language Support
41 *
42 * 2000-09-01 Michael Charles Pruznick <dummy@netwiz.net>
43 * Added "-3" option to print prev/next month with current.
44 * Added overridable default MONTHS_IN_ROW and "-1" option to
45 * get traditional output when -3 is the default. I hope that
46 * enough people will like -3 as the default that one day the
47 * product can be shipped that way.
48 *
49 * 2001-05-07 Pablo Saratxaga <pablo@mandrakesoft.com>
50 * Fixed the bugs with multi-byte charset (zg: cjk, utf-8)
51 * displaying. made the 'month year' ("%s %d") header translatable
52 * so it can be adapted to conventions used by different languages
53 * added support to read "first_weekday" locale information
54 * still to do: support for 'cal_direction' (will require a major
55 * rewrite of the displaying) and proper handling of RTL scripts
56 */
57
58 #include <sys/types.h>
59
60 #include <ctype.h>
61 #include <getopt.h>
62 #include <stdint.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <time.h>
67 #include <unistd.h>
68 #include <errno.h>
69
70 #include "c.h"
71 #include "closestream.h"
72 #include "colors.h"
73 #include "nls.h"
74 #include "mbsalign.h"
75 #include "strutils.h"
76 #include "optutils.h"
77 #include "timeutils.h"
78
79 static int has_term = 0;
80 static const char *Senter = "", *Sexit = ""; /* enter and exit standout mode */
81
82 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
83 # if defined(HAVE_NCURSESW_TERM_H)
84 # include <ncursesw/term.h>
85 # elif defined(HAVE_NCURSES_TERM_H)
86 # include <ncurses/term.h>
87 # elif defined(HAVE_TERM_H)
88 # include <term.h>
89 # endif
90 #endif
91
92 static int setup_terminal(char *term
93 #if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
94 __attribute__((__unused__))
95 #endif
96 )
97 {
98 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
99 int ret;
100
101 if (setupterm(term, STDOUT_FILENO, &ret) != 0 || ret != 1)
102 return -1;
103 #endif
104 return 0;
105 }
106
107 static void my_putstring(char *s)
108 {
109 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
110 if (has_term)
111 putp(s);
112 else
113 #endif
114 fputs(s, stdout);
115 }
116
117 static const char *my_tgetstr(char *ss
118 #if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
119 __attribute__((__unused__))
120 #endif
121 )
122 {
123 const char *ret = NULL;
124
125 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
126 if (has_term)
127 ret = tigetstr(ss);
128 #endif
129 if (!ret || ret == (char *)-1)
130 return "";
131 return ret;
132 }
133
134 #include "widechar.h"
135
136 enum {
137 GREGORIAN = INT32_MIN,
138 ISO = INT32_MIN,
139 GB1752 = 1752,
140 DEFAULT_REFORM_YEAR = 1752,
141 JULIAN = INT32_MAX
142 };
143
144 enum {
145 SUNDAY = 0,
146 MONDAY,
147 TUESDAY,
148 WEDNESDAY,
149 THURSDAY,
150 FRIDAY,
151 SATURDAY,
152 DAYS_IN_WEEK,
153 NONEDAY
154 };
155
156 enum {
157 JANUARY = 1,
158 FEBRUARY,
159 MARCH,
160 APRIL,
161 MAY,
162 JUNE,
163 JULY,
164 AUGUST,
165 SEPTEMBER,
166 OCTOBER,
167 NOVEMBER,
168 DECEMBER
169 };
170
171 #define REFORMATION_MONTH SEPTEMBER
172 #define NUMBER_MISSING_DAYS 11 /* 11 day correction */
173 #define YDAY_AFTER_MISSING 258 /* 14th in Sep 1752 */
174
175 #define MONTHS_IN_YEAR DECEMBER
176 #define DAYS_IN_MONTH 31
177 #define MAXDAYS 42 /* slots in a month array */
178 #define SPACE -1 /* used in day array */
179
180 #define SMALLEST_YEAR 1
181
182 #define DAY_LEN 3 /* 3 spaces per day */
183 #define WEEK_LEN (DAYS_IN_WEEK * DAY_LEN)
184 #define MONTHS_IN_YEAR_ROW 3 /* month columns in year view */
185 #define WNUM_LEN 3
186
187 #define FMT_ST_CHARS 300 /* 90 suffices in most locales */
188
189 static const int days_in_month[2][13] = {
190 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
191 {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
192 };
193
194 enum {
195 WEEK_NUM_DISABLED = 0,
196 WEEK_NUM_MASK=0xff,
197 WEEK_NUM_ISO=0x100,
198 WEEK_NUM_US=0x200,
199 };
200
201 /* utf-8 can have up to 6 bytes per char; and an extra byte for ending \0 */
202 static char day_headings[(WEEK_LEN + 1) * 6 + 1];
203
204 struct cal_request {
205 int day;
206 int month;
207 int32_t year;
208 int week;
209 int start_month;
210 };
211
212 struct cal_control {
213 const char *full_month[MONTHS_IN_YEAR]; /* month names */
214 const char *abbr_month[MONTHS_IN_YEAR]; /* abbreviated month names */
215
216 int reform_year; /* Gregorian reform year */
217 int colormode; /* day and week number highlight */
218 int num_months; /* number of requested months */
219 int span_months; /* span the date */
220 int months_in_row; /* number of months horizontally in print out */
221 int weekstart; /* day the week starts, often Sun or Mon */
222 int weektype; /* WEEK_TYPE_{NONE,ISO,US} */
223 size_t day_width; /* day width in characters in printout */
224 size_t week_width; /* 7 * day_width + possible week num */
225 int gutter_width; /* spaces in between horizontal month outputs */
226 struct cal_request req; /* the times user is interested */
227 unsigned int julian:1, /* julian output */
228 header_year:1, /* print year number */
229 header_hint:1; /* does month name + year need two lines to fit */
230 };
231
232 struct cal_month {
233 int days[MAXDAYS]; /* the day numbers, or SPACE */
234 int weeks[MAXDAYS / DAYS_IN_WEEK];
235 int month;
236 int32_t year;
237 struct cal_month *next;
238 };
239
240 /* function prototypes */
241 static int leap_year(const struct cal_control *ctl, int32_t year);
242 static int monthname_to_number(struct cal_control *ctl, const char *name);
243 static void headers_init(struct cal_control *ctl);
244 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl);
245 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl);
246 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl);
247 static void monthly(const struct cal_control *ctl);
248 static void yearly(const struct cal_control *ctl);
249 static int day_in_year(const struct cal_control *ctl, int day,
250 int month, int32_t year);
251 static int day_in_week(const struct cal_control *ctl, int day,
252 int month, int32_t year);
253 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl);
254 static int week_to_day(const struct cal_control *ctl);
255 static int center_str(const char *src, char *dest, size_t dest_size, size_t width);
256 static void center(const char *str, size_t len, int separate);
257 static int parse_reform_year(const char *reform_year);
258 static void __attribute__((__noreturn__)) usage(void);
259
260 int main(int argc, char **argv)
261 {
262 struct tm *local_time;
263 char *term;
264 time_t now;
265 int ch = 0, yflag = 0, Yflag = 0;
266
267 static struct cal_control ctl = {
268 .reform_year = DEFAULT_REFORM_YEAR,
269 .weekstart = SUNDAY,
270 .num_months = 1, /* default is "cal -1" */
271 .span_months = 0,
272 .colormode = UL_COLORMODE_UNDEF,
273 .weektype = WEEK_NUM_DISABLED,
274 .day_width = DAY_LEN,
275 .gutter_width = 2,
276 .req.day = 0,
277 .req.month = 0
278 };
279
280 enum {
281 OPT_COLOR = CHAR_MAX + 1,
282 OPT_ISO,
283 OPT_REFORM
284 };
285
286 static const struct option longopts[] = {
287 {"one", no_argument, NULL, '1'},
288 {"three", no_argument, NULL, '3'},
289 {"sunday", no_argument, NULL, 's'},
290 {"monday", no_argument, NULL, 'm'},
291 {"julian", no_argument, NULL, 'j'},
292 {"months", required_argument, NULL, 'n'},
293 {"span", no_argument, NULL, 'S'},
294 {"year", no_argument, NULL, 'y'},
295 {"week", optional_argument, NULL, 'w'},
296 {"color", optional_argument, NULL, OPT_COLOR},
297 {"reform", required_argument, NULL, OPT_REFORM},
298 {"iso", no_argument, NULL, OPT_ISO},
299 {"version", no_argument, NULL, 'V'},
300 {"twelve", no_argument, NULL, 'Y'},
301 {"help", no_argument, NULL, 'h'},
302 {NULL, 0, NULL, 0}
303 };
304
305 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
306 { 'Y','n','y' },
307 { 0 }
308 };
309 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
310
311 setlocale(LC_ALL, "");
312 bindtextdomain(PACKAGE, LOCALEDIR);
313 textdomain(PACKAGE);
314 atexit(close_stdout);
315
316 term = getenv("TERM");
317 if (term) {
318 has_term = setup_terminal(term) == 0;
319 if (has_term) {
320 Senter = my_tgetstr("smso");
321 Sexit = my_tgetstr("rmso");
322 }
323 }
324
325 /*
326 * The traditional Unix cal utility starts the week at Sunday,
327 * while ISO 8601 starts at Monday. We read the start day from
328 * the locale database, which can be overridden with the
329 * -s (Sunday) or -m (Monday) options.
330 */
331 #if HAVE_DECL__NL_TIME_WEEK_1STDAY
332 /*
333 * You need to use 2 locale variables to get the first day of the week.
334 * This is needed to support first_weekday=2 and first_workday=1 for
335 * the rare case where working days span across 2 weeks.
336 * This shell script shows the combinations and calculations involved:
337 *
338 * for LANG in en_US ru_RU fr_FR csb_PL POSIX; do
339 * printf "%s:\t%s + %s -1 = " $LANG $(locale week-1stday first_weekday)
340 * date -d"$(locale week-1stday) +$(($(locale first_weekday)-1))day" +%w
341 * done
342 *
343 * en_US: 19971130 + 1 -1 = 0 #0 = sunday
344 * ru_RU: 19971130 + 2 -1 = 1
345 * fr_FR: 19971201 + 1 -1 = 1
346 * csb_PL: 19971201 + 2 -1 = 2
347 * POSIX: 19971201 + 7 -1 = 0
348 */
349 {
350 int wfd;
351 union { unsigned int word; char *string; } val;
352 val.string = nl_langinfo(_NL_TIME_WEEK_1STDAY);
353
354 wfd = val.word;
355 wfd = day_in_week(&ctl, wfd % 100, (wfd / 100) % 100,
356 wfd / (100 * 100));
357 ctl.weekstart = (wfd + *nl_langinfo(_NL_TIME_FIRST_WEEKDAY) - 1) % DAYS_IN_WEEK;
358 }
359 #endif
360 while ((ch = getopt_long(argc, argv, "13mjn:sSywYVh", longopts, NULL)) != -1) {
361
362 err_exclusive_options(ch, longopts, excl, excl_st);
363
364 switch(ch) {
365 case '1':
366 /* default */
367 break;
368 case '3':
369 ctl.num_months = 3;
370 ctl.span_months = 1;
371 ctl.months_in_row = 3;
372 break;
373 case 's':
374 ctl.weekstart = SUNDAY; /* default */
375 break;
376 case 'm':
377 ctl.weekstart = MONDAY;
378 break;
379 case 'j':
380 ctl.julian = 1;
381 ctl.day_width = DAY_LEN + 1;
382 break;
383 case 'y':
384 yflag = 1;
385 break;
386 case 'Y':
387 Yflag = 1;
388 break;
389 case 'n':
390 ctl.num_months = strtou32_or_err(optarg,
391 _("invalid month argument"));
392 break;
393 case 'S':
394 ctl.span_months = 1;
395 break;
396 case 'w':
397 if (optarg) {
398 ctl.req.week = strtos32_or_err(optarg,
399 _("invalid week argument"));
400 if (ctl.req.week < 1 || 54 < ctl.req.week)
401 errx(EXIT_FAILURE,_("illegal week value: use 1-54"));
402 }
403 ctl.weektype = WEEK_NUM_US; /* default per weekstart */
404 break;
405 case OPT_COLOR:
406 ctl.colormode = UL_COLORMODE_AUTO;
407 if (optarg)
408 ctl.colormode = colormode_or_err(optarg,
409 _("unsupported color mode"));
410 break;
411 case OPT_REFORM:
412 ctl.reform_year = parse_reform_year(optarg);
413 break;
414 case OPT_ISO:
415 ctl.reform_year = ISO;
416 break;
417 case 'V':
418 printf(UTIL_LINUX_VERSION);
419 return EXIT_SUCCESS;
420 case 'h':
421 usage();
422 default:
423 errtryhelp(EXIT_FAILURE);
424 }
425 }
426
427 argc -= optind;
428 argv += optind;
429
430 if (ctl.weektype) {
431 ctl.weektype = ctl.req.week & WEEK_NUM_MASK;
432 ctl.weektype |= (ctl.weekstart == MONDAY ? WEEK_NUM_ISO : WEEK_NUM_US);
433 ctl.week_width = (ctl.day_width * DAYS_IN_WEEK) + WNUM_LEN;
434 } else
435 ctl.week_width = ctl.day_width * DAYS_IN_WEEK;
436
437 if (argc == 1 && !isdigit_string(*argv)) {
438 usec_t x;
439 /* cal <timestamp> */
440 if (parse_timestamp(*argv, &x) == 0)
441 now = (time_t) (x / 1000000);
442 /* cal <monthname> */
443 else if ((ctl.req.month = monthname_to_number(&ctl, *argv)) > 0)
444 time(&now); /* this year */
445 else
446 errx(EXIT_FAILURE, _("failed to parse timestamp or unknown month name: %s"), *argv);
447 argc = 0;
448 } else
449 time(&now);
450
451 local_time = localtime(&now);
452
453 switch(argc) {
454 case 3:
455 ctl.req.day = strtos32_or_err(*argv++, _("illegal day value"));
456 if (ctl.req.day < 1 || DAYS_IN_MONTH < ctl.req.day)
457 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), DAYS_IN_MONTH);
458 /* fallthrough */
459 case 2:
460 if (isdigit(**argv))
461 ctl.req.month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
462 else {
463 ctl.req.month = monthname_to_number(&ctl, *argv);
464 if (ctl.req.month < 0)
465 errx(EXIT_FAILURE, _("unknown month name: %s"), *argv);
466 argv++;
467 }
468 if (ctl.req.month < 1 || MONTHS_IN_YEAR < ctl.req.month)
469 errx(EXIT_FAILURE, _("illegal month value: use 1-12"));
470 /* fallthrough */
471 case 1:
472 ctl.req.year = strtos32_or_err(*argv++, _("illegal year value"));
473 if (ctl.req.year < SMALLEST_YEAR)
474 errx(EXIT_FAILURE, _("illegal year value: use positive integer"));
475 if (ctl.req.year == JULIAN)
476 errx(EXIT_FAILURE, _("illegal year value"));
477 if (ctl.req.day) {
478 int dm = days_in_month[leap_year(&ctl, ctl.req.year)]
479 [ctl.req.month];
480 if (ctl.req.day > dm)
481 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), dm);
482 ctl.req.day = day_in_year(&ctl, ctl.req.day,
483 ctl.req.month, ctl.req.year);
484 } else if ((int32_t) (local_time->tm_year + 1900) == ctl.req.year) {
485 ctl.req.day = local_time->tm_yday + 1;
486 }
487 if (!ctl.req.month && !ctl.req.week) {
488 ctl.req.month = local_time->tm_mon + 1;
489 yflag = 1;
490 }
491 break;
492 case 0:
493 ctl.req.day = local_time->tm_yday + 1;
494 ctl.req.year = local_time->tm_year + 1900;
495 if (!ctl.req.month)
496 ctl.req.month = local_time->tm_mon + 1;
497 break;
498 default:
499 warnx(_("bad usage"));
500 errtryhelp(EXIT_FAILURE);
501 }
502
503 if (0 < ctl.req.week) {
504 int yday = week_to_day(&ctl);
505 int leap = leap_year(&ctl, ctl.req.year);
506 int m = 1;
507
508 if (yday < 1)
509 errx(EXIT_FAILURE, _("illegal week value: year %d "
510 "doesn't have week %d"),
511 ctl.req.year, ctl.req.week);
512 while (m <= DECEMBER && yday > days_in_month[leap][m])
513 yday -= days_in_month[leap][m++];
514 if (DECEMBER < m && ctl.weektype & WEEK_NUM_ISO) {
515 /* In some years (e.g. 2010 in ISO mode) it's possible
516 * to have a remnant of week 53 starting the year yet
517 * the year in question ends during 52, in this case
518 * we're assuming that early remnant is being referred
519 * to if 53 is given as argument. */
520 if (ctl.req.week != week_number(31, DECEMBER, ctl.req.year - 1, &ctl))
521 errx(EXIT_FAILURE,
522 _("illegal week value: year %d "
523 "doesn't have week %d"),
524 ctl.req.year, ctl.req.week);
525 }
526 if (!ctl.req.month)
527 ctl.req.month = MONTHS_IN_YEAR < m ? 1 : m;
528 }
529
530 headers_init(&ctl);
531
532 if (!colors_init(ctl.colormode, "cal")) {
533 ctl.req.day = 0;
534 ctl.weektype &= ~WEEK_NUM_MASK;
535 }
536
537 if (yflag || Yflag) {
538 ctl.gutter_width = 3;
539 ctl.num_months = MONTHS_IN_YEAR;
540 if (yflag) {
541 ctl.req.start_month = 1; /* start from Jan */
542 ctl.header_year = 1; /* print year number */
543 }
544 }
545
546 if (ctl.num_months > 1 && ctl.months_in_row == 0)
547 ctl.months_in_row = ctl.julian ? MONTHS_IN_YEAR_ROW - 1 :
548 MONTHS_IN_YEAR_ROW;
549 else if (!ctl.months_in_row)
550 ctl.months_in_row = 1;
551
552 if (yflag || Yflag)
553 yearly(&ctl);
554 else
555 monthly(&ctl);
556
557 return EXIT_SUCCESS;
558 }
559
560 /* leap year -- account for gregorian reformation in 1752 */
561 static int leap_year(const struct cal_control *ctl, int32_t year)
562 {
563 if (year <= ctl->reform_year)
564 return !(year % 4);
565 else
566 return ( !(year % 4) && (year % 100) ) || !(year % 400);
567 }
568
569 static void init_monthnames(struct cal_control *ctl)
570 {
571 size_t i;
572
573 if (ctl->full_month[0] != NULL)
574 return; /* already initialized */
575
576 for (i = 0; i < MONTHS_IN_YEAR; i++)
577 ctl->full_month[i] = nl_langinfo(ALTMON_1 + i);
578 }
579
580 static void init_abbr_monthnames(struct cal_control *ctl)
581 {
582 size_t i;
583
584 if (ctl->abbr_month[0] != NULL)
585 return; /* already initialized */
586
587 for (i = 0; i < MONTHS_IN_YEAR; i++)
588 ctl->abbr_month[i] = nl_langinfo(_NL_ABALTMON_1 + i);
589 }
590
591 static int monthname_to_number(struct cal_control *ctl, const char *name)
592 {
593 size_t i;
594
595 init_monthnames(ctl);
596 for (i = 0; i < MONTHS_IN_YEAR; i++)
597 if (strcasecmp(ctl->full_month[i], name) == 0)
598 return i + 1;
599
600 init_abbr_monthnames(ctl);
601 for (i = 0; i < MONTHS_IN_YEAR; i++)
602 if (strcasecmp(ctl->abbr_month[i], name) == 0)
603 return i + 1;
604
605 return -EINVAL;
606 }
607
608 static void headers_init(struct cal_control *ctl)
609 {
610 size_t i, wd;
611 char *cur_dh = day_headings;
612 char tmp[FMT_ST_CHARS];
613 int year_len;
614
615 year_len = snprintf(tmp, sizeof(tmp), "%04d", ctl->req.year);
616
617 if (year_len < 0 || (size_t)year_len >= sizeof(tmp)) {
618 /* XXX impossible error */
619 return;
620 }
621
622 for (i = 0; i < DAYS_IN_WEEK; i++) {
623 size_t space_left;
624 wd = (i + ctl->weekstart) % DAYS_IN_WEEK;
625
626 if (i)
627 strcat(cur_dh++, " ");
628 space_left = sizeof(day_headings) - (cur_dh - day_headings);
629
630 if (space_left <= (ctl->day_width - 1))
631 break;
632 cur_dh += center_str(nl_langinfo(ABDAY_1 + wd), cur_dh,
633 space_left, ctl->day_width - 1);
634 }
635
636 init_monthnames(ctl);
637
638 for (i = 0; i < MONTHS_IN_YEAR; i++) {
639 /* The +1 after year_len is space in between month and year. */
640 if (ctl->week_width < strlen(ctl->full_month[i]) + year_len + 1)
641 ctl->header_hint = 1;
642 }
643 }
644
645 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl)
646 {
647 int first_week_day = day_in_week(ctl, 1, month->month, month->year);
648 int month_days;
649 int i, j, weeklines = 0;
650
651 if (ctl->julian)
652 j = day_in_year(ctl, 1, month->month, month->year);
653 else
654 j = 1;
655 month_days = j + days_in_month[leap_year(ctl, month->year)][month->month];
656
657 /* True when Sunday is not first day in the output week. */
658 if (ctl->weekstart) {
659 first_week_day -= ctl->weekstart;
660 if (first_week_day < 0)
661 first_week_day = DAYS_IN_WEEK - ctl->weekstart;
662 month_days += ctl->weekstart - 1;
663 }
664
665 /* Fill day array. */
666 for (i = 0; i < MAXDAYS; i++) {
667 if (0 < first_week_day) {
668 month->days[i] = SPACE;
669 first_week_day--;
670 continue;
671 }
672 if (j < month_days) {
673 if (month->year == ctl->reform_year &&
674 month->month == REFORMATION_MONTH &&
675 (j == 3 || j == 247))
676 j += NUMBER_MISSING_DAYS;
677 month->days[i] = j;
678 j++;
679 continue;
680 }
681 month->days[i] = SPACE;
682 weeklines++;
683 }
684
685 /* Add week numbers */
686 if (ctl->weektype) {
687 int weeknum = week_number(1, month->month, month->year, ctl);
688 weeklines = MAXDAYS / DAYS_IN_WEEK - weeklines / DAYS_IN_WEEK;
689 for (i = 0; i < MAXDAYS / DAYS_IN_WEEK; i++) {
690 if (0 < weeklines) {
691 if (52 < weeknum)
692 weeknum = week_number(month->days[i * DAYS_IN_WEEK], month->month, month->year, ctl);
693 month->weeks[i] = weeknum++;
694 } else
695 month->weeks[i] = SPACE;
696 weeklines--;
697 }
698 }
699 }
700
701 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl)
702 {
703 char out[FMT_ST_CHARS];
704 struct cal_month *i;
705
706 if (ctl->header_hint || ctl->header_year) {
707 for (i = month; i; i = i->next) {
708 sprintf(out, _("%s"), ctl->full_month[i->month - 1]);
709 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
710 }
711 if (!ctl->header_year) {
712 my_putstring("\n");
713 for (i = month; i; i = i->next) {
714 sprintf(out, _("%04d"), i->year);
715 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
716 }
717 }
718 } else {
719 for (i = month; i; i = i->next) {
720 sprintf(out, _("%s %04d"), ctl->full_month[i->month - 1], i->year);
721 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
722 }
723 }
724 my_putstring("\n");
725 for (i = month; i; i = i->next) {
726 if (ctl->weektype) {
727 if (ctl->julian)
728 sprintf(out, "%*s%s", (int)ctl->day_width - 1, "", day_headings);
729 else
730 sprintf(out, "%*s%s", (int)ctl->day_width, "", day_headings);
731 my_putstring(out);
732 } else
733 my_putstring(day_headings);
734 if (i->next != NULL) {
735 sprintf(out, "%*s", ctl->gutter_width, "");
736 my_putstring(out);
737 }
738 }
739 my_putstring("\n");
740 }
741
742 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl)
743 {
744 char out[FMT_ST_CHARS];
745 int reqday, week_line, d;
746 int skip;
747 struct cal_month *i;
748
749 for (week_line = 0; week_line < MAXDAYS / DAYS_IN_WEEK; week_line++) {
750 for (i = month; i; i = i->next) {
751 /* Determine the day that should be highlighted. */
752 reqday = 0;
753 if (i->month == ctl->req.month && i->year == ctl->req.year) {
754 if (ctl->julian)
755 reqday = ctl->req.day;
756 else
757 reqday = ctl->req.day + 1 -
758 day_in_year(ctl, 1, i->month,
759 i->year);
760 }
761
762 if (ctl->weektype) {
763 if (0 < i->weeks[week_line]) {
764 if ((ctl->weektype & WEEK_NUM_MASK) ==
765 i->weeks[week_line])
766 sprintf(out, "%s%2d%s", Senter, i->weeks[week_line],
767 Sexit);
768 else
769 sprintf(out, "%2d", i->weeks[week_line]);
770 } else
771 sprintf(out, "%2s", "");
772 my_putstring(out);
773 skip = ctl->day_width;
774 } else
775 /* First day of the week is one char narrower than the other days,
776 * unless week number is printed. */
777 skip = ctl->day_width - 1;
778
779 for (d = DAYS_IN_WEEK * week_line;
780 d < DAYS_IN_WEEK * week_line + DAYS_IN_WEEK; d++) {
781 if (0 < i->days[d]) {
782 if (reqday == i->days[d])
783 sprintf(out, "%*s%s%*d%s", skip - (ctl->julian ? 3 : 2),
784 "", Senter, (ctl->julian ? 3 : 2),
785 i->days[d], Sexit);
786 else
787 sprintf(out, "%*d", skip, i->days[d]);
788 } else
789 sprintf(out, "%*s", skip, "");
790 my_putstring(out);
791 if (skip < (int)ctl->day_width)
792 skip++;
793 }
794 if (i->next != NULL) {
795 sprintf(out, "%*s", ctl->gutter_width, "");
796 my_putstring(out);
797 }
798 }
799 if (i == NULL) {
800 int extra = ctl->num_months > 3 ? 0 : 1;
801 sprintf(out, "%*s\n", ctl->gutter_width - extra, "");
802 my_putstring(out);
803 }
804 }
805 }
806
807 static void monthly(const struct cal_control *ctl)
808 {
809 struct cal_month m1,m2,m3, *m;
810 int i, rows, new_month, month = ctl->req.start_month ? ctl->req.start_month : ctl->req.month;
811 int32_t year = ctl->req.year;
812
813 /* cal -3, cal -Y --span, etc. */
814 if (ctl->span_months) {
815 new_month = month - ctl->num_months / 2;
816 if (new_month < 1) {
817 month = new_month + MONTHS_IN_YEAR;
818 year--;
819 }
820 else
821 month = new_month;
822 }
823
824 m1.next = (ctl->months_in_row > 1) ? &m2 : NULL;
825 m2.next = (ctl->months_in_row > 2) ? &m3 : NULL;
826 m3.next = NULL;
827
828 rows = (ctl->num_months - 1) / ctl->months_in_row;
829 for (i = 0; i < rows + 1 ; i++){
830 if (i == rows){
831 switch (ctl->num_months % ctl->months_in_row){
832 case 1:
833 m1.next = NULL;
834 /* fallthrough */
835 case 2:
836 m2.next = NULL;
837 /* fallthrough */
838 }
839 }
840 for (m = &m1; m; m = m->next){
841 m->month = month++;
842 m->year = year;
843 if (MONTHS_IN_YEAR < month) {
844 year++;
845 month = 1;
846 }
847 cal_fill_month(m, ctl);
848 }
849 cal_output_header(&m1, ctl);
850 cal_output_months(&m1, ctl);
851 }
852 }
853
854 static void yearly(const struct cal_control *ctl)
855 {
856 char out[FMT_ST_CHARS];
857 int year_width = 0;
858
859 year_width += (ctl->week_width + 1) * (ctl->julian ? 2 : 3);
860 if (ctl->julian)
861 year_width--;
862
863 if (ctl->header_year) {
864 sprintf(out, "%04d", ctl->req.year);
865 center(out, year_width, 0);
866 my_putstring("\n\n");
867 }
868 monthly(ctl);
869
870 /* Is empty line at the end year output really needed? */
871 my_putstring("\n");
872 }
873
874 /*
875 * day_in_year --
876 * return the 1 based day number within the year
877 */
878 static int day_in_year(const struct cal_control *ctl,
879 int day, int month, int32_t year)
880 {
881 int i, leap;
882
883 leap = leap_year(ctl, year);
884 for (i = 1; i < month; i++)
885 day += days_in_month[leap][i];
886 return day;
887 }
888
889 /*
890 * day_in_week
891 * return the 0 based day number for any date from 1 Jan. 1 to
892 * 31 Dec. 9999. Assumes the Gregorian reformation eliminates
893 * 3 Sep. 1752 through 13 Sep. 1752, and returns invalid weekday
894 * during the period of 11 days.
895 */
896 static int day_in_week(const struct cal_control *ctl, int day,
897 int month, int32_t year)
898 {
899 /*
900 * The magic constants in the reform[] array are, in a simplified
901 * sense, the remaining days after slicing into one week periods the total
902 * days from the beginning of the year to the target month. That is,
903 * weeks + reform[] days gets us to the target month. The exception is,
904 * that for the months past February 'DOY - 1' must be used.
905 *
906 * DoY (Day of Year): total days to the target month
907 *
908 * Month 1 2 3 4 5 6 7 8 9 10 11 12
909 * DoY 0 31 59 90 120 151 181 212 243 273 304 334
910 * DoY % 7 0 3
911 * DoY - 1 % 7 - -- 2 5 0 3 5 1 4 6 2 4
912 * reform[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
913 *
914 * Note: these calculations are for non leap years.
915 */
916 static const int reform[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
917 static const int old[] = { 5, 1, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2 };
918
919 if (year != ctl->reform_year + 1)
920 year -= month < MARCH;
921 else
922 year -= (month < MARCH) + 14;
923 if (ctl->reform_year < year
924 || (year == ctl->reform_year && REFORMATION_MONTH < month)
925 || (year == ctl->reform_year
926 && month == REFORMATION_MONTH && 13 < day)) {
927 return ((int64_t) year + (year / 4)
928 - (year / 100) + (year / 400)
929 + reform[month - 1] + day) % DAYS_IN_WEEK;
930 }
931 if (year < ctl->reform_year
932 || (year == ctl->reform_year && month < REFORMATION_MONTH)
933 || (year == ctl->reform_year && month == REFORMATION_MONTH && day < 3))
934 return ((int64_t) year + year / 4 + old[month - 1] + day)
935 % DAYS_IN_WEEK;
936 return NONEDAY;
937 }
938
939 /*
940 * week_number
941 * return the week number of a given date, 1..54.
942 * Supports ISO-8601 and North American modes.
943 * Day may be given as Julian day of the year mode, in which
944 * case the month is disregarded entirely.
945 */
946 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl)
947 {
948 int fday = 0, yday;
949 const int wday = day_in_week(ctl, 1, JANUARY, year);
950
951 if (ctl->weektype & WEEK_NUM_ISO)
952 fday = wday + (wday >= FRIDAY ? -2 : 5);
953 else {
954 /* WEEK_NUM_US: Jan 1 is always First week, that may
955 * begin previous year. That means there is very seldom
956 * more than 52 weeks, */
957 fday = wday + 6;
958 }
959 /* For julian dates the month can be set to 1, the global julian
960 * variable cannot be relied upon here, because we may recurse
961 * internally for 31.12. which would not work. */
962 if (day > DAYS_IN_MONTH)
963 month = JANUARY;
964
965 yday = day_in_year(ctl, day, month, year);
966 if (year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
967 fday -= NUMBER_MISSING_DAYS;
968
969 /* Last year is last year */
970 if (yday + fday < DAYS_IN_WEEK)
971 return week_number(31, DECEMBER, year - 1, ctl);
972
973 /* Or it could be part of the next year. The reformation year had less
974 * days than 365 making this check invalid, but reformation year ended
975 * on Sunday and in week 51, so it's ok here. */
976 if (ctl->weektype == WEEK_NUM_ISO && yday >= 363
977 && day_in_week(ctl, day, month, year) >= MONDAY
978 && day_in_week(ctl, day, month, year) <= WEDNESDAY
979 && day_in_week(ctl, 31, DECEMBER, year) >= MONDAY
980 && day_in_week(ctl, 31, DECEMBER, year) <= WEDNESDAY)
981 return week_number(1, JANUARY, year + 1, ctl);
982
983 return (yday + fday) / DAYS_IN_WEEK;
984 }
985
986 /*
987 * week_to_day
988 * return the yday of the first day in a given week inside
989 * the given year. This may be something other than Monday
990 * for ISO-8601 modes. For North American numbering this
991 * always returns a Sunday.
992 */
993 static int week_to_day(const struct cal_control *ctl)
994 {
995 int yday, wday;
996
997 wday = day_in_week(ctl, 1, JANUARY, ctl->req.year);
998 yday = ctl->req.week * DAYS_IN_WEEK - wday;
999
1000 if (ctl->req.year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
1001 yday += NUMBER_MISSING_DAYS;
1002
1003 if (ctl->weektype & WEEK_NUM_ISO)
1004 yday -= (wday >= FRIDAY ? -2 : 5);
1005 else
1006 yday -= 6; /* WEEK_NUM_US */
1007 if (yday <= 0)
1008 return 1;
1009
1010 return yday;
1011 }
1012
1013 /*
1014 * Center string, handling multibyte characters appropriately.
1015 * In addition if the string is too large for the width it's truncated.
1016 * The number of trailing spaces may be 1 less than the number of leading spaces.
1017 */
1018 static int center_str(const char* src, char* dest,
1019 size_t dest_size, size_t width)
1020 {
1021 return mbsalign(src, dest, dest_size, &width,
1022 MBS_ALIGN_CENTER, MBA_UNIBYTE_FALLBACK);
1023 }
1024
1025 static void center(const char *str, size_t len, int separate)
1026 {
1027 char lineout[FMT_ST_CHARS];
1028
1029 center_str(str, lineout, ARRAY_SIZE(lineout), len);
1030 my_putstring(lineout);
1031
1032 if (separate) {
1033 snprintf(lineout, sizeof(lineout), "%*s", separate, "");
1034 my_putstring(lineout);
1035 }
1036 }
1037
1038 static int parse_reform_year(const char *reform_year)
1039 {
1040 size_t i;
1041
1042 struct reform {
1043 char *name;
1044 int val;
1045 };
1046
1047 struct reform years[] = {
1048 {"gregorian", GREGORIAN},
1049 {"iso", ISO},
1050 {"1752", GB1752},
1051 {"julian", JULIAN},
1052 };
1053
1054 for (i = 0; i < ARRAY_SIZE(years); i++) {
1055 if (strcasecmp(reform_year, years[i].name) == 0) {
1056 return years[i].val;
1057 }
1058 }
1059 errx(EXIT_FAILURE, "invalid --reform value: '%s'", reform_year);
1060 }
1061
1062 static void __attribute__((__noreturn__)) usage(void)
1063 {
1064 FILE *out = stdout;
1065 fputs(USAGE_HEADER, out);
1066 fprintf(out, _(" %s [options] [[[day] month] year]\n"), program_invocation_short_name);
1067 fprintf(out, _(" %s [options] <timestamp|monthname>\n"), program_invocation_short_name);
1068
1069 fputs(USAGE_SEPARATOR, out);
1070 fputs(_("Display a calendar, or some part of it.\n"), out);
1071 fputs(_("Without any arguments, display the current month.\n"), out);
1072
1073 fputs(USAGE_OPTIONS, out);
1074 fputs(_(" -1, --one show only a single month (default)\n"), out);
1075 fputs(_(" -3, --three show three months spanning the date\n"), out);
1076 fputs(_(" -n, --months <num> show num months starting with date's month\n"), out);
1077 fputs(_(" -S, --span span the date when displaying multiple months\n"), out);
1078 fputs(_(" -s, --sunday Sunday as first day of week\n"), out);
1079 fputs(_(" -m, --monday Monday as first day of week\n"), out);
1080 fputs(_(" -j, --julian use day-of-year for all calendars\n"), out);
1081 fputs(_(" --reform <val> Gregorian reform date (1752|gregorian|iso|julian)\n"), out);
1082 fputs(_(" --iso alias for --reform=iso\n"), out);
1083 fputs(_(" -y, --year show the whole year\n"), out);
1084 fputs(_(" -Y, --twelve show the next twelve months\n"), out);
1085 fputs(_(" -w, --week[=<num>] show US or ISO-8601 week numbers\n"), out);
1086 fputs(_(" --color[=<when>] colorize messages (auto, always or never)\n"), out);
1087 fprintf(out,
1088 " %s\n", USAGE_COLORS_DEFAULT);
1089
1090 fputs(USAGE_SEPARATOR, out);
1091 printf(USAGE_HELP_OPTIONS(23));
1092 printf(USAGE_MAN_TAIL("cal(1)"));
1093
1094 exit(EXIT_SUCCESS);
1095 }