xref: /freebsd/usr.bin/ncal/ncal.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1997 Wolfgang Helbig
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <calendar.h>
33 #include <ctype.h>
34 #include <err.h>
35 #include <langinfo.h>
36 #include <libgen.h>
37 #include <locale.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sysexits.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include <wchar.h>
45 #include <wctype.h>
46 #include <term.h>
47 #undef lines			/* term.h defines this */
48 
49 /* Width of one month with backward compatibility and in regular mode*/
50 #define MONTH_WIDTH_B_J 27
51 #define MONTH_WIDTH_B 20
52 
53 #define MONTH_WIDTH_R_J 24
54 #define MONTH_WIDTH_R 18
55 
56 #define MAX_WIDTH 64
57 
58 typedef struct date date;
59 
60 struct monthlines {
61 	wchar_t name[MAX_WIDTH + 1];
62 	char lines[7][MAX_WIDTH + 1];
63 	char weeks[MAX_WIDTH + 1];
64 	unsigned int extralen[7];
65 };
66 
67 struct weekdays {
68 	wchar_t names[7][4];
69 };
70 
71 /* The switches from Julian to Gregorian in some countries */
72 static struct djswitch {
73 	const char *cc;	/* Country code according to ISO 3166 */
74 	const char *nm;	/* Name of country */
75 	date dt;	/* Last day of Julian calendar */
76 } switches[] = {
77 	{"AL", "Albania",       {1912, 11, 30}},
78 	{"AT", "Austria",       {1583, 10,  5}},
79 	{"AU", "Australia",     {1752,  9,  2}},
80 	{"BE", "Belgium",       {1582, 12, 14}},
81 	{"BG", "Bulgaria",      {1916,  3, 31}},
82 	{"CA", "Canada",        {1752,  9,  2}},
83 	{"CH", "Switzerland",   {1655,  2, 28}},
84 	{"CN", "China",         {1911, 12, 18}},
85 	{"CZ", "Czech Republic",{1584,  1,  6}},
86 	{"DE", "Germany",       {1700,  2, 18}},
87 	{"DK", "Denmark",       {1700,  2, 18}},
88 	{"ES", "Spain",         {1582, 10,  4}},
89 	{"FI", "Finland",       {1753,  2, 17}},
90 	{"FR", "France",        {1582, 12,  9}},
91 	{"GB", "United Kingdom",{1752,  9,  2}},
92 	{"GR", "Greece",        {1924,  3,  9}},
93 	{"HU", "Hungary",       {1587, 10, 21}},
94 	{"IS", "Iceland",       {1700, 11, 16}},
95 	{"IT", "Italy",         {1582, 10,  4}},
96 	{"JP", "Japan",         {1918, 12, 18}},
97 	{"LT", "Lithuania",     {1918,  2,  1}},
98 	{"LU", "Luxembourg",    {1582, 12, 14}},
99 	{"LV", "Latvia",        {1918,  2,  1}},
100 	{"NL", "Netherlands",   {1582, 12, 14}},
101 	{"NO", "Norway",        {1700,  2, 18}},
102 	{"PL", "Poland",        {1582, 10,  4}},
103 	{"PT", "Portugal",      {1582, 10,  4}},
104 	{"RO", "Romania",       {1919,  3, 31}},
105 	{"RU", "Russia",        {1918,  1, 31}},
106 	{"SI", "Slovenia",      {1919,  3,  4}},
107 	{"SE", "Sweden",        {1753,  2, 17}},
108 	{"TR", "Turkey",        {1926, 12, 18}},
109 	{"US", "United States", {1752,  9,  2}},
110 	{"YU", "Yugoslavia",    {1919,  3,  4}}
111 };
112 
113 static struct djswitch *dftswitch =
114     switches + sizeof(switches) / sizeof(struct djswitch) - 2;
115     /* default switch (should be "US") */
116 
117 /* Table used to print day of month and week numbers */
118 static char daystr[] = "     1  2  3  4  5  6  7  8  9 10 11 12 13 14 15"
119 		       " 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31"
120 		       " 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47"
121 		       " 48 49 50 51 52 53";
122 
123 /* Table used to print day of year and week numbers */
124 static char jdaystr[] = "       1   2   3   4   5   6   7   8   9"
125 			"  10  11  12  13  14  15  16  17  18  19"
126 			"  20  21  22  23  24  25  26  27  28  29"
127 			"  30  31  32  33  34  35  36  37  38  39"
128 			"  40  41  42  43  44  45  46  47  48  49"
129 			"  50  51  52  53  54  55  56  57  58  59"
130 			"  60  61  62  63  64  65  66  67  68  69"
131 			"  70  71  72  73  74  75  76  77  78  79"
132 			"  80  81  82  83  84  85  86  87  88  89"
133 			"  90  91  92  93  94  95  96  97  98  99"
134 			" 100 101 102 103 104 105 106 107 108 109"
135 			" 110 111 112 113 114 115 116 117 118 119"
136 			" 120 121 122 123 124 125 126 127 128 129"
137 			" 130 131 132 133 134 135 136 137 138 139"
138 			" 140 141 142 143 144 145 146 147 148 149"
139 			" 150 151 152 153 154 155 156 157 158 159"
140 			" 160 161 162 163 164 165 166 167 168 169"
141 			" 170 171 172 173 174 175 176 177 178 179"
142 			" 180 181 182 183 184 185 186 187 188 189"
143 			" 190 191 192 193 194 195 196 197 198 199"
144 			" 200 201 202 203 204 205 206 207 208 209"
145 			" 210 211 212 213 214 215 216 217 218 219"
146 			" 220 221 222 223 224 225 226 227 228 229"
147 			" 230 231 232 233 234 235 236 237 238 239"
148 			" 240 241 242 243 244 245 246 247 248 249"
149 			" 250 251 252 253 254 255 256 257 258 259"
150 			" 260 261 262 263 264 265 266 267 268 269"
151 			" 270 271 272 273 274 275 276 277 278 279"
152 			" 280 281 282 283 284 285 286 287 288 289"
153 			" 290 291 292 293 294 295 296 297 298 299"
154 			" 300 301 302 303 304 305 306 307 308 309"
155 			" 310 311 312 313 314 315 316 317 318 319"
156 			" 320 321 322 323 324 325 326 327 328 329"
157 			" 330 331 332 333 334 335 336 337 338 339"
158 			" 340 341 342 343 344 345 346 347 348 349"
159 			" 350 351 352 353 354 355 356 357 358 359"
160 			" 360 361 362 363 364 365 366";
161 
162 static int flag_nohighlight;	/* user doesn't want a highlighted today */
163 static int flag_weeks;		/* user wants number of week */
164 static int nswitch;		/* user defined switch date */
165 static int nswitchb;		/* switch date for backward compatibility */
166 static int highlightdate;
167 
168 static char	*center(char *s, char *t, int w);
169 static wchar_t *wcenter(wchar_t *s, wchar_t *t, int w);
170 static int	firstday(int y, int m);
171 static void	highlight(char *dst, char *src, int len, int *extraletters);
172 static void	mkmonthr(int year, int month, int jd_flag,
173     struct monthlines * monthl);
174 static void	mkmonthb(int year, int month, int jd_flag,
175     struct monthlines * monthl);
176 static void	mkweekdays(struct weekdays * wds);
177 static void	monthranger(int year, int m, int jd_flag,
178     int before, int after);
179 static void	monthrangeb(int year, int m, int jd_flag,
180     int before, int after);
181 static int	parsemonth(const char *s, int *m, int *y);
182 static void	printcc(void);
183 static void	printeaster(int year, int julian, int orthodox);
184 static date	*sdater(int ndays, struct date * d);
185 static date	*sdateb(int ndays, struct date * d);
186 static int	sndaysr(struct date * d);
187 static int	sndaysb(struct date * d);
188 static void	usage(void);
189 
190 int
191 main(int argc, char *argv[])
192 {
193 	struct  djswitch *p, *q;	/* to search user defined switch date */
194 	date	never = {10000, 1, 1};	/* outside valid range of dates */
195 	date	ukswitch = {1752, 9, 2};/* switch date for Great Britain */
196 	date	dt;
197 	int     ch;			/* holds the option character */
198 	int     m = 0;			/* month */
199 	int	y = 0;			/* year */
200 	int     flag_backward = 0;	/* user called cal--backward compat. */
201 	int     flag_wholeyear = 0;	/* user wants the whole year */
202 	int	flag_julian_cal = 0;	/* user wants Julian Calendar */
203 	int     flag_julian_day = 0;	/* user wants the Julian day numbers */
204 	int	flag_orthodox = 0;	/* user wants Orthodox easter */
205 	int	flag_easter = 0;	/* user wants easter date */
206 	int	flag_3months = 0;	/* user wants 3 month display (-3) */
207 	int	flag_after = 0;		/* user wants to see months after */
208 	int	flag_before = 0;	/* user wants to see months before */
209 	int	flag_specifiedmonth = 0;/* user wants to see this month (-m) */
210 	int	flag_givenmonth = 0;	/* user has specified month [n] */
211 	int	flag_givenyear = 0;	/* user has specified year [n] */
212 	char	*cp;			/* character pointer */
213 	char	*flag_today = NULL;	/* debug: use date as being today */
214 	char	*flag_month = NULL;	/* requested month as string */
215 	char	*flag_highlightdate = NULL; /* debug: date to highlight */
216 	int	before, after;
217 	const char    *locale;		/* locale to get country code */
218 
219 	flag_nohighlight = 0;
220 	flag_weeks = 0;
221 
222 	/*
223 	 * Use locale to determine the country code,
224 	 * and use the country code to determine the default
225 	 * switchdate and date format from the switches table.
226 	 */
227 	if (setlocale(LC_ALL, "") == NULL)
228 		warn("setlocale");
229 	locale = setlocale(LC_TIME, NULL);
230 	if (locale == NULL ||
231 	    strcmp(locale, "C") == 0 ||
232 	    strcmp(locale, "POSIX") == 0 ||
233 	    strcmp(locale, "ASCII") == 0 ||
234 	    strcmp(locale, "US-ASCII") == 0)
235 		locale = "_US";
236 	q = switches + sizeof(switches) / sizeof(struct djswitch);
237 	for (p = switches; p != q; p++)
238 		if ((cp = strstr(locale, p->cc)) != NULL && *(cp - 1) == '_')
239 			break;
240 	if (p == q) {
241 		nswitch = ndaysj(&dftswitch->dt);
242 	} else {
243 		nswitch = ndaysj(&p->dt);
244 		dftswitch = p;
245 	}
246 
247 
248 	/*
249 	 * Get the filename portion of argv[0] and set flag_backward if
250 	 * this program is called "cal".
251 	 */
252 	if (strncmp(basename(argv[0]), "cal", strlen("cal")) == 0)
253 		flag_backward = 1;
254 
255 	/* Set the switch date to United Kingdom if backwards compatible */
256 	if (flag_backward)
257 		nswitchb = ndaysj(&ukswitch);
258 
259 	before = after = -1;
260 
261 	while ((ch = getopt(argc, argv, "3A:B:Cd:eH:hjJm:Nops:wy")) != -1)
262 		switch (ch) {
263 		case '3':
264 			flag_3months = 1;
265 			break;
266 		case 'A':
267 			if (flag_after > 0)
268 				errx(EX_USAGE, "Double -A specified");
269 			flag_after = strtol(optarg, NULL, 10);
270 			if (flag_after <= 0)
271 				errx(EX_USAGE,
272 				    "Argument to -A must be positive");
273 			break;
274 		case 'B':
275 			if (flag_before > 0)
276 				errx(EX_USAGE, "Double -A specified");
277 			flag_before = strtol(optarg, NULL, 10);
278 			if (flag_before <= 0)
279 				errx(EX_USAGE,
280 				    "Argument to -B must be positive");
281 			break;
282 		case 'J':
283 			if (flag_backward)
284 				usage();
285 			nswitch = ndaysj(&never);
286 			flag_julian_cal = 1;
287 			break;
288 		case 'C':
289 			flag_backward = 1;
290 			break;
291 		case 'N':
292 			flag_backward = 0;
293 			break;
294 		case 'd':
295 			flag_today = optarg;
296 			break;
297 		case 'H':
298 			flag_highlightdate = optarg;
299 			break;
300 		case 'h':
301 			flag_nohighlight = 1;
302 			break;
303 		case 'e':
304 			if (flag_backward)
305 				usage();
306 			flag_easter = 1;
307 			break;
308 		case 'j':
309 			flag_julian_day = 1;
310 			break;
311 		case 'm':
312 			if (flag_specifiedmonth)
313 				errx(EX_USAGE, "Double -m specified");
314 			flag_month = optarg;
315 			flag_specifiedmonth = 1;
316 			break;
317 		case 'o':
318 			if (flag_backward)
319 				usage();
320 			flag_orthodox = 1;
321 			flag_easter = 1;
322 			break;
323 		case 'p':
324 			if (flag_backward)
325 				usage();
326 			printcc();
327 			return (0);
328 			break;
329 		case 's':
330 			if (flag_backward)
331 				usage();
332 			q = switches +
333 			    sizeof(switches) / sizeof(struct djswitch);
334 			for (p = switches;
335 			     p != q && strcmp(p->cc, optarg) != 0; p++)
336 				;
337 			if (p == q)
338 				errx(EX_USAGE,
339 				    "%s: invalid country code", optarg);
340 			nswitch = ndaysj(&(p->dt));
341 			break;
342 		case 'w':
343 			if (flag_backward)
344 				usage();
345 			flag_weeks = 1;
346 			break;
347 		case 'y':
348 			flag_wholeyear = 1;
349 			break;
350 		default:
351 			usage();
352 		}
353 
354 	argc -= optind;
355 	argv += optind;
356 
357 	switch (argc) {
358 	case 2:
359 		if (flag_easter)
360 			usage();
361 		flag_month = *argv++;
362 		flag_givenmonth = 1;
363 		m = strtol(flag_month, NULL, 10);
364 		/* FALLTHROUGH */
365 	case 1:
366 		y = atoi(*argv);
367 		if (y < 1 || y > 9999)
368 			errx(EX_USAGE, "year `%s' not in range 1..9999", *argv);
369 		argv++;
370 		flag_givenyear = 1;
371 		break;
372 	case 0:
373 		if (flag_today != NULL) {
374 			y = strtol(flag_today, NULL, 10);
375 			m = strtol(flag_today + 5, NULL, 10);
376 		} else {
377 			time_t t;
378 			struct tm *tm;
379 
380 			t = time(NULL);
381 			tm = localtime(&t);
382 			y = tm->tm_year + 1900;
383 			m = tm->tm_mon + 1;
384 		}
385 		break;
386 	default:
387 		usage();
388 	}
389 
390 	if (flag_month != NULL) {
391 		if (parsemonth(flag_month, &m, &y)) {
392 			errx(EX_USAGE,
393 			    "%s is neither a month number (1..12) nor a name",
394 			    flag_month);
395 		}
396 	}
397 
398 	/*
399 	 * What is not supported:
400 	 * -3 with -A or -B
401 	 *	-3 displays 3 months, -A and -B change that behaviour.
402 	 * -3 with -y
403 	 *	-3 displays 3 months, -y says display a whole year.
404 	 * -3 with a given year but no given month or without -m
405 	 *	-3 displays 3 months, no month specified doesn't make clear
406 	 *      which three months.
407 	 * -m with a given month
408 	 *	conflicting arguments, both specify the same field.
409 	 * -y with -m
410 	 *	-y displays the whole year, -m displays a single month.
411 	 * -y with a given month
412 	 *	-y displays the whole year, the given month displays a single
413 	 *	month.
414 	 * -y with -A or -B
415 	 *	-y displays the whole year, -A and -B display extra months.
416 	 */
417 
418 	/* -3 together with -A or -B. */
419 	if (flag_3months && (flag_after || flag_before))
420 		errx(EX_USAGE, "-3 together with -A and -B is not supported.");
421 	/* -3 together with -y. */
422 	if (flag_3months && flag_wholeyear)
423 		errx(EX_USAGE, "-3 together with -y is not supported.");
424 	/* -3 together with givenyear but no givenmonth. */
425 	if (flag_3months && flag_givenyear &&
426 	    !(flag_givenmonth || flag_specifiedmonth))
427 		errx(EX_USAGE,
428 		    "-3 together with a given year but no given month is "
429 		    "not supported.");
430 	/* -m together with xx xxxx. */
431 	if (flag_specifiedmonth && flag_givenmonth)
432 		errx(EX_USAGE,
433 		    "-m together with a given month is not supported.");
434 	/* -y together with -m. */
435 	if (flag_wholeyear && flag_specifiedmonth)
436 		errx(EX_USAGE, "-y together with -m is not supported.");
437 	/* -y together with xx xxxx. */
438 	if (flag_wholeyear && flag_givenmonth)
439 		errx(EX_USAGE, "-y together a given month is not supported.");
440 	/* -y together with -A or -B. */
441 	if (flag_wholeyear && (flag_before > 0 || flag_after > 0))
442 		errx(EX_USAGE, "-y together a -A or -B is not supported.");
443 	/* The rest should be fine. */
444 
445 	/* Select the period to display, in order of increasing priority .*/
446 	if (flag_wholeyear ||
447 	    (flag_givenyear && !(flag_givenmonth || flag_specifiedmonth))) {
448 		m = 1;
449 		before = 0;
450 		after = 11;
451 	}
452 	if (flag_givenyear && flag_givenmonth) {
453 		before = 0;
454 		after = 0;
455 	}
456 	if (flag_specifiedmonth) {
457 		before = 0;
458 		after = 0;
459 	}
460 	if (flag_before) {
461 		before = flag_before;
462 	}
463 	if (flag_after) {
464 		after = flag_after;
465 	}
466 	if (flag_3months) {
467 		before = 1;
468 		after = 1;
469 	}
470 	if (after == -1)
471 		after = 0;
472 	if (before == -1)
473 		before = 0;
474 
475 	/* Highlight a specified day or today .*/
476 	if (flag_highlightdate != NULL) {
477 		dt.y = strtol(flag_highlightdate, NULL, 10);
478 		dt.m = strtol(flag_highlightdate + 5, NULL, 10);
479 		dt.d = strtol(flag_highlightdate + 8, NULL, 10);
480 	} else {
481 		time_t t;
482 		struct tm *tm1;
483 
484 		t = time(NULL);
485 		tm1 = localtime(&t);
486 		dt.y = tm1->tm_year + 1900;
487 		dt.m = tm1->tm_mon + 1;
488 		dt.d = tm1->tm_mday;
489 	}
490 	highlightdate = sndaysb(&dt);
491 
492 	/* And now we finally start to calculate and output calendars. */
493 	if (flag_easter)
494 		printeaster(y, flag_julian_cal, flag_orthodox);
495 	else
496 		if (flag_backward)
497 			monthrangeb(y, m, flag_julian_day, before, after);
498 		else
499 			monthranger(y, m, flag_julian_day, before, after);
500 	if (ferror(stdout) != 0 || fflush(stdout) != 0)
501 		err(1, "stdout");
502 	return (0);
503 }
504 
505 static void
506 usage(void)
507 {
508 
509 	fputs(
510 "Usage: cal [general options] [-hjy] [[month] year]\n"
511 "       cal [general options] [-hj] [-m month] [year]\n"
512 "       ncal [general options] [-hJjpwy] [-s country_code] [[month] year]\n"
513 "       ncal [general options] [-hJeo] [year]\n"
514 "General options: [-NC3] [-A months] [-B months]\n"
515 "For debug the highlighting: [-H yyyy-mm-dd] [-d yyyy-mm]\n",
516 	    stderr);
517 	exit(EX_USAGE);
518 }
519 
520 /* Print the assumed switches for all countries. */
521 static void
522 printcc(void)
523 {
524 	struct djswitch *p;
525 	int n;	/* number of lines to print */
526 	int m;	/* offset from left to right table entry on the same line */
527 
528 #define FSTR "%c%s %-15s%4d-%02d-%02d"
529 #define DFLT(p) ((p) == dftswitch ? '*' : ' ')
530 #define FSTRARG(p) DFLT(p), (p)->cc, (p)->nm, (p)->dt.y, (p)->dt.m, (p)->dt.d
531 
532 	n = sizeof(switches) / sizeof(struct djswitch);
533 	m = (n + 1) / 2;
534 	n /= 2;
535 	for (p = switches; p != switches + n; p++)
536 		printf(FSTR"     "FSTR"\n", FSTRARG(p), FSTRARG(p+m));
537 	if (m != n)
538 		printf(FSTR"\n", FSTRARG(p));
539 }
540 
541 /* Print the date of easter sunday. */
542 static void
543 printeaster(int y, int julian, int orthodox)
544 {
545 	date    dt;
546 	struct tm tm;
547 	char    buf[MAX_WIDTH];
548 	static int d_first = -1;
549 
550 	if (d_first < 0)
551 		d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
552 	/* force orthodox easter for years before 1583 */
553 	if (y < 1583)
554 		orthodox = 1;
555 
556 	if (orthodox)
557 		if (julian)
558 			easteroj(y, &dt);
559 		else
560 			easterog(y, &dt);
561 	else
562 		easterg(y, &dt);
563 
564 	memset(&tm, 0, sizeof(tm));
565 	tm.tm_year = dt.y - 1900;
566 	tm.tm_mon  = dt.m - 1;
567 	tm.tm_mday = dt.d;
568 	strftime(buf, sizeof(buf), d_first ? "%e %B %Y" : "%B %e %Y",  &tm);
569 	printf("%s\n", buf);
570 }
571 
572 #define MW(mw, me)		((mw) + me)
573 #define	DECREASEMONTH(m, y) 		\
574 		if (--m == 0) {		\
575 			m = 12;		\
576 			y--;		\
577 		}
578 #define	INCREASEMONTH(m, y)		\
579 		if (++(m) == 13) {	\
580 			(m) = 1;	\
581 			(y)++;		\
582 		}
583 #define	M2Y(m)	((m) / 12)
584 #define	M2M(m)	(1 + (m) % 12)
585 
586 /* Print all months for the period in the range [ before .. y-m .. after ]. */
587 static void
588 monthrangeb(int y, int m, int jd_flag, int before, int after)
589 {
590 	struct monthlines year[12];
591 	struct weekdays wds;
592 	char	s[MAX_WIDTH], t[MAX_WIDTH];
593 	wchar_t	ws[MAX_WIDTH], ws1[MAX_WIDTH];
594 	const char	*wdss;
595 	int     i, j;
596 	int     mpl;
597 	int     mw;
598 	int	m1, m2;
599 	int	printyearheader;
600 	int	prevyear = -1;
601 
602 	mpl = jd_flag ? 2 : 3;
603 	mw = jd_flag ? MONTH_WIDTH_B_J : MONTH_WIDTH_B;
604 	wdss = (mpl == 2) ? " " : "";
605 
606 	while (before != 0) {
607 		DECREASEMONTH(m, y);
608 		before--;
609 		after++;
610 	}
611 	m1 = y * 12 + m - 1;
612 	m2 = m1 + after;
613 
614 	mkweekdays(&wds);
615 
616 	/*
617 	 * The year header is printed when there are more than 'mpl' months
618 	 * and if the first month is a multitude of 'mpl'.
619 	 * If not, it will print the year behind every month.
620 	 */
621 	printyearheader = (after >= mpl - 1) && (M2M(m1) - 1) % mpl == 0;
622 
623 	m = m1;
624 	while (m <= m2) {
625 		int count = 0;
626 		for (i = 0; i != mpl && m + i <= m2; i++) {
627 			mkmonthb(M2Y(m + i), M2M(m + i) - 1, jd_flag, year + i);
628 			count++;
629 		}
630 
631 		/* Empty line between two rows of months */
632 		if (m != m1)
633 			printf("\n");
634 
635 		/* Year at the top. */
636 		if (printyearheader && M2Y(m) != prevyear) {
637 			sprintf(s, "%d", M2Y(m));
638 			printf("%s\n", center(t, s, mpl * mw));
639 			prevyear = M2Y(m);
640 		}
641 
642 		/* Month names. */
643 		for (i = 0; i < count; i++)
644 			if (printyearheader)
645 				wprintf(L"%-*ls  ",
646 				    mw, wcenter(ws, year[i].name, mw));
647 			else {
648 				swprintf(ws, sizeof(ws)/sizeof(ws[0]),
649 				    L"%-ls %d", year[i].name, M2Y(m + i));
650 				wprintf(L"%-*ls  ", mw, wcenter(ws1, ws, mw));
651 			}
652 		printf("\n");
653 
654 		/* Day of the week names. */
655 		for (i = 0; i < count; i++) {
656 			wprintf(L"%s%ls%s%ls%s%ls%s%ls%s%ls%s%ls%s%ls ",
657 				wdss, wds.names[6], wdss, wds.names[0],
658 				wdss, wds.names[1], wdss, wds.names[2],
659 				wdss, wds.names[3], wdss, wds.names[4],
660 				wdss, wds.names[5]);
661 		}
662 		printf("\n");
663 
664 		/* And the days of the month. */
665 		for (i = 0; i != 6; i++) {
666 			for (j = 0; j < count; j++)
667 				printf("%-*s  ",
668 				    MW(mw, year[j].extralen[i]),
669 					year[j].lines[i]+1);
670 			printf("\n");
671 		}
672 
673 		m += mpl;
674 	}
675 }
676 
677 static void
678 monthranger(int y, int m, int jd_flag, int before, int after)
679 {
680 	struct monthlines year[12];
681 	struct weekdays wds;
682 	char    s[MAX_WIDTH], t[MAX_WIDTH];
683 	int     i, j;
684 	int     mpl;
685 	int     mw;
686 	int	m1, m2;
687 	int	prevyear = -1;
688 	int	printyearheader;
689 
690 	mpl = jd_flag ? 3 : 4;
691 	mw = jd_flag ? MONTH_WIDTH_R_J : MONTH_WIDTH_R;
692 
693 	while (before != 0) {
694 		DECREASEMONTH(m, y);
695 		before--;
696 		after++;
697 	}
698 	m1 = y * 12 + m - 1;
699 	m2 = m1 + after;
700 
701 	mkweekdays(&wds);
702 
703 	/*
704 	 * The year header is printed when there are more than 'mpl' months
705 	 * and if the first month is a multitude of 'mpl'.
706 	 * If not, it will print the year behind every month.
707 	 */
708 	printyearheader = (after >= mpl - 1) && (M2M(m1) - 1) % mpl == 0;
709 
710 	m = m1;
711 	while (m <= m2) {
712 		int count = 0;
713 		for (i = 0; i != mpl && m + i <= m2; i++) {
714 			mkmonthr(M2Y(m + i), M2M(m + i) - 1, jd_flag, year + i);
715 			count++;
716 		}
717 
718 		/* Empty line between two rows of months. */
719 		if (m != m1)
720 			printf("\n");
721 
722 		/* Year at the top. */
723 		if (printyearheader && M2Y(m) != prevyear) {
724 			sprintf(s, "%d", M2Y(m));
725 			printf("%s\n", center(t, s, mpl * mw));
726 			prevyear = M2Y(m);
727 		}
728 
729 		/* Month names. */
730 		wprintf(L"    ");
731 		for (i = 0; i < count; i++)
732 			if (printyearheader)
733 				wprintf(L"%-*ls", mw, year[i].name);
734 			else
735 				wprintf(L"%-ls %-*d", year[i].name,
736 				    mw - wcslen(year[i].name) - 1, M2Y(m + i));
737 		printf("\n");
738 
739 		/* And the days of the month. */
740 		for (i = 0; i != 7; i++) {
741 			/* Week day */
742 			wprintf(L"%.2ls", wds.names[i]);
743 
744 			/* Full months */
745 			for (j = 0; j < count; j++)
746 				printf("%-*s",
747 				    MW(mw, year[j].extralen[i]),
748 					year[j].lines[i]);
749 			printf("\n");
750 		}
751 
752 		/* Week numbers. */
753 		if (flag_weeks) {
754 			printf("  ");
755 			for (i = 0; i < count; i++)
756 				printf("%-*s", mw, year[i].weeks);
757 			printf("\n");
758 		}
759 
760 		m += mpl;
761 	}
762 	return;
763 }
764 
765 static void
766 mkmonthr(int y, int m, int jd_flag, struct monthlines *mlines)
767 {
768 
769 	struct tm tm;		/* for strftime printing local names of
770 				 * months */
771 	date    dt;		/* handy date */
772 	int     dw;		/* width of numbers */
773 	int     first;		/* first day of month */
774 	int     firstm;		/* first day of first week of month */
775 	int     i, j, k, l;	/* just indices */
776 	int     last;		/* the first day of next month */
777 	int     jan1 = 0;	/* the first day of this year */
778 	char   *ds;		/* pointer to day strings (daystr or
779 				 * jdaystr) */
780 
781 	/* Set name of month. */
782 	memset(&tm, 0, sizeof(tm));
783 	tm.tm_mon = m;
784 	wcsftime(mlines->name, sizeof(mlines->name) / sizeof(mlines->name[0]),
785 		 L"%OB", &tm);
786 	mlines->name[0] = towupper(mlines->name[0]);
787 
788 	/*
789 	 * Set first and last to the day number of the first day of this
790 	 * month and the first day of next month respectively. Set jan1 to
791 	 * the day number of the first day of this year.
792 	 */
793 	first = firstday(y, m + 1);
794 	if (m == 11)
795 		last = firstday(y + 1, 1);
796 	else
797 		last = firstday(y, m + 2);
798 
799 	if (jd_flag)
800 		jan1 = firstday(y, 1);
801 
802 	/*
803 	 * Set firstm to the day number of monday of the first week of
804 	 * this month. (This might be in the last month)
805 	 */
806 	firstm = first - weekday(first);
807 
808 	/* Set ds (daystring) and dw (daywidth) according to the jd_flag. */
809 	if (jd_flag) {
810 		ds = jdaystr;
811 		dw = 4;
812 	} else {
813 		ds = daystr;
814 		dw = 3;
815 	}
816 
817 	/*
818 	 * Fill the lines with day of month or day of year (julian day)
819 	 * line index: i, each line is one weekday. column index: j, each
820 	 * column is one day number. print column index: k.
821 	 */
822 	for (i = 0; i != 7; i++) {
823 		l = 0;
824 		for (j = firstm + i, k = 0; j < last; j += 7, k += dw) {
825 			if (j >= first) {
826 				if (jd_flag)
827 					dt.d = j - jan1 + 1;
828 				else
829 					sdater(j, &dt);
830 				if (j == highlightdate && !flag_nohighlight
831 				 && isatty(STDOUT_FILENO))
832 					highlight(mlines->lines[i] + k,
833 					    ds + dt.d * dw, dw, &l);
834 				else
835 					memcpy(mlines->lines[i] + k + l,
836 					       ds + dt.d * dw, dw);
837 			} else
838 				memcpy(mlines->lines[i] + k + l, "    ", dw);
839 		}
840 		mlines->lines[i][k + l] = '\0';
841 		mlines->extralen[i] = l;
842 	}
843 
844 	/* fill the weeknumbers. */
845 	if (flag_weeks) {
846 		for (j = firstm, k = 0; j < last;  k += dw, j += 7)
847 			if (j <= nswitch)
848 				memset(mlines->weeks + k, ' ', dw);
849 			else
850 				memcpy(mlines->weeks + k,
851 				    ds + week(j, &i)*dw, dw);
852 		mlines->weeks[k] = '\0';
853 	}
854 }
855 
856 static void
857 mkmonthb(int y, int m, int jd_flag, struct monthlines *mlines)
858 {
859 
860 	struct tm tm;		/* for strftime printing local names of
861 				 * months */
862 	date    dt;		/* handy date */
863 	int     dw;		/* width of numbers */
864 	int     first;		/* first day of month */
865 	int     firsts;		/* sunday of first week of month */
866 	int     i, j, k, l;	/* just indices */
867 	int     jan1 = 0;	/* the first day of this year */
868 	int     last;		/* the first day of next month */
869 	char   *ds;		/* pointer to day strings (daystr or
870 				 * jdaystr) */
871 
872 	/* Set ds (daystring) and dw (daywidth) according to the jd_flag */
873 	if (jd_flag) {
874 		ds = jdaystr;
875 		dw = 4;
876 	} else {
877 		ds = daystr;
878 		dw = 3;
879 	}
880 
881 	/* Set name of month centered. */
882 	memset(&tm, 0, sizeof(tm));
883 	tm.tm_mon = m;
884 	wcsftime(mlines->name, sizeof(mlines->name) / sizeof(mlines->name[0]),
885 		 L"%OB", &tm);
886 	mlines->name[0] = towupper(mlines->name[0]);
887 
888 	/*
889 	 * Set first and last to the day number of the first day of this
890 	 * month and the first day of next month respectively. Set jan1 to
891 	 * the day number of Jan 1st of this year.
892 	 */
893 	dt.y = y;
894 	dt.m = m + 1;
895 	dt.d = 1;
896 	first = sndaysb(&dt);
897 	if (m == 11) {
898 		dt.y = y + 1;
899 		dt.m = 1;
900 		dt.d = 1;
901 	} else {
902 		dt.y = y;
903 		dt.m = m + 2;
904 		dt.d = 1;
905 	}
906 	last = sndaysb(&dt);
907 
908 	if (jd_flag) {
909 		dt.y = y;
910 		dt.m = 1;
911 		dt.d = 1;
912 		jan1 = sndaysb(&dt);
913 	}
914 
915 	/*
916 	 * Set firsts to the day number of sunday of the first week of
917 	 * this month. (This might be in the last month)
918 	 */
919 	firsts = first - (weekday(first)+1) % 7;
920 
921 	/*
922 	 * Fill the lines with day of month or day of year (Julian day)
923 	 * line index: i, each line is one week. column index: j, each
924 	 * column is one day number. print column index: k.
925 	 */
926 	for (i = 0; i != 6; i++) {
927 		l = 0;
928 		for (j = firsts + 7 * i, k = 0; j < last && k != dw * 7;
929 		    j++, k += dw) {
930 			if (j >= first) {
931 				if (jd_flag)
932 					dt.d = j - jan1 + 1;
933 				else
934 					sdateb(j, &dt);
935 				if (j == highlightdate && !flag_nohighlight
936 				 && isatty(STDOUT_FILENO))
937 					highlight(mlines->lines[i] + k,
938 					    ds + dt.d * dw, dw, &l);
939 				else
940 					memcpy(mlines->lines[i] + k + l,
941 					       ds + dt.d * dw, dw);
942 			} else
943 				memcpy(mlines->lines[i] + k + l, "    ", dw);
944 		}
945 		if (k == 0)
946 			mlines->lines[i][1] = '\0';
947 		else
948 			mlines->lines[i][k + l] = '\0';
949 		mlines->extralen[i] = l;
950 	}
951 }
952 
953 /* Put the local names of weekdays into the wds. */
954 static void
955 mkweekdays(struct weekdays *wds)
956 {
957 	int i, len, width = 0;
958 	struct tm tm;
959 	wchar_t buf[20];
960 
961 	memset(&tm, 0, sizeof(tm));
962 
963 	for (i = 0; i != 7; i++) {
964 		tm.tm_wday = (i+1) % 7;
965 		wcsftime(buf, sizeof(buf)/sizeof(buf[0]), L"%a", &tm);
966 		for (len = 2; len > 0; --len) {
967 			if ((width = wcswidth(buf, len)) <= 2)
968 				break;
969 		}
970 		wmemset(wds->names[i], L'\0', 4);
971 		if (width == 1)
972 			wds->names[i][0] = L' ';
973 		wcsncat(wds->names[i], buf, len);
974 		wcsncat(wds->names[i], L" ", 1);
975 	}
976 }
977 
978 /*
979  * Compute the day number of the first existing date after the first day in
980  * month. (the first day in month and even the month might not exist!)
981  */
982 static int
983 firstday(int y, int m)
984 {
985 	date dt;
986 	int nd;
987 
988 	dt.y = y;
989 	dt.m = m;
990 	dt.d = 1;
991 	nd = sndaysr(&dt);
992 	for (;;) {
993 		sdater(nd, &dt);
994 		if ((dt.m >= m && dt.y == y) || dt.y > y)
995 			return (nd);
996 		else
997 			nd++;
998 	}
999 	/* NEVER REACHED */
1000 }
1001 
1002 /*
1003  * Compute the number of days from date, obey the local switch from
1004  * Julian to Gregorian if specified by the user.
1005  */
1006 static int
1007 sndaysr(struct date *d)
1008 {
1009 
1010 	if (nswitch != 0)
1011 		if (nswitch < ndaysj(d))
1012 			return (ndaysg(d));
1013 		else
1014 			return (ndaysj(d));
1015 	else
1016 		return ndaysg(d);
1017 }
1018 
1019 /*
1020  * Compute the number of days from date, obey the switch from
1021  * Julian to Gregorian as used by UK and her colonies.
1022  */
1023 static int
1024 sndaysb(struct date *d)
1025 {
1026 
1027 	if (nswitchb < ndaysj(d))
1028 		return (ndaysg(d));
1029 	else
1030 		return (ndaysj(d));
1031 }
1032 
1033 /* Inverse of sndays. */
1034 static struct date *
1035 sdater(int nd, struct date *d)
1036 {
1037 
1038 	if (nswitch < nd)
1039 		return (gdate(nd, d));
1040 	else
1041 		return (jdate(nd, d));
1042 }
1043 
1044 /* Inverse of sndaysb. */
1045 static struct date *
1046 sdateb(int nd, struct date *d)
1047 {
1048 
1049 	if (nswitchb < nd)
1050 		return (gdate(nd, d));
1051 	else
1052 		return (jdate(nd, d));
1053 }
1054 
1055 /* Center string t in string s of length w by putting enough leading blanks. */
1056 static char *
1057 center(char *s, char *t, int w)
1058 {
1059 	char blanks[MAX_WIDTH];
1060 
1061 	memset(blanks, ' ', sizeof(blanks));
1062 	sprintf(s, "%.*s%s", (int)(w - strlen(t)) / 2, blanks, t);
1063 	return (s);
1064 }
1065 
1066 /* Center string t in string s of length w by putting enough leading blanks. */
1067 static wchar_t *
1068 wcenter(wchar_t *s, wchar_t *t, int w)
1069 {
1070 	char blanks[MAX_WIDTH];
1071 
1072 	memset(blanks, ' ', sizeof(blanks));
1073 	swprintf(s, MAX_WIDTH, L"%.*s%ls", (int)(w - wcslen(t)) / 2, blanks, t);
1074 	return (s);
1075 }
1076 
1077 static int
1078 parsemonth(const char *s, int *m, int *y)
1079 {
1080 	int nm, ny;
1081 	char *cp;
1082 	struct tm tm;
1083 
1084 	nm = (int)strtol(s, &cp, 10);
1085 	if (cp != s) {
1086 		ny = *y;
1087 		if (*cp == '\0') {
1088 			;	/* no special action */
1089 		} else if (*cp == 'f' || *cp == 'F') {
1090 			if (nm <= *m)
1091 				ny++;
1092 		} else if (*cp == 'p' || *cp == 'P') {
1093 			if (nm >= *m)
1094 				ny--;
1095 		} else
1096 			return (1);
1097 		if (nm < 1 || nm > 12)
1098 			return 1;
1099 		*m = nm;
1100 		*y = ny;
1101 		return (0);
1102 	}
1103 	if (strptime(s, "%B", &tm) != NULL || strptime(s, "%b", &tm) != NULL) {
1104 		*m = tm.tm_mon + 1;
1105 		return (0);
1106 	}
1107 	return (1);
1108 }
1109 
1110 static void
1111 highlight(char *dst, char *src, int len, int *extralen)
1112 {
1113 	static int first = 1;
1114 	static const char *term_so, *term_se;
1115 
1116 	if (first) {
1117 		static char cbuf[512];
1118 		char tbuf[1024], *b;
1119 
1120 		term_se = term_so = NULL;
1121 
1122 		/* On how to highlight on this type of terminal (if any). */
1123 		if (isatty(STDOUT_FILENO) && tgetent(tbuf, NULL) == 1) {
1124 			b = cbuf;
1125 			term_so = tgetstr("so", &b);
1126 			term_se = tgetstr("se", &b);
1127 		}
1128 
1129 		first = 0;
1130 	}
1131 
1132 	/*
1133 	 * This check is not necessary, should have been handled before calling
1134 	 * this function.
1135 	 */
1136 	if (flag_nohighlight) {
1137 		memcpy(dst, src, len);
1138 		return;
1139 	}
1140 
1141 	/*
1142 	 * If it is a real terminal, use the data from the termcap database.
1143 	 */
1144 	if (term_so != NULL && term_se != NULL) {
1145 		/* separator. */
1146 		dst[0] = ' ';
1147 		dst++;
1148 		/* highlight on. */
1149 		memcpy(dst, term_so, strlen(term_so));
1150 		dst += strlen(term_so);
1151 		/* the actual text. (minus leading space) */
1152 		len--;
1153 		src++;
1154 		memcpy(dst, src, len);
1155 		dst += len;
1156 		/* highlight off. */
1157 		memcpy(dst, term_se, strlen(term_se));
1158 		*extralen = strlen(term_so) + strlen(term_se);
1159 		return;
1160 	}
1161 
1162 	/*
1163 	 * Otherwise, print a _, backspace and the letter.
1164 	 */
1165 	*extralen = 0;
1166 	/* skip leading space. */
1167 	src++;
1168 	len--;
1169 	/* separator. */
1170 	dst[0] = ' ';
1171 	dst++;
1172 	while (len > 0) {
1173 		/* _ and backspace. */
1174 		memcpy(dst, "_\010", 2);
1175 		dst += 2;
1176 		*extralen += 2;
1177 		/* the character. */
1178 		*dst++ = *src++;
1179 		len--;
1180 	}
1181 	return;
1182 }
1183