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