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