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