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