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