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