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