]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/cal.c
cal: support alone month name parameter
[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 # ifdef HAVE_NCURSES_H
84 # include <ncurses.h>
85 # elif defined(HAVE_NCURSES_NCURSES_H)
86 # include <ncurses/ncurses.h>
87 # endif
88 # include <term.h>
89 #endif
90
91 static int setup_terminal(char *term
92 #if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
93 __attribute__((__unused__))
94 #endif
95 )
96 {
97 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
98 int ret;
99
100 if (setupterm(term, STDOUT_FILENO, &ret) != OK || ret != 1)
101 return -1;
102 #endif
103 return 0;
104 }
105
106 static void my_putstring(char *s)
107 {
108 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
109 if (has_term)
110 putp(s);
111 else
112 #endif
113 fputs(s, stdout);
114 }
115
116 static const char *my_tgetstr(char *ss
117 #if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
118 __attribute__((__unused__))
119 #endif
120 )
121 {
122 const char *ret = NULL;
123
124 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
125 if (has_term)
126 ret = tigetstr(ss);
127 #endif
128 if (!ret || ret == (char *)-1)
129 return "";
130 return ret;
131 }
132
133 #include "widechar.h"
134
135 enum {
136 SUNDAY = 0,
137 MONDAY,
138 TUESDAY,
139 WEDNESDAY,
140 THURSDAY,
141 FRIDAY,
142 SATURDAY,
143 DAYS_IN_WEEK,
144 NONEDAY
145 };
146
147 enum {
148 JANUARY = 1,
149 FEBRUARY,
150 MARCH,
151 APRIL,
152 MAY,
153 JUNE,
154 JULY,
155 AUGUST,
156 SEPTEMBER,
157 OCTOBER,
158 NOVEMBER,
159 DECEMBER
160 };
161
162 #define REFORMATION_YEAR 1752 /* Signed-off-by: Lord Chesterfield */
163 #define REFORMATION_MONTH SEPTEMBER
164 #define NUMBER_MISSING_DAYS 11 /* 11 day correction */
165 #define YDAY_AFTER_MISSING 258 /* 14th in Sep 1752 */
166
167 #define MONTHS_IN_YEAR DECEMBER
168 #define DAYS_IN_MONTH 31
169 #define MAXDAYS 42 /* slots in a month array */
170 #define SPACE -1 /* used in day array */
171
172 #define SMALLEST_YEAR 1
173
174 #define DAY_LEN 3 /* 3 spaces per day */
175 #define WEEK_LEN (DAYS_IN_WEEK * DAY_LEN)
176 #define MONTHS_IN_YEAR_ROW 3 /* month columns in year view */
177 #define WNUM_LEN 3
178
179 #define FMT_ST_CHARS 300 /* 90 suffices in most locales */
180
181 static const int days_in_month[2][13] = {
182 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
183 {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
184 };
185
186 enum {
187 WEEK_NUM_DISABLED = 0,
188 WEEK_NUM_MASK=0xff,
189 WEEK_NUM_ISO=0x100,
190 WEEK_NUM_US=0x200,
191 };
192
193 /* utf-8 can have up to 6 bytes per char; and an extra byte for ending \0 */
194 static char day_headings[(WEEK_LEN + 1) * 6 + 1];
195
196 struct cal_request {
197 int day;
198 int month;
199 int32_t year;
200 int week;
201 int start_month;
202 };
203
204 struct cal_control {
205 const char *full_month[MONTHS_IN_YEAR]; /* month names */
206 int colormode; /* day and week number highlight */
207 int num_months; /* number of requested monts */
208 int span_months; /* span the date */
209 int months_in_row; /* number of months horizontally in print out */
210 int weekstart; /* day the week starts, often Sun or Mon */
211 int weektype; /* WEEK_TYPE_{NONE,ISO,US} */
212 size_t day_width; /* day width in characters in printout */
213 size_t week_width; /* 7 * day_width + possible week num */
214 int gutter_width; /* spaces in between horizontal month outputs */
215 struct cal_request req; /* the times user is interested */
216 unsigned int julian:1, /* julian output */
217 header_year:1, /* print year number */
218 header_hint:1; /* does month name + year need two lines to fit */
219 };
220
221 struct cal_month {
222 int days[MAXDAYS]; /* the day numbers, or SPACE */
223 int weeks[MAXDAYS / DAYS_IN_WEEK];
224 int month;
225 int32_t year;
226 struct cal_month *next;
227 };
228
229 /* function prototypes */
230 static int leap_year(int32_t year);
231 static int monthname_to_number(struct cal_control *ctl, const char *name);
232 static void headers_init(struct cal_control *ctl);
233 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl);
234 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl);
235 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl);
236 static void monthly(const struct cal_control *ctl);
237 static void yearly(const struct cal_control *ctl);
238 static int day_in_year(int day, int month, int32_t year);
239 static int day_in_week(int day, int month, int32_t year);
240 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl);
241 static int week_to_day(const struct cal_control *ctl);
242 static int center_str(const char *src, char *dest, size_t dest_size, size_t width);
243 static void center(const char *str, size_t len, int separate);
244 static void __attribute__((__noreturn__)) usage(FILE *out);
245
246 int main(int argc, char **argv)
247 {
248 struct tm *local_time;
249 char *term;
250 time_t now;
251 int ch = 0, yflag = 0, Yflag = 0;
252 static struct cal_control ctl = {
253 .weekstart = SUNDAY,
254 .num_months = 1, /* default is "cal -1" */
255 .span_months = 0,
256 .colormode = UL_COLORMODE_UNDEF,
257 .weektype = WEEK_NUM_DISABLED,
258 .day_width = DAY_LEN,
259 .gutter_width = 2,
260 .req.day = 0,
261 .req.month = 0
262 };
263
264 enum {
265 OPT_COLOR = CHAR_MAX + 1
266 };
267
268 static const struct option longopts[] = {
269 {"one", no_argument, NULL, '1'},
270 {"three", no_argument, NULL, '3'},
271 {"sunday", no_argument, NULL, 's'},
272 {"monday", no_argument, NULL, 'm'},
273 {"julian", no_argument, NULL, 'j'},
274 {"months", required_argument, NULL, 'n'},
275 {"span", no_argument, NULL, 'S'},
276 {"year", no_argument, NULL, 'y'},
277 {"week", optional_argument, NULL, 'w'},
278 {"color", optional_argument, NULL, OPT_COLOR},
279 {"version", no_argument, NULL, 'V'},
280 {"twelve", no_argument, NULL, 'Y'},
281 {"help", no_argument, NULL, 'h'},
282 {NULL, 0, NULL, 0}
283 };
284
285 static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */
286 { 'Y','n','y' },
287 { 0 }
288 };
289 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
290
291 setlocale(LC_ALL, "");
292 bindtextdomain(PACKAGE, LOCALEDIR);
293 textdomain(PACKAGE);
294 atexit(close_stdout);
295
296 term = getenv("TERM");
297 if (term) {
298 has_term = setup_terminal(term) == 0;
299 if (has_term) {
300 Senter = my_tgetstr("smso");
301 Sexit = my_tgetstr("rmso");
302 }
303 }
304
305 /*
306 * The traditional Unix cal utility starts the week at Sunday,
307 * while ISO 8601 starts at Monday. We read the start day from
308 * the locale database, which can be overridden with the
309 * -s (Sunday) or -m (Monday) options.
310 */
311 #if HAVE_DECL__NL_TIME_WEEK_1STDAY
312 /*
313 * You need to use 2 locale variables to get the first day of the week.
314 * This is needed to support first_weekday=2 and first_workday=1 for
315 * the rare case where working days span across 2 weeks.
316 * This shell script shows the combinations and calculations involved:
317 *
318 * for LANG in en_US ru_RU fr_FR csb_PL POSIX; do
319 * printf "%s:\t%s + %s -1 = " $LANG $(locale week-1stday first_weekday)
320 * date -d"$(locale week-1stday) +$(($(locale first_weekday)-1))day" +%w
321 * done
322 *
323 * en_US: 19971130 + 1 -1 = 0 #0 = sunday
324 * ru_RU: 19971130 + 2 -1 = 1
325 * fr_FR: 19971201 + 1 -1 = 1
326 * csb_PL: 19971201 + 2 -1 = 2
327 * POSIX: 19971201 + 7 -1 = 0
328 */
329 {
330 int wfd;
331 union { unsigned int word; char *string; } val;
332 val.string = nl_langinfo(_NL_TIME_WEEK_1STDAY);
333
334 wfd = val.word;
335 wfd = day_in_week(wfd % 100, (wfd / 100) % 100, wfd / (100 * 100));
336 ctl.weekstart = (wfd + *nl_langinfo(_NL_TIME_FIRST_WEEKDAY) - 1) % DAYS_IN_WEEK;
337 }
338 #endif
339 while ((ch = getopt_long(argc, argv, "13mjn:sSywYVh", longopts, NULL)) != -1) {
340
341 err_exclusive_options(ch, longopts, excl, excl_st);
342
343 switch(ch) {
344 case '1':
345 /* default */
346 break;
347 case '3':
348 ctl.num_months = 3;
349 ctl.span_months = 1;
350 ctl.months_in_row = 3;
351 break;
352 case 's':
353 ctl.weekstart = SUNDAY; /* default */
354 break;
355 case 'm':
356 ctl.weekstart = MONDAY;
357 break;
358 case 'j':
359 ctl.julian = 1;
360 ctl.day_width = DAY_LEN + 1;
361 break;
362 case 'y':
363 yflag = 1;
364 break;
365 case 'Y':
366 Yflag = 1;
367 break;
368 case 'n':
369 ctl.num_months = strtou32_or_err(optarg,
370 _("invalid month argument"));
371 break;
372 case 'S':
373 ctl.span_months = 1;
374 break;
375 case 'w':
376 if (optarg) {
377 ctl.req.week = strtos32_or_err(optarg,
378 _("invalid week argument"));
379 if (ctl.req.week < 1 || 54 < ctl.req.week)
380 errx(EXIT_FAILURE,_("illegal week value: use 1-54"));
381 }
382 ctl.weektype = WEEK_NUM_US; /* default per weekstart */
383 break;
384 case OPT_COLOR:
385 ctl.colormode = UL_COLORMODE_AUTO;
386 if (optarg)
387 ctl.colormode = colormode_or_err(optarg,
388 _("unsupported color mode"));
389 break;
390 case 'V':
391 printf(UTIL_LINUX_VERSION);
392 return EXIT_SUCCESS;
393 case 'h':
394 usage(stdout);
395 case '?':
396 default:
397 usage(stderr);
398 }
399 }
400
401 argc -= optind;
402 argv += optind;
403
404 if (ctl.weektype) {
405 ctl.weektype = ctl.req.week & WEEK_NUM_MASK;
406 ctl.weektype |= (ctl.weekstart == MONDAY ? WEEK_NUM_ISO : WEEK_NUM_US);
407 ctl.week_width = (ctl.day_width * DAYS_IN_WEEK) + WNUM_LEN;
408 } else
409 ctl.week_width = ctl.day_width * DAYS_IN_WEEK;
410
411 if (argc == 1 && !isdigit_string(*argv)) {
412 usec_t x;
413 /* cal <timestamp> */
414 if (parse_timestamp(*argv, &x) == 0)
415 now = (time_t) (x / 1000000);
416 /* cal <monthname> */
417 else if ((ctl.req.month = monthname_to_number(&ctl, *argv)) > 0)
418 time(&now); /* this year */
419 else
420 errx(EXIT_FAILURE, _("failed to parse timestamp or unknown month name: %s"), *argv);
421 argc = 0;
422 } else
423 time(&now);
424
425 local_time = localtime(&now);
426
427 switch(argc) {
428 case 3:
429 ctl.req.day = strtos32_or_err(*argv++, _("illegal day value"));
430 if (ctl.req.day < 1 || DAYS_IN_MONTH < ctl.req.day)
431 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), DAYS_IN_MONTH);
432 /* FALLTHROUGH */
433 case 2:
434 if (isdigit(**argv))
435 ctl.req.month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
436 else {
437 ctl.req.month = monthname_to_number(&ctl, *argv);
438 if (ctl.req.month < 0)
439 errx(EXIT_FAILURE, _("unknown month name: %s"), *argv);
440 argv++;
441 }
442 if (ctl.req.month < 1 || MONTHS_IN_YEAR < ctl.req.month)
443 errx(EXIT_FAILURE, _("illegal month value: use 1-12"));
444 /* FALLTHROUGH */
445 case 1:
446 ctl.req.year = strtos32_or_err(*argv++, _("illegal year value"));
447 if (ctl.req.year < SMALLEST_YEAR)
448 errx(EXIT_FAILURE, _("illegal year value: use positive integer"));
449 if (ctl.req.year == INT32_MAX)
450 errx(EXIT_FAILURE, _("illegal year value"));
451 if (ctl.req.day) {
452 int dm = days_in_month[leap_year(ctl.req.year)][ctl.req.month];
453 if (ctl.req.day > dm)
454 errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), dm);
455 ctl.req.day = day_in_year(ctl.req.day, ctl.req.month, ctl.req.year);
456 } else if ((int32_t) (local_time->tm_year + 1900) == ctl.req.year) {
457 ctl.req.day = local_time->tm_yday + 1;
458 }
459 if (!ctl.req.month && !ctl.req.week) {
460 ctl.req.month = local_time->tm_mon + 1;
461 yflag = 1;
462 }
463 break;
464 case 0:
465 ctl.req.day = local_time->tm_yday + 1;
466 ctl.req.year = local_time->tm_year + 1900;
467 if (!ctl.req.month)
468 ctl.req.month = local_time->tm_mon + 1;
469 break;
470 default:
471 usage(stderr);
472 }
473
474 if (0 < ctl.req.week) {
475 int yday = week_to_day(&ctl);
476 int leap = leap_year(ctl.req.year);
477 int m = 1;
478
479 if (yday < 1)
480 errx(EXIT_FAILURE, _("illegal week value: year %d "
481 "doesn't have week %d"),
482 ctl.req.year, ctl.req.week);
483 while (m <= DECEMBER && yday > days_in_month[leap][m])
484 yday -= days_in_month[leap][m++];
485 if (DECEMBER < m && ctl.weektype & WEEK_NUM_ISO) {
486 /* In some years (e.g. 2010 in ISO mode) it's possible
487 * to have a remnant of week 53 starting the year yet
488 * the year in question ends during 52, in this case
489 * we're assuming that early remnant is being referred
490 * to if 53 is given as argument. */
491 if (ctl.req.week != week_number(31, DECEMBER, ctl.req.year - 1, &ctl))
492 errx(EXIT_FAILURE,
493 _("illegal week value: year %d "
494 "doesn't have week %d"),
495 ctl.req.year, ctl.req.week);
496 }
497 if (!ctl.req.month)
498 ctl.req.month = MONTHS_IN_YEAR < m ? 1 : m;
499 }
500
501 headers_init(&ctl);
502
503 if (!colors_init(ctl.colormode, "cal")) {
504 ctl.req.day = 0;
505 ctl.weektype &= ~WEEK_NUM_MASK;
506 }
507
508 if (yflag || Yflag) {
509 ctl.gutter_width = 3;
510 ctl.num_months = MONTHS_IN_YEAR;
511 if (yflag) {
512 ctl.req.start_month = 1; /* start from Jan */
513 ctl.header_year = 1; /* print year number */
514 }
515 }
516
517 if (ctl.num_months > 1 && ctl.months_in_row == 0)
518 ctl.months_in_row = ctl.julian ? MONTHS_IN_YEAR_ROW - 1 :
519 MONTHS_IN_YEAR_ROW;
520 else if (!ctl.months_in_row)
521 ctl.months_in_row = 1;
522
523 if (yflag || Yflag)
524 yearly(&ctl);
525 else
526 monthly(&ctl);
527
528 return EXIT_SUCCESS;
529 }
530
531 /* leap year -- account for gregorian reformation in 1752 */
532 static int leap_year(int32_t year)
533 {
534 if (year <= REFORMATION_YEAR)
535 return !(year % 4);
536 else
537 return ( !(year % 4) && (year % 100) ) || !(year % 400);
538 }
539
540 static void init_monthnames(struct cal_control *ctl)
541 {
542 size_t i;
543
544 if (ctl->full_month[0] != '\0')
545 return; /* already initialized */
546
547 for (i = 0; i < MONTHS_IN_YEAR; i++)
548 ctl->full_month[i] = nl_langinfo(MON_1 + i);
549 }
550
551 static int monthname_to_number(struct cal_control *ctl, const char *name)
552 {
553 size_t i;
554
555 init_monthnames(ctl);
556
557 for (i = 0; i < MONTHS_IN_YEAR; i++)
558 if (strcasecmp(ctl->full_month[i], name) == 0)
559 return i + 1;
560
561 return -EINVAL;
562 }
563
564 static void headers_init(struct cal_control *ctl)
565 {
566 size_t i, wd;
567 char *cur_dh = day_headings;
568 char tmp[FMT_ST_CHARS];
569 int year_len;
570
571 year_len = snprintf(tmp, sizeof(tmp), "%04d", ctl->req.year);
572
573 if (year_len < 0 || (size_t)year_len >= sizeof(tmp)) {
574 /* XXX impossible error */
575 return;
576 }
577
578 for (i = 0; i < DAYS_IN_WEEK; i++) {
579 size_t space_left;
580 wd = (i + ctl->weekstart) % DAYS_IN_WEEK;
581
582 if (i)
583 strcat(cur_dh++, " ");
584 space_left = sizeof(day_headings) - (cur_dh - day_headings);
585
586 if (space_left <= (ctl->day_width - 1))
587 break;
588 cur_dh += center_str(nl_langinfo(ABDAY_1 + wd), cur_dh,
589 space_left, ctl->day_width - 1);
590 }
591
592 init_monthnames(ctl);
593
594 for (i = 0; i < MONTHS_IN_YEAR; i++) {
595 /* The +1 after year_len is space in between month and year. */
596 if (ctl->week_width < strlen(ctl->full_month[i]) + year_len + 1)
597 ctl->header_hint = 1;
598 }
599 }
600
601 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl)
602 {
603 int first_week_day = day_in_week(1, month->month, month->year);
604 int month_days;
605 int i, j, weeklines = 0;
606
607 if (ctl->julian)
608 j = day_in_year(1, month->month, month->year);
609 else
610 j = 1;
611 month_days = j + days_in_month[leap_year(month->year)][month->month];
612
613 /* True when Sunday is not first day in the output week. */
614 if (ctl->weekstart) {
615 first_week_day -= ctl->weekstart;
616 if (first_week_day < 0)
617 first_week_day = DAYS_IN_WEEK - ctl->weekstart;
618 month_days += ctl->weekstart - 1;
619 }
620
621 /* Fill day array. */
622 for (i = 0; i < MAXDAYS; i++) {
623 if (0 < first_week_day) {
624 month->days[i] = SPACE;
625 first_week_day--;
626 continue;
627 }
628 if (j < month_days) {
629 if (month->year == REFORMATION_YEAR && month->month == REFORMATION_MONTH && (j == 3 || j == 247))
630 j += NUMBER_MISSING_DAYS;
631 month->days[i] = j;
632 j++;
633 continue;
634 }
635 month->days[i] = SPACE;
636 weeklines++;
637 }
638
639 /* Add week numbers */
640 if (ctl->weektype) {
641 int weeknum = week_number(1, month->month, month->year, ctl);
642 weeklines = MAXDAYS / DAYS_IN_WEEK - weeklines / DAYS_IN_WEEK;
643 for (i = 0; i < MAXDAYS / DAYS_IN_WEEK; i++) {
644 if (0 < weeklines) {
645 if (52 < weeknum)
646 weeknum = week_number(month->days[i * DAYS_IN_WEEK], month->month, month->year, ctl);
647 month->weeks[i] = weeknum++;
648 } else
649 month->weeks[i] = SPACE;
650 weeklines--;
651 }
652 }
653 }
654
655 static void cal_output_header(struct cal_month *month, const struct cal_control *ctl)
656 {
657 char out[FMT_ST_CHARS];
658 struct cal_month *i;
659
660 if (ctl->header_hint || ctl->header_year) {
661 for (i = month; i; i = i->next) {
662 sprintf(out, _("%s"), ctl->full_month[i->month - 1]);
663 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
664 }
665 if (!ctl->header_year) {
666 my_putstring("\n");
667 for (i = month; i; i = i->next) {
668 sprintf(out, _("%04d"), i->year);
669 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
670 }
671 }
672 } else {
673 for (i = month; i; i = i->next) {
674 sprintf(out, _("%s %04d"), ctl->full_month[i->month - 1], i->year);
675 center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
676 }
677 }
678 my_putstring("\n");
679 for (i = month; i; i = i->next) {
680 if (ctl->weektype) {
681 if (ctl->julian)
682 sprintf(out, "%*s%s", (int)ctl->day_width - 1, "", day_headings);
683 else
684 sprintf(out, "%*s%s", (int)ctl->day_width, "", day_headings);
685 my_putstring(out);
686 } else
687 my_putstring(day_headings);
688 if (i->next != NULL) {
689 sprintf(out, "%*s", ctl->gutter_width, "");
690 my_putstring(out);
691 }
692 }
693 my_putstring("\n");
694 }
695
696 static void cal_output_months(struct cal_month *month, const struct cal_control *ctl)
697 {
698 char out[FMT_ST_CHARS];
699 int reqday, week_line, d;
700 int skip;
701 struct cal_month *i;
702
703 for (week_line = 0; week_line < MAXDAYS / DAYS_IN_WEEK; week_line++) {
704 for (i = month; i; i = i->next) {
705 /* Determine the day that should be highlighted. */
706 reqday = 0;
707 if (i->month == ctl->req.month && i->year == ctl->req.year) {
708 if (ctl->julian)
709 reqday = ctl->req.day;
710 else
711 reqday =
712 ctl->req.day + 1 - day_in_year(1, i->month,
713 i->year);
714 }
715
716 if (ctl->weektype) {
717 if (0 < i->weeks[week_line]) {
718 if ((ctl->weektype & WEEK_NUM_MASK) ==
719 i->weeks[week_line])
720 sprintf(out, "%s%2d%s", Senter, i->weeks[week_line],
721 Sexit);
722 else
723 sprintf(out, "%2d", i->weeks[week_line]);
724 } else
725 sprintf(out, "%2s", "");
726 my_putstring(out);
727 skip = ctl->day_width;
728 } else
729 /* First day of the week is one char narrower than the other days,
730 * unless week number is printed. */
731 skip = ctl->day_width - 1;
732
733 for (d = DAYS_IN_WEEK * week_line;
734 d < DAYS_IN_WEEK * week_line + DAYS_IN_WEEK; d++) {
735 if (0 < i->days[d]) {
736 if (reqday == i->days[d])
737 sprintf(out, "%*s%s%*d%s", skip - (ctl->julian ? 3 : 2),
738 "", Senter, (ctl->julian ? 3 : 2),
739 i->days[d], Sexit);
740 else
741 sprintf(out, "%*d", skip, i->days[d]);
742 } else
743 sprintf(out, "%*s", skip, "");
744 my_putstring(out);
745 if (skip < (int)ctl->day_width)
746 skip++;
747 }
748 if (i->next != NULL) {
749 sprintf(out, "%*s", ctl->gutter_width, "");
750 my_putstring(out);
751 }
752 }
753 if (i == NULL) {
754 int extra = ctl->num_months > 3 ? 0 : 1;
755 sprintf(out, "%*s\n", ctl->gutter_width - extra, "");
756 my_putstring(out);
757 }
758 }
759 }
760
761 static void monthly(const struct cal_control *ctl)
762 {
763 struct cal_month m1,m2,m3, *m;
764 int i, rows, new_month, month = ctl->req.start_month ? ctl->req.start_month : ctl->req.month;
765 int32_t year = ctl->req.year;
766
767 /* cal -3, cal -Y --span, etc. */
768 if (ctl->span_months) {
769 new_month = month - ctl->num_months / 2;
770 if (new_month < 1) {
771 month = new_month + MONTHS_IN_YEAR;
772 year--;
773 }
774 else
775 month = new_month;
776 }
777
778 m1.next = (ctl->months_in_row > 1) ? &m2 : NULL;
779 m2.next = (ctl->months_in_row > 2) ? &m3 : NULL;
780 m3.next = NULL;
781
782 rows = (ctl->num_months - 1) / ctl->months_in_row;
783 for (i = 0; i < rows + 1 ; i++){
784 if (i == rows){
785 switch (ctl->num_months % ctl->months_in_row){
786 case 1:
787 m1.next = NULL;
788 /* fallthrough */
789 case 2:
790 m2.next = NULL;
791 /* fallthrough */
792 }
793 }
794 for (m = &m1; m; m = m->next){
795 m->month = month++;
796 m->year = year;
797 if (MONTHS_IN_YEAR < month) {
798 year++;
799 month = 1;
800 }
801 cal_fill_month(m, ctl);
802 }
803 cal_output_header(&m1, ctl);
804 cal_output_months(&m1, ctl);
805 }
806 }
807
808 static void yearly(const struct cal_control *ctl)
809 {
810 char out[FMT_ST_CHARS];
811 int year_width = 0;
812
813 year_width += (ctl->week_width + 1) * (ctl->julian ? 2 : 3);
814 if (ctl->julian)
815 year_width--;
816
817 if (ctl->header_year) {
818 sprintf(out, "%04d", ctl->req.year);
819 center(out, year_width, 0);
820 my_putstring("\n\n");
821 }
822 monthly(ctl);
823
824 /* Is empty line at the end year output really needed? */
825 my_putstring("\n");
826 }
827
828 /*
829 * day_in_year --
830 * return the 1 based day number within the year
831 */
832 static int day_in_year(int day, int month, int32_t year)
833 {
834 int i, leap;
835
836 leap = leap_year(year);
837 for (i = 1; i < month; i++)
838 day += days_in_month[leap][i];
839 return day;
840 }
841
842 /*
843 * day_in_week
844 * return the 0 based day number for any date from 1 Jan. 1 to
845 * 31 Dec. 9999. Assumes the Gregorian reformation eliminates
846 * 3 Sep. 1752 through 13 Sep. 1752, and returns invalid weekday
847 * during the period of 11 days.
848 */
849 static int day_in_week(int day, int month, int32_t year)
850 {
851 static const int reform[] = {
852 SUNDAY, WEDNESDAY, TUESDAY, FRIDAY, SUNDAY, WEDNESDAY,
853 FRIDAY, MONDAY, THURSDAY, SATURDAY, TUESDAY, THURSDAY
854 };
855 static const int old[] = {
856 FRIDAY, MONDAY, SUNDAY, WEDNESDAY, FRIDAY, MONDAY,
857 WEDNESDAY, SATURDAY, TUESDAY, THURSDAY, SUNDAY, TUESDAY
858 };
859 if (year != REFORMATION_YEAR + 1)
860 year -= month < MARCH;
861 else
862 year -= (month < MARCH) + 14;
863 if (REFORMATION_YEAR < year
864 || (year == REFORMATION_YEAR && REFORMATION_MONTH < month)
865 || (year == REFORMATION_YEAR && month == REFORMATION_MONTH && 13 < day)) {
866 int64_t long_year = year;
867 return (long_year + (year / 4) - (year / 100) + (year / 400) + reform[month - 1] +
868 day) % DAYS_IN_WEEK;
869 }
870 if (year < REFORMATION_YEAR
871 || (year == REFORMATION_YEAR && month < REFORMATION_MONTH)
872 || (year == REFORMATION_YEAR && month == REFORMATION_MONTH && day < 3))
873 return (year + year / 4 + old[month - 1] + day) % DAYS_IN_WEEK;
874 return NONEDAY;
875 }
876
877 /*
878 * week_number
879 * return the week number of a given date, 1..54.
880 * Supports ISO-8601 and North American modes.
881 * Day may be given as Julian day of the year mode, in which
882 * case the month is disregarded entirely.
883 */
884 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl)
885 {
886 int fday = 0, yday;
887 const int wday = day_in_week(1, JANUARY, year);
888
889 if (ctl->weektype & WEEK_NUM_ISO)
890 fday = wday + (wday >= FRIDAY ? -2 : 5);
891 else {
892 /* WEEK_NUM_US: Jan 1 is always First week, that may
893 * begin previous year. That means there is very seldom
894 * more than 52 weeks, */
895 fday = wday + 6;
896 }
897 /* For julian dates the month can be set to 1, the global julian
898 * variable cannot be relied upon here, because we may recurse
899 * internally for 31.12. which would not work. */
900 if (day > DAYS_IN_MONTH)
901 month = JANUARY;
902
903 yday = day_in_year(day,month,year);
904 if (year == REFORMATION_YEAR && yday >= YDAY_AFTER_MISSING)
905 fday -= NUMBER_MISSING_DAYS;
906
907 /* Last year is last year */
908 if (yday + fday < DAYS_IN_WEEK)
909 return week_number(31, DECEMBER, year - 1, ctl);
910
911 /* Or it could be part of the next year. The reformation year had less
912 * days than 365 making this check invalid, but reformation year ended
913 * on Sunday and in week 51, so it's ok here. */
914 if (ctl->weektype == WEEK_NUM_ISO && yday >= 363
915 && day_in_week(day, month, year) >= MONDAY
916 && day_in_week(day, month, year) <= WEDNESDAY
917 && day_in_week(31, DECEMBER, year) >= MONDAY
918 && day_in_week(31, DECEMBER, year) <= WEDNESDAY)
919 return week_number(1, JANUARY, year + 1, ctl);
920
921 return (yday + fday) / DAYS_IN_WEEK;
922 }
923
924 /*
925 * week_to_day
926 * return the yday of the first day in a given week inside
927 * the given year. This may be something other than Monday
928 * for ISO-8601 modes. For North American numbering this
929 * always returns a Sunday.
930 */
931 static int week_to_day(const struct cal_control *ctl)
932 {
933 int yday, wday;
934
935 wday = day_in_week(1, JANUARY, ctl->req.year);
936 yday = ctl->req.week * DAYS_IN_WEEK - wday;
937
938 if (ctl->weektype & WEEK_NUM_ISO)
939 yday -= (wday >= FRIDAY ? -2 : 5);
940 else
941 yday -= (wday == SUNDAY ? 6 : -1); /* WEEK_NUM_US */
942 if (yday <= 0)
943 return 1;
944
945 return yday;
946 }
947
948 /*
949 * Center string, handling multibyte characters appropriately.
950 * In addition if the string is too large for the width it's truncated.
951 * The number of trailing spaces may be 1 less than the number of leading spaces.
952 */
953 static int center_str(const char* src, char* dest,
954 size_t dest_size, size_t width)
955 {
956 return mbsalign(src, dest, dest_size, &width,
957 MBS_ALIGN_CENTER, MBA_UNIBYTE_FALLBACK);
958 }
959
960 static void center(const char *str, size_t len, int separate)
961 {
962 char lineout[FMT_ST_CHARS];
963
964 center_str(str, lineout, ARRAY_SIZE(lineout), len);
965 my_putstring(lineout);
966
967 if (separate) {
968 snprintf(lineout, sizeof(lineout), "%*s", separate, "");
969 my_putstring(lineout);
970 }
971 }
972
973 static void __attribute__ ((__noreturn__)) usage(FILE * out)
974 {
975 fputs(USAGE_HEADER, out);
976 fprintf(out, _(" %s [options] [[[day] month] year]\n"), program_invocation_short_name);
977 fprintf(out, _(" %s [options] <timestamp|monthname>\n"), program_invocation_short_name);
978
979 fputs(USAGE_SEPARATOR, out);
980 fputs(_("Display a calendar, or some part of it.\n"), out);
981 fputs(_("Without any arguments, display the current month.\n"), out);
982
983 fputs(USAGE_OPTIONS, out);
984 fputs(_(" -1, --one show only a single month (default)\n"), out);
985 fputs(_(" -3, --three show three months spanning the date\n"), out);
986 fputs(_(" -n, --months <num> show num months starting with date's month\n"), out);
987 fputs(_(" -S, --span span the date when displaying multiple months\n"), out);
988 fputs(_(" -s, --sunday Sunday as first day of week\n"), out);
989 fputs(_(" -m, --monday Monday as first day of week\n"), out);
990 fputs(_(" -j, --julian output Julian dates\n"), out);
991 fputs(_(" -y, --year show the whole year\n"), out);
992 fputs(_(" -Y, --twelve show the next twelve months\n"), out);
993 fputs(_(" -w, --week[=<num>] show US or ISO-8601 week numbers\n"), out);
994 fputs(_(" --color[=<when>] colorize messages (auto, always or never)\n"), out);
995 fprintf(out,
996 " %s\n", USAGE_COLORS_DEFAULT);
997
998 fputs(USAGE_SEPARATOR, out);
999 fputs(USAGE_HELP, out);
1000 fputs(USAGE_VERSION, out);
1001 fprintf(out, USAGE_MAN_TAIL("cal(1)"));
1002
1003 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
1004 }