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