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