]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/cal.c
fix compiler warnings
[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 #include "ttyutils.h"
79
80 #define DOY_MONTH_WIDTH 27 /* -j month width */
81 #define DOM_MONTH_WIDTH 20 /* month width */
82
83 static int has_term = 0;
84 static const char *Senter = "", *Sexit = ""; /* enter and exit standout mode */
85
86 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
87 # if defined(HAVE_NCURSESW_TERM_H)
88 # include <ncursesw/term.h>
89 # elif defined(HAVE_NCURSES_TERM_H)
90 # include <ncurses/term.h>
91 # elif defined(HAVE_TERM_H)
92 # include <term.h>
93 # endif
94 #endif
95
96 static int setup_terminal(char *term
97 #if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
98 __attribute__((__unused__))
99 #endif
100 )
101 {
102 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
103 int ret;
104
105 if (setupterm(term, STDOUT_FILENO, &ret) != 0 || ret != 1)
106 return -1;
107 #endif
108 return 0;
109 }
110
111 static const char *my_tgetstr(char *ss
112 #if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
113 __attribute__((__unused__))
114 #endif
115 )
116 {
117 const char *ret = NULL;
118
119 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
120 if (has_term)
121 ret = tigetstr(ss);
122 #endif
123 if (!ret || ret == (char *)-1)
124 return "";
125 return ret;
126 }
127
128 #include "widechar.h"
129
130 enum {
131 GREGORIAN = INT32_MIN,
132 ISO = INT32_MIN,
133 GB1752 = 1752,
134 DEFAULT_REFORM_YEAR = 1752,
135 JULIAN = INT32_MAX
136 };
137
138 enum {
139 SUNDAY = 0,
140 MONDAY,
141 TUESDAY,
142 WEDNESDAY,
143 THURSDAY,
144 FRIDAY,
145 SATURDAY,
146 DAYS_IN_WEEK,
147 NONEDAY
148 };
149
150 enum {
151 JANUARY = 1,
152 FEBRUARY,
153 MARCH,
154 APRIL,
155 MAY,
156 JUNE,
157 JULY,
158 AUGUST,
159 SEPTEMBER,
160 OCTOBER,
161 NOVEMBER,
162 DECEMBER
163 };
164
165 #define REFORMATION_MONTH SEPTEMBER
166 #define NUMBER_MISSING_DAYS 11 /* 11 day correction */
167 #define YDAY_AFTER_MISSING 258 /* 14th in Sep 1752 */
168
169 #define MONTHS_IN_YEAR DECEMBER
170 #define DAYS_IN_MONTH 31
171 #define MAXDAYS 42 /* slots in a month array */
172 #define SPACE -1 /* used in day array */
173
174 #define SMALLEST_YEAR 1
175
176 #define DAY_LEN 3 /* 3 spaces per day */
177 #define WEEK_LEN (DAYS_IN_WEEK * DAY_LEN)
178 #define MONTHS_IN_YEAR_ROW 3 /* month columns in year view */
179 #define WNUM_LEN 3
180
181 #define FMT_ST_CHARS 300 /* 90 suffices in most locales */
182
183 static const int days_in_month[2][13] = {
184 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
185 {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
186 };
187
188 enum {
189 WEEK_NUM_DISABLED = 0,
190 WEEK_NUM_MASK=0xff,
191 WEEK_NUM_ISO=0x100,
192 WEEK_NUM_US=0x200,
193 };
194
195 /* utf-8 can have up to 6 bytes per char; and an extra byte for ending \0 */
196 static char day_headings[(WEEK_LEN + 1) * 6 + 1];
197
198 struct cal_request {
199 int day;
200 int month;
201 int32_t year;
202 int week;
203 int start_month;
204 };
205
206 struct cal_control {
207 const char *full_month[MONTHS_IN_YEAR]; /* month names */
208 const char *abbr_month[MONTHS_IN_YEAR]; /* abbreviated month names */
209 const char *weekdays[DAYS_IN_WEEK]; /* day names */
210
211 int reform_year; /* Gregorian reform year */
212 int colormode; /* day and week number highlight */
213 int num_months; /* number of requested months */
214 int span_months; /* span the date */
215 int months_in_row; /* number of months horizontally in print out */
216 int weekstart; /* day the week starts, often Sun or Mon */
217 int weektype; /* WEEK_TYPE_{NONE,ISO,US} */
218 size_t day_width; /* day width in characters in printout */
219 size_t week_width; /* 7 * day_width + possible week num */
220 size_t month_width; /* width of a month (vertical mode) */
221 int gutter_width; /* spaces in between horizontal month outputs */
222 struct cal_request req; /* the times user is interested */
223 unsigned int julian:1, /* julian output */
224 header_year:1, /* print year number */
225 header_hint:1, /* does month name + year need two lines to fit */
226 vertical:1; /* display the output in vertical */
227 };
228
229 struct cal_month {
230 int days[MAXDAYS]; /* the day numbers, or SPACE */
231 int weeks[MAXDAYS / DAYS_IN_WEEK];
232 int month;
233 int32_t year;
234 struct cal_month *next;
235 };
236 /* function prototypes */
237 static int leap_year(const struct cal_control *ctl, int32_t year);
238 static int monthname_to_number(struct cal_control *ctl, const char *name);
239 static void weekdays_init(struct cal_control *ctl);
240 static void headers_init(struct cal_control *ctl);
241 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl);
242 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl);
243 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl);
244 static void cal_vert_output_months(struct cal_month *month, const struct cal_control *ctl);
245 static void monthly(const struct cal_control *ctl);
246 static void yearly(const struct cal_control *ctl);
247 static int day_in_year(const struct cal_control *ctl, int day,
248 int month, int32_t year);
249 static int day_in_week(const struct cal_control *ctl, int day,
250 int month, int32_t year);
251 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl);
252 static int week_to_day(const struct cal_control *ctl);
253 static int center_str(const char *src, char *dest, size_t dest_size, size_t width);
254 static void center(const char *str, size_t len, int separate);
255 static int left_str(const char *src, char *dest, size_t dest_size, size_t width);
256 static void left(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 #ifdef TEST_CAL
261 static time_t cal_time(time_t *t)
262 {
263 char *str = getenv("CAL_TEST_TIME");
264
265 if (str) {
266 uint64_t x = strtou64_or_err(str, "failed to parse CAL_TEST_TIME");
267
268 *t = x;
269 return *t;
270 }
271
272 return time(t);
273 }
274 #else
275 # define cal_time(t) time(t)
276 #endif
277
278 int main(int argc, char **argv)
279 {
280 struct tm local_time;
281 char *term;
282 time_t now;
283 int ch = 0, yflag = 0, Yflag = 0;
284
285 static struct cal_control ctl = {
286 .reform_year = DEFAULT_REFORM_YEAR,
287 .weekstart = SUNDAY,
288 .span_months = 0,
289 .colormode = UL_COLORMODE_UNDEF,
290 .weektype = WEEK_NUM_DISABLED,
291 .day_width = DAY_LEN,
292 .gutter_width = 2,
293 .req.day = 0,
294 .req.month = 0
295 };
296
297 enum {
298 OPT_COLOR = CHAR_MAX + 1,
299 OPT_ISO,
300 OPT_REFORM
301 };
302
303 static const struct option longopts[] = {
304 {"one", no_argument, NULL, '1'},
305 {"three", no_argument, NULL, '3'},
306 {"sunday", no_argument, NULL, 's'},
307 {"monday", no_argument, NULL, 'm'},
308 {"julian", no_argument, NULL, 'j'},
309 {"months", required_argument, NULL, 'n'},
310 {"span", no_argument, NULL, 'S'},
311 {"year", no_argument, NULL, 'y'},
312 {"week", optional_argument, NULL, 'w'},
313 {"color", optional_argument, NULL, OPT_COLOR},
314 {"reform", required_argument, NULL, OPT_REFORM},
315 {"iso", no_argument, NULL, OPT_ISO},
316 {"version", no_argument, NULL, 'V'},
317 {"twelve", no_argument, NULL, 'Y'},
318 {"help", no_argument, NULL, 'h'},
319 {"vertical", no_argument, NULL,'v'},
320 {NULL, 0, NULL, 0}
321 };
322
323 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
324 { 'Y','n','y' },
325 { 0 }
326 };
327 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
328
329 setlocale(LC_ALL, "");
330 bindtextdomain(PACKAGE, LOCALEDIR);
331 textdomain(PACKAGE);
332 close_stdout_atexit();
333
334 term = getenv("TERM");
335 if (term) {
336 has_term = setup_terminal(term) == 0;
337 if (has_term) {
338 Senter = my_tgetstr("smso");
339 Sexit = my_tgetstr("rmso");
340 }
341 }
342
343 /*
344 * The traditional Unix cal utility starts the week at Sunday,
345 * while ISO 8601 starts at Monday. We read the start day from
346 * the locale database, which can be overridden with the
347 * -s (Sunday) or -m (Monday) options.
348 */
349 #if HAVE_DECL__NL_TIME_WEEK_1STDAY
350 /*
351 * You need to use 2 locale variables to get the first day of the week.
352 * This is needed to support first_weekday=2 and first_workday=1 for
353 * the rare case where working days span across 2 weeks.
354 * This shell script shows the combinations and calculations involved:
355 *
356 * for LANG in en_US ru_RU fr_FR csb_PL POSIX; do
357 * printf "%s:\t%s + %s -1 = " $LANG $(locale week-1stday first_weekday)
358 * date -d"$(locale week-1stday) +$(($(locale first_weekday)-1))day" +%w
359 * done
360 *
361 * en_US: 19971130 + 1 -1 = 0 #0 = sunday
362 * ru_RU: 19971130 + 2 -1 = 1
363 * fr_FR: 19971201 + 1 -1 = 1
364 * csb_PL: 19971201 + 2 -1 = 2
365 * POSIX: 19971201 + 7 -1 = 0
366 */
367 {
368 int wfd;
369 union { unsigned int word; char *string; } val;
370 val.string = nl_langinfo(_NL_TIME_WEEK_1STDAY);
371
372 wfd = val.word;
373 wfd = day_in_week(&ctl, wfd % 100, (wfd / 100) % 100,
374 wfd / (100 * 100));
375 ctl.weekstart = (wfd + *nl_langinfo(_NL_TIME_FIRST_WEEKDAY) - 1) % DAYS_IN_WEEK;
376 }
377 #endif
378 while ((ch = getopt_long(argc, argv, "13mjn:sSywYvVh", longopts, NULL)) != -1) {
379
380 err_exclusive_options(ch, longopts, excl, excl_st);
381
382 switch(ch) {
383 case '1':
384 ctl.num_months = 1;
385 break;
386 case '3':
387 ctl.num_months = 3;
388 ctl.span_months = 1;
389 break;
390 case 's':
391 ctl.weekstart = SUNDAY; /* default */
392 break;
393 case 'm':
394 ctl.weekstart = MONDAY;
395 break;
396 case 'j':
397 ctl.julian = 1;
398 ctl.day_width = DAY_LEN + 1;
399 break;
400 case 'y':
401 yflag = 1;
402 break;
403 case 'Y':
404 Yflag = 1;
405 break;
406 case 'n':
407 ctl.num_months = strtou32_or_err(optarg,
408 _("invalid month argument"));
409 break;
410 case 'S':
411 ctl.span_months = 1;
412 break;
413 case 'w':
414 if (optarg) {
415 ctl.req.week = strtos32_or_err(optarg,
416 _("invalid week argument"));
417 if (ctl.req.week < 1 || 54 < ctl.req.week)
418 errx(EXIT_FAILURE,_("illegal week value: use 1-54"));
419 }
420 ctl.weektype = WEEK_NUM_US; /* default per weekstart */
421 break;
422 case OPT_COLOR:
423 ctl.colormode = UL_COLORMODE_AUTO;
424 if (optarg)
425 ctl.colormode = colormode_or_err(optarg,
426 _("unsupported color mode"));
427 break;
428 case OPT_REFORM:
429 ctl.reform_year = parse_reform_year(optarg);
430 break;
431 case OPT_ISO:
432 ctl.reform_year = ISO;
433 break;
434 case 'v':
435 ctl.vertical = 1;
436 break;
437 case 'V':
438 print_version(EXIT_SUCCESS);
439 case 'h':
440 usage();
441 default:
442 errtryhelp(EXIT_FAILURE);
443 }
444 }
445
446 argc -= optind;
447 argv += optind;
448
449 if (ctl.weektype) {
450 ctl.weektype = ctl.req.week & WEEK_NUM_MASK;
451 ctl.weektype |= (ctl.weekstart == MONDAY ? WEEK_NUM_ISO : WEEK_NUM_US);
452 ctl.week_width = (ctl.day_width * DAYS_IN_WEEK) + WNUM_LEN;
453 } else
454 ctl.week_width = ctl.day_width * DAYS_IN_WEEK;
455 /*
456 * The day_width includes the space between days,
457 * as there is no leading space, remove 1
458 * */
459 ctl.week_width -= 1;
460
461 if (argc == 1 && !isdigit_string(*argv)) {
462 usec_t x;
463 /* cal <timestamp> */
464 if (parse_timestamp(*argv, &x) == 0)
465 now = (time_t) (x / 1000000);
466 /* cal <monthname> */
467 else if ((ctl.req.month = monthname_to_number(&ctl, *argv)) > 0)
468 cal_time(&now); /* this year */
469 else
470 errx(EXIT_FAILURE, _("failed to parse timestamp or unknown month name: %s"), *argv);
471 argc = 0;
472 } else
473 cal_time(&now);
474
475 localtime_r(&now, &local_time);
476
477 switch(argc) {
478 case 3:
479 ctl.req.day = strtos32_or_err(*argv++, _("illegal day value"));
480 if (ctl.req.day < 1 || DAYS_IN_MONTH < ctl.req.day)
481 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), DAYS_IN_MONTH);
482 /* fallthrough */
483 case 2:
484 if (isdigit(**argv))
485 ctl.req.month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
486 else {
487 ctl.req.month = monthname_to_number(&ctl, *argv);
488 if (ctl.req.month < 0)
489 errx(EXIT_FAILURE, _("unknown month name: %s"), *argv);
490 argv++;
491 }
492 if (ctl.req.month < 1 || MONTHS_IN_YEAR < ctl.req.month)
493 errx(EXIT_FAILURE, _("illegal month value: use 1-12"));
494 /* fallthrough */
495 case 1:
496 ctl.req.year = strtos32_or_err(*argv++, _("illegal year value"));
497 if (ctl.req.year < SMALLEST_YEAR)
498 errx(EXIT_FAILURE, _("illegal year value: use positive integer"));
499 if (ctl.req.year == JULIAN)
500 errx(EXIT_FAILURE, _("illegal year value"));
501 if (ctl.req.day) {
502 int dm = days_in_month[leap_year(&ctl, ctl.req.year)]
503 [ctl.req.month];
504 if (ctl.req.day > dm)
505 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), dm);
506 ctl.req.day = day_in_year(&ctl, ctl.req.day,
507 ctl.req.month, ctl.req.year);
508 } else if ((int32_t) (local_time.tm_year + 1900) == ctl.req.year) {
509 ctl.req.day = local_time.tm_yday + 1;
510 }
511 if (!ctl.req.month && !ctl.req.week) {
512 ctl.req.month = local_time.tm_mon + 1;
513 if (!ctl.num_months)
514 yflag = 1;
515 }
516 break;
517 case 0:
518 ctl.req.day = local_time.tm_yday + 1;
519 ctl.req.year = local_time.tm_year + 1900;
520 if (!ctl.req.month)
521 ctl.req.month = local_time.tm_mon + 1;
522 break;
523 default:
524 warnx(_("bad usage"));
525 errtryhelp(EXIT_FAILURE);
526 }
527
528 if (0 < ctl.req.week) {
529 int yday = week_to_day(&ctl);
530 int leap = leap_year(&ctl, ctl.req.year);
531 int m = 1;
532
533 if (yday < 1)
534 errx(EXIT_FAILURE, _("illegal week value: year %d "
535 "doesn't have week %d"),
536 ctl.req.year, ctl.req.week);
537 while (m <= DECEMBER && yday > days_in_month[leap][m])
538 yday -= days_in_month[leap][m++];
539 if (DECEMBER < m && ctl.weektype & WEEK_NUM_ISO) {
540 /* In some years (e.g. 2010 in ISO mode) it's possible
541 * to have a remnant of week 53 starting the year yet
542 * the year in question ends during 52, in this case
543 * we're assuming that early remnant is being referred
544 * to if 53 is given as argument. */
545 if (ctl.req.week != week_number(31, DECEMBER, ctl.req.year - 1, &ctl))
546 errx(EXIT_FAILURE,
547 _("illegal week value: year %d "
548 "doesn't have week %d"),
549 ctl.req.year, ctl.req.week);
550 }
551 if (!ctl.req.month)
552 ctl.req.month = MONTHS_IN_YEAR < m ? 1 : m;
553 }
554
555 weekdays_init(&ctl);
556 headers_init(&ctl);
557
558 if (colors_init(ctl.colormode, "cal") == 0) {
559 /*
560 * If standout mode available (Senter and Sexit are set) and
561 * user or terminal-colors.d do not disable colors than
562 * ignore colors_init().
563 */
564 if (*Senter && *Sexit && colors_mode() != UL_COLORMODE_NEVER) {
565 /* let use standout mode */
566 ;
567 } else {
568 /* disable */
569 Senter = ""; Sexit = "";
570 ctl.req.day = 0;
571 ctl.weektype &= ~WEEK_NUM_MASK;
572 }
573 }
574
575 if (yflag || Yflag) {
576 ctl.gutter_width = 3;
577 if (!ctl.num_months)
578 ctl.num_months = MONTHS_IN_YEAR;
579 if (yflag) {
580 ctl.req.start_month = 1; /* start from Jan */
581 ctl.header_year = 1; /* print year number */
582 }
583 }
584
585 if (ctl.vertical)
586 ctl.gutter_width = 1;
587
588 if (ctl.num_months > 1 && ctl.months_in_row == 0) {
589 ctl.months_in_row = MONTHS_IN_YEAR_ROW; /* default */
590
591 if (isatty(STDOUT_FILENO)) {
592 int w, mw, extra, new_n;
593
594 w = get_terminal_width(80);
595 mw = ctl.julian ? DOY_MONTH_WIDTH : DOM_MONTH_WIDTH;
596
597 if (w < mw)
598 w = mw;
599
600 extra = ((w / mw) - 1) * ctl.gutter_width;
601 new_n = (w - extra) / mw;
602
603 if (new_n < MONTHS_IN_YEAR_ROW)
604 ctl.months_in_row = new_n > 0 ? new_n : 1;
605 }
606 } else if (!ctl.months_in_row)
607 ctl.months_in_row = 1;
608
609 if (!ctl.num_months)
610 ctl.num_months = 1; /* display at least one month */
611
612 if (yflag || Yflag)
613 yearly(&ctl);
614 else
615 monthly(&ctl);
616
617 return EXIT_SUCCESS;
618 }
619
620 /* leap year -- account for gregorian reformation in 1752 */
621 static int leap_year(const struct cal_control *ctl, int32_t year)
622 {
623 if (year <= ctl->reform_year)
624 return !(year % 4);
625
626 return ( !(year % 4) && (year % 100) ) || !(year % 400);
627 }
628
629 static void init_monthnames(struct cal_control *ctl)
630 {
631 size_t i;
632
633 if (ctl->full_month[0] != NULL)
634 return; /* already initialized */
635
636 for (i = 0; i < MONTHS_IN_YEAR; i++)
637 ctl->full_month[i] = nl_langinfo(ALTMON_1 + i);
638 }
639
640 static void init_abbr_monthnames(struct cal_control *ctl)
641 {
642 size_t i;
643
644 if (ctl->abbr_month[0] != NULL)
645 return; /* already initialized */
646
647 for (i = 0; i < MONTHS_IN_YEAR; i++)
648 ctl->abbr_month[i] = nl_langinfo(_NL_ABALTMON_1 + i);
649 }
650
651 static int monthname_to_number(struct cal_control *ctl, const char *name)
652 {
653 size_t i;
654
655 init_monthnames(ctl);
656 for (i = 0; i < MONTHS_IN_YEAR; i++)
657 if (strcasecmp(ctl->full_month[i], name) == 0)
658 return i + 1;
659
660 init_abbr_monthnames(ctl);
661 for (i = 0; i < MONTHS_IN_YEAR; i++)
662 if (strcasecmp(ctl->abbr_month[i], name) == 0)
663 return i + 1;
664
665 return -EINVAL;
666 }
667
668 static void weekdays_init(struct cal_control *ctl)
669 {
670 size_t wd;
671 int i;
672
673 for (i = 0; i < DAYS_IN_WEEK; i++) {
674 wd = (i + ctl->weekstart) % DAYS_IN_WEEK;
675 ctl->weekdays[i] = nl_langinfo(ABDAY_1 + wd);
676 }
677 }
678 static void headers_init(struct cal_control *ctl)
679 {
680 size_t i;
681 char *cur_dh = day_headings;
682 char tmp[FMT_ST_CHARS];
683 int year_len;
684
685 year_len = snprintf(tmp, sizeof(tmp), "%04d", ctl->req.year);
686
687 if (year_len < 0 || (size_t)year_len >= sizeof(tmp)) {
688 /* XXX impossible error */
689 return;
690 }
691
692 for (i = 0; i < DAYS_IN_WEEK; i++) {
693 size_t space_left;
694
695 if (i)
696 strcat(cur_dh++, " ");
697 space_left = sizeof(day_headings) - (cur_dh - day_headings);
698
699 if (space_left <= (ctl->day_width - 1))
700 break;
701 cur_dh += center_str(ctl->weekdays[i], cur_dh,
702 space_left, ctl->day_width - 1);
703 }
704
705 init_monthnames(ctl);
706
707 for (i = 0; i < MONTHS_IN_YEAR; i++) {
708 /* The +1 after year_len is space in between month and year. */
709 if (ctl->week_width < strlen(ctl->full_month[i]) + year_len)
710 ctl->header_hint = 1;
711 }
712 }
713
714 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl)
715 {
716 int first_week_day = day_in_week(ctl, 1, month->month, month->year);
717 int month_days;
718 int i, j, weeklines = 0;
719
720 if (ctl->julian)
721 j = day_in_year(ctl, 1, month->month, month->year);
722 else
723 j = 1;
724 month_days = j + days_in_month[leap_year(ctl, month->year)][month->month];
725
726 /* True when Sunday is not first day in the output week. */
727 if (ctl->weekstart) {
728 first_week_day -= ctl->weekstart;
729 if (first_week_day < 0)
730 first_week_day = DAYS_IN_WEEK - ctl->weekstart;
731 month_days += ctl->weekstart - 1;
732 }
733
734 /* Fill day array. */
735 for (i = 0; i < MAXDAYS; i++) {
736 if (0 < first_week_day) {
737 month->days[i] = SPACE;
738 first_week_day--;
739 continue;
740 }
741 if (j < month_days) {
742 if (month->year == ctl->reform_year &&
743 month->month == REFORMATION_MONTH &&
744 (j == 3 || j == 247))
745 j += NUMBER_MISSING_DAYS;
746 month->days[i] = j;
747 j++;
748 continue;
749 }
750 month->days[i] = SPACE;
751 weeklines++;
752 }
753
754 /* Add week numbers */
755 if (ctl->weektype) {
756 int weeknum = week_number(1, month->month, month->year, ctl);
757 weeklines = MAXDAYS / DAYS_IN_WEEK - weeklines / DAYS_IN_WEEK;
758 for (i = 0; i < MAXDAYS / DAYS_IN_WEEK; i++) {
759 if (0 < weeklines) {
760 if (52 < weeknum)
761 weeknum = week_number(month->days[i * DAYS_IN_WEEK], month->month, month->year, ctl);
762 month->weeks[i] = weeknum++;
763 } else
764 month->weeks[i] = SPACE;
765 weeklines--;
766 }
767 }
768 }
769
770 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl)
771 {
772 char out[FMT_ST_CHARS];
773 struct cal_month *i;
774
775 if (ctl->header_hint || ctl->header_year) {
776 for (i = month; i; i = i->next) {
777 snprintf(out, sizeof(out), "%s", ctl->full_month[i->month - 1]);
778 center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
779 }
780 if (!ctl->header_year) {
781 fputc('\n', stdout);
782 for (i = month; i; i = i->next) {
783 snprintf(out, sizeof(out), "%04d", i->year);
784 center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
785 }
786 }
787 } else {
788 for (i = month; i; i = i->next) {
789 snprintf(out, sizeof(out), "%s %04d", ctl->full_month[i->month - 1], i->year);
790 center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
791 }
792 }
793 fputc('\n', stdout);
794 for (i = month; i; i = i->next) {
795 if (ctl->weektype) {
796 if (ctl->julian)
797 printf("%*s%s", (int)ctl->day_width - 1, "", day_headings);
798 else
799 printf("%*s%s", (int)ctl->day_width, "", day_headings);
800 } else
801 fputs(day_headings, stdout);
802 if (i->next != NULL)
803 printf("%*s", ctl->gutter_width, "");
804 }
805 fputc('\n', stdout);
806 }
807
808 static void cal_vert_output_header(struct cal_month *month,
809 const struct cal_control *ctl)
810 {
811 char out[FMT_ST_CHARS];
812 struct cal_month *m;
813 int month_width;
814
815 month_width = ctl->day_width * (MAXDAYS / DAYS_IN_WEEK);
816
817 /* Padding for the weekdays */
818 printf("%*s", (int)ctl->day_width + 1, "");
819
820 if (ctl->header_hint || ctl->header_year) {
821 for (m = month; m; m = m->next) {
822 snprintf(out, sizeof(out), "%s", ctl->full_month[m->month - 1]);
823 left(out, month_width, ctl->gutter_width);
824 }
825 if (!ctl->header_year) {
826 fputc('\n', stdout);
827 /* Padding for the weekdays */
828 printf("%*s", (int)ctl->day_width + 1, "");
829
830 for (m = month; m; m = m->next) {
831 snprintf(out, sizeof(out), "%04d", m->year);
832 left(out, month_width, ctl->gutter_width);
833 }
834 }
835 } else {
836 for (m = month; m; m = m->next) {
837 snprintf(out, sizeof(out), "%s %04d", ctl->full_month[m->month - 1], m->year);
838 left(out, month_width, ctl->gutter_width);
839 }
840 }
841 fputc('\n', stdout);
842 }
843
844 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl)
845 {
846 int reqday, week_line, d;
847 int skip;
848 struct cal_month *i;
849
850 for (week_line = 0; week_line < MAXDAYS / DAYS_IN_WEEK; week_line++) {
851 for (i = month; i; i = i->next) {
852 /* Determine the day that should be highlighted. */
853 reqday = 0;
854 if (i->month == ctl->req.month && i->year == ctl->req.year) {
855 if (ctl->julian)
856 reqday = ctl->req.day;
857 else
858 reqday = ctl->req.day + 1 -
859 day_in_year(ctl, 1, i->month,
860 i->year);
861 }
862
863 if (ctl->weektype) {
864 if (0 < i->weeks[week_line]) {
865 if ((ctl->weektype & WEEK_NUM_MASK) == i->weeks[week_line])
866 printf("%s%2d%s", Senter, i->weeks[week_line], Sexit);
867 else
868 printf("%2d", i->weeks[week_line]);
869 } else
870 printf("%2s", "");
871 skip = ctl->day_width;
872 } else
873 /* First day of the week is one char narrower than the other days,
874 * unless week number is printed. */
875 skip = ctl->day_width - 1;
876
877 for (d = DAYS_IN_WEEK * week_line;
878 d < DAYS_IN_WEEK * week_line + DAYS_IN_WEEK; d++) {
879 if (0 < i->days[d]) {
880 if (reqday == i->days[d])
881 printf("%*s%s%*d%s",
882 skip - (ctl->julian ? 3 : 2),
883 "", Senter, (ctl->julian ? 3 : 2),
884 i->days[d], Sexit);
885 else
886 printf("%*d", skip, i->days[d]);
887 } else
888 printf("%*s", skip, "");
889
890 if (skip < (int)ctl->day_width)
891 skip++;
892 }
893 if (i->next != NULL)
894 printf("%*s", ctl->gutter_width, "");
895 }
896 if (i == NULL)
897 fputc('\n', stdout);
898 }
899 }
900
901 static void
902 cal_vert_output_months(struct cal_month *month, const struct cal_control *ctl)
903 {
904 int i, reqday, week, d;
905 int skip;
906 struct cal_month *m;
907
908 skip = ctl->day_width;
909 for (i = 0; i < DAYS_IN_WEEK; i++) {
910 left(ctl->weekdays[i], ctl->day_width - 1, 0);
911 for (m = month; m; m = m->next) {
912 reqday = 0;
913 if (m->month == ctl->req.month && m->year == ctl->req.year) {
914 if (ctl->julian) {
915 reqday = ctl->req.day;
916 } else {
917 reqday = ctl->req.day + 1 -
918 day_in_year(ctl, 1, m->month, m->year);
919 }
920 }
921 for (week = 0; week < MAXDAYS / DAYS_IN_WEEK; week++) {
922 d = i + DAYS_IN_WEEK * week;
923 if (0 < m->days[d]) {
924 if (reqday == m->days[d]) {
925 printf("%*s%s%*d%s",
926 skip - (ctl->julian ? 3 : 2),
927 "", Senter, (ctl->julian ? 3 : 2),
928 m->days[d], Sexit);
929 } else {
930 printf("%*d", skip, m->days[d]);
931 }
932 } else {
933 printf("%*s", skip, "");
934 }
935 skip = ctl->day_width;
936 }
937 if (m->next != NULL)
938 printf("%*s", ctl->gutter_width, "");
939 }
940 fputc('\n', stdout);
941 }
942 if (!ctl->weektype)
943 return;
944
945 printf("%*s", (int)ctl->day_width - 1, "");
946 for (m = month; m; m = m->next) {
947 for (week = 0; week < MAXDAYS / DAYS_IN_WEEK; week++) {
948 if (0 < m->weeks[week]) {
949 if ((ctl->weektype & WEEK_NUM_MASK) == m->weeks[week])
950 printf("%s%*d%s",
951 Senter,
952 skip - (ctl->julian ? 3 : 2),
953 m->weeks[week], Sexit);
954 else
955 printf("%*d", skip, m->weeks[week]);
956 } else
957 printf("%*s", skip, "");
958 }
959 if (m->next != NULL)
960 printf("%*s", ctl->gutter_width, "");
961 }
962 fputc('\n', stdout);
963 }
964
965
966 static void monthly(const struct cal_control *ctl)
967 {
968 struct cal_month m1,m2,m3, *m;
969 int i, rows, month = ctl->req.start_month ? ctl->req.start_month : ctl->req.month;
970 int32_t year = ctl->req.year;
971
972 /* cal -3, cal -Y --span, etc. */
973 if (ctl->span_months) {
974 int new_month = month - ctl->num_months / 2;
975 if (new_month < 1) {
976 new_month *= -1;
977 year -= (new_month / MONTHS_IN_YEAR) + 1;
978
979 if (new_month > MONTHS_IN_YEAR)
980 new_month %= MONTHS_IN_YEAR;
981 month = MONTHS_IN_YEAR - new_month;
982 } else
983 month = new_month;
984 }
985
986 m1.next = (ctl->months_in_row > 1) ? &m2 : NULL;
987 m2.next = (ctl->months_in_row > 2) ? &m3 : NULL;
988 m3.next = NULL;
989
990 rows = (ctl->num_months - 1) / ctl->months_in_row;
991 for (i = 0; i < rows + 1 ; i++){
992 if (i == rows){
993 switch (ctl->num_months % ctl->months_in_row){
994 case 1:
995 m1.next = NULL;
996 /* fallthrough */
997 case 2:
998 m2.next = NULL;
999 /* fallthrough */
1000 }
1001 }
1002 for (m = &m1; m; m = m->next){
1003 m->month = month++;
1004 m->year = year;
1005 if (MONTHS_IN_YEAR < month) {
1006 year++;
1007 month = 1;
1008 }
1009 cal_fill_month(m, ctl);
1010 }
1011 if (ctl->vertical) {
1012 if (i > 0)
1013 fputc('\n', stdout); /* Add a line between row */
1014
1015 cal_vert_output_header(&m1, ctl);
1016 cal_vert_output_months(&m1, ctl);
1017 } else {
1018 cal_output_header(&m1, ctl);
1019 cal_output_months(&m1, ctl);
1020 }
1021 }
1022 }
1023
1024 static void yearly(const struct cal_control *ctl)
1025 {
1026 size_t year_width;
1027
1028 year_width = (size_t) ctl->months_in_row * ctl->week_width
1029 + ((size_t) ctl->months_in_row - 1) * ctl->gutter_width;
1030
1031 if (ctl->header_year) {
1032 char out[FMT_ST_CHARS];
1033
1034 snprintf(out, sizeof(out), "%04d", ctl->req.year);
1035 center(out, year_width, 0);
1036 fputs("\n\n", stdout);
1037 }
1038 monthly(ctl);
1039 }
1040
1041 /*
1042 * day_in_year --
1043 * return the 1 based day number within the year
1044 */
1045 static int day_in_year(const struct cal_control *ctl,
1046 int day, int month, int32_t year)
1047 {
1048 int i, leap;
1049
1050 leap = leap_year(ctl, year);
1051 for (i = 1; i < month; i++)
1052 day += days_in_month[leap][i];
1053 return day;
1054 }
1055
1056 /*
1057 * day_in_week
1058 * return the 0 based day number for any date from 1 Jan. 1 to
1059 * 31 Dec. 9999. Assumes the Gregorian reformation eliminates
1060 * 3 Sep. 1752 through 13 Sep. 1752, and returns invalid weekday
1061 * during the period of 11 days.
1062 */
1063 static int day_in_week(const struct cal_control *ctl, int day,
1064 int month, int32_t year)
1065 {
1066 /*
1067 * The magic constants in the reform[] array are, in a simplified
1068 * sense, the remaining days after slicing into one week periods the total
1069 * days from the beginning of the year to the target month. That is,
1070 * weeks + reform[] days gets us to the target month. The exception is,
1071 * that for the months past February 'DOY - 1' must be used.
1072 *
1073 * DoY (Day of Year): total days to the target month
1074 *
1075 * Month 1 2 3 4 5 6 7 8 9 10 11 12
1076 * DoY 0 31 59 90 120 151 181 212 243 273 304 334
1077 * DoY % 7 0 3
1078 * DoY - 1 % 7 - -- 2 5 0 3 5 1 4 6 2 4
1079 * reform[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
1080 *
1081 * Note: these calculations are for non leap years.
1082 */
1083 static const int reform[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
1084 static const int old[] = { 5, 1, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2 };
1085
1086 if (year != ctl->reform_year + 1)
1087 year -= month < MARCH;
1088 else
1089 year -= (month < MARCH) + 14;
1090 if (ctl->reform_year < year
1091 || (year == ctl->reform_year && REFORMATION_MONTH < month)
1092 || (year == ctl->reform_year
1093 && month == REFORMATION_MONTH && 13 < day)) {
1094 return ((int64_t) year + (year / 4)
1095 - (year / 100) + (year / 400)
1096 + reform[month - 1] + day) % DAYS_IN_WEEK;
1097 }
1098 if (year < ctl->reform_year
1099 || (year == ctl->reform_year && month < REFORMATION_MONTH)
1100 || (year == ctl->reform_year && month == REFORMATION_MONTH && day < 3))
1101 return ((int64_t) year + year / 4 + old[month - 1] + day)
1102 % DAYS_IN_WEEK;
1103 return NONEDAY;
1104 }
1105
1106 /*
1107 * week_number
1108 * return the week number of a given date, 1..54.
1109 * Supports ISO-8601 and North American modes.
1110 * Day may be given as Julian day of the year mode, in which
1111 * case the month is disregarded entirely.
1112 */
1113 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl)
1114 {
1115 int fday = 0, yday;
1116 const int wday = day_in_week(ctl, 1, JANUARY, year);
1117
1118 if (ctl->weektype & WEEK_NUM_ISO)
1119 fday = wday + (wday >= FRIDAY ? -2 : 5);
1120 else {
1121 /* WEEK_NUM_US: Jan 1 is always First week, that may
1122 * begin previous year. That means there is very seldom
1123 * more than 52 weeks, */
1124 fday = wday + 6;
1125 }
1126 /* For julian dates the month can be set to 1, the global julian
1127 * variable cannot be relied upon here, because we may recurse
1128 * internally for 31.12. which would not work. */
1129 if (day > DAYS_IN_MONTH)
1130 month = JANUARY;
1131
1132 yday = day_in_year(ctl, day, month, year);
1133 if (year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
1134 fday -= NUMBER_MISSING_DAYS;
1135
1136 /* Last year is last year */
1137 if (yday + fday < DAYS_IN_WEEK)
1138 return week_number(31, DECEMBER, year - 1, ctl);
1139
1140 /* Or it could be part of the next year. The reformation year had less
1141 * days than 365 making this check invalid, but reformation year ended
1142 * on Sunday and in week 51, so it's ok here. */
1143 if (ctl->weektype == WEEK_NUM_ISO && yday >= 363
1144 && day_in_week(ctl, day, month, year) >= MONDAY
1145 && day_in_week(ctl, day, month, year) <= WEDNESDAY
1146 && day_in_week(ctl, 31, DECEMBER, year) >= MONDAY
1147 && day_in_week(ctl, 31, DECEMBER, year) <= WEDNESDAY)
1148 return week_number(1, JANUARY, year + 1, ctl);
1149
1150 return (yday + fday) / DAYS_IN_WEEK;
1151 }
1152
1153 /*
1154 * week_to_day
1155 * return the yday of the first day in a given week inside
1156 * the given year. This may be something other than Monday
1157 * for ISO-8601 modes. For North American numbering this
1158 * always returns a Sunday.
1159 */
1160 static int week_to_day(const struct cal_control *ctl)
1161 {
1162 int yday, wday;
1163
1164 wday = day_in_week(ctl, 1, JANUARY, ctl->req.year);
1165 yday = ctl->req.week * DAYS_IN_WEEK - wday;
1166
1167 if (ctl->req.year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
1168 yday += NUMBER_MISSING_DAYS;
1169
1170 if (ctl->weektype & WEEK_NUM_ISO)
1171 yday -= (wday >= FRIDAY ? -2 : 5);
1172 else
1173 yday -= 6; /* WEEK_NUM_US */
1174 if (yday <= 0)
1175 return 1;
1176
1177 return yday;
1178 }
1179
1180 /*
1181 * Center string, handling multibyte characters appropriately.
1182 * In addition if the string is too large for the width it's truncated.
1183 * The number of trailing spaces may be 1 less than the number of leading spaces.
1184 */
1185 static int center_str(const char* src, char* dest,
1186 size_t dest_size, size_t width)
1187 {
1188 return mbsalign(src, dest, dest_size, &width,
1189 MBS_ALIGN_CENTER, MBA_UNIBYTE_FALLBACK);
1190 }
1191
1192 static void center(const char *str, size_t len, int separate)
1193 {
1194 char lineout[FMT_ST_CHARS];
1195
1196 center_str(str, lineout, ARRAY_SIZE(lineout), len);
1197 fputs(lineout, stdout);
1198
1199 if (separate)
1200 printf("%*s", separate, "");
1201 }
1202 static int left_str(const char* src, char* dest,
1203 size_t dest_size, size_t width)
1204 {
1205 return mbsalign(src, dest, dest_size, &width,
1206 MBS_ALIGN_LEFT, MBA_UNIBYTE_FALLBACK);
1207 }
1208
1209 static void left(const char *str, size_t len, int separate)
1210 {
1211 char lineout[FMT_ST_CHARS];
1212
1213 left_str(str, lineout, sizeof(lineout), len);
1214 fputs(lineout, stdout);
1215
1216 if (separate)
1217 printf("%*s", separate, "");
1218 }
1219
1220 static int parse_reform_year(const char *reform_year)
1221 {
1222 size_t i;
1223
1224 struct reform {
1225 char *name;
1226 int val;
1227 };
1228
1229 struct reform years[] = {
1230 {"gregorian", GREGORIAN},
1231 {"iso", ISO},
1232 {"1752", GB1752},
1233 {"julian", JULIAN},
1234 };
1235
1236 for (i = 0; i < ARRAY_SIZE(years); i++) {
1237 if (strcasecmp(reform_year, years[i].name) == 0)
1238 return years[i].val;
1239 }
1240 errx(EXIT_FAILURE, "invalid --reform value: '%s'", reform_year);
1241 }
1242
1243 static void __attribute__((__noreturn__)) usage(void)
1244 {
1245 FILE *out = stdout;
1246
1247 fputs(USAGE_HEADER, out);
1248 fprintf(out, _(" %s [options] [[[day] month] year]\n"), program_invocation_short_name);
1249 fprintf(out, _(" %s [options] <timestamp|monthname>\n"), program_invocation_short_name);
1250
1251 fputs(USAGE_SEPARATOR, out);
1252 fputs(_("Display a calendar, or some part of it.\n"), out);
1253 fputs(_("Without any arguments, display the current month.\n"), out);
1254
1255 fputs(USAGE_OPTIONS, out);
1256 fputs(_(" -1, --one show only a single month (default)\n"), out);
1257 fputs(_(" -3, --three show three months spanning the date\n"), out);
1258 fputs(_(" -n, --months <num> show num months starting with date's month\n"), out);
1259 fputs(_(" -S, --span span the date when displaying multiple months\n"), out);
1260 fputs(_(" -s, --sunday Sunday as first day of week\n"), out);
1261 fputs(_(" -m, --monday Monday as first day of week\n"), out);
1262 fputs(_(" -j, --julian use day-of-year for all calendars\n"), out);
1263 fputs(_(" --reform <val> Gregorian reform date (1752|gregorian|iso|julian)\n"), out);
1264 fputs(_(" --iso alias for --reform=iso\n"), out);
1265 fputs(_(" -y, --year show the whole year\n"), out);
1266 fputs(_(" -Y, --twelve show the next twelve months\n"), out);
1267 fputs(_(" -w, --week[=<num>] show US or ISO-8601 week numbers\n"), out);
1268 fputs(_(" -v, --vertical show day vertically instead of line\n"), out);
1269 fprintf(out,
1270 _(" --color[=<when>] colorize messages (%s, %s or %s)\n"), "auto", "always", "never");
1271 fprintf(out,
1272 " %s\n", USAGE_COLORS_DEFAULT);
1273
1274 fputs(USAGE_SEPARATOR, out);
1275 printf(USAGE_HELP_OPTIONS(23));
1276 printf(USAGE_MAN_TAIL("cal(1)"));
1277
1278 exit(EXIT_SUCCESS);
1279 }