commit 70e5f00193eb8fa8fddaa7cda335522e0bd5b923 Author: Kartik K. Agaram Date: Tue Feb 15 14:37:22 2022 -0800 from bsdmainutils 11.1.2ubuntu3 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7d0826d --- /dev/null +++ b/Makefile @@ -0,0 +1,12 @@ +PROG = ncal +SRC = ncal.c calendar.c easter.c +FLAGS = -D_GNU_SOURCE -include bsd/string.h + +LIBS += -ltinfo -lbsd + +topdir=../.. +include $(topdir)/config.mk + +install-2: + (cd $(bindir); ln -sf ncal cal) + (cd $(mandir); ln -sf ncal.1 cal.1) diff --git a/calendar.3 b/calendar.3 new file mode 100644 index 0000000..01aabd2 --- /dev/null +++ b/calendar.3 @@ -0,0 +1,203 @@ +.\" Copyright (c) 1997 Wolfgang Helbig +.\" All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" $FreeBSD: head/lib/libcalendar/calendar.3 267773 2014-06-23 08:23:05Z bapt $ +.\" +.Dd November 29, 1997 +.Dt CALENDAR 3 +.Os +.Sh NAME +.Nm easterg , +.Nm easterog , +.Nm easteroj , +.Nm gdate , +.Nm jdate , +.Nm ndaysg , +.Nm ndaysj , +.Nm week , +.Nm weekday +.Nd Calendar arithmetic for the Christian era +.Sh LIBRARY +.Lb libcalendar +.Sh SYNOPSIS +.In calendar.h +.Ft struct date * +.Fn easterg "int year" "struct date *dt" +.Ft struct date * +.Fn easterog "int year" "struct date *dt" +.Ft struct date * +.Fn easteroj "int year" "struct date *dt" +.Ft struct date * +.Fn gdate "int nd" "struct date *dt" +.Ft struct date * +.Fn jdate "int nd" "struct date *dt" +.Ft int +.Fn ndaysg "struct date *dt" +.Ft int +.Fn ndaysj "struct date *dt" +.Ft int +.Fn week "int nd" "int *year" +.Ft int +.Fn weekday "int nd" +.Sh DESCRIPTION +These functions provide calendar arithmetic for a large range of years, +starting at March 1st, year zero (i.e., 1 B.C.) and ending way beyond +year 100000. +.Pp +Programs should be linked with +.Fl lcalendar . +.Pp +The functions +.Fn easterg , +.Fn easterog +and +.Fn easteroj +store the date of Easter Sunday into the structure pointed at by +.Fa dt +and return a pointer to this structure. +The function +.Fn easterg +assumes Gregorian Calendar (adopted by most western churches after 1582) and +the functions +.Fn easterog +and +.Fn easteroj +compute the date of Easter Sunday according to the orthodox rules +(Western churches before 1582, Greek and Russian Orthodox Church +until today). +The result returned by +.Fn easterog +is the date in Gregorian Calendar, whereas +.Fn easteroj +returns the date in Julian Calendar. +.Pp +The functions +.Fn gdate , +.Fn jdate , +.Fn ndaysg +and +.Fn ndaysj +provide conversions between the common "year, month, day" notation +of a date and the "number of days" representation, which is better suited +for calculations. +The days are numbered from March 1st year 1 B.C., starting +with zero, so the number of a day gives the number of days since March 1st, +year 1 B.C. +The conversions work for nonnegative day numbers only. +.Pp +The +.Fn gdate +and +.Fn jdate +functions +store the date corresponding to the day number +.Fa nd +into the structure pointed at by +.Fa dt +and return a pointer to this structure. +.Pp +The +.Fn ndaysg +and +.Fn ndaysj +functions +return the day number of the date pointed at by +.Fa dt . +.Pp +The +.Fn gdate +and +.Fn ndaysg +functions +assume Gregorian Calendar after October 4, 1582 and Julian Calendar before, +whereas +.Fn jdate +and +.Fn ndaysj +assume Julian Calendar throughout. +.Pp +The two calendars differ by the definition of the leap year. +The +Julian Calendar says every year that is a multiple of four is a +leap year. +The Gregorian Calendar excludes years that are multiples of +100 and not multiples of 400. +This means the years 1700, 1800, 1900, 2100 are not leap years +and the year 2000 is +a leap year. +The new rules were inaugurated on October 4, 1582 by deleting ten +days following this date. +Most catholic countries adopted the new +calendar by the end of the 16th century, whereas others stayed with +the Julian Calendar until the 20th century. +The United Kingdom and +their colonies switched on September 2, 1752. +They already had to +delete 11 days. +.Pp +The function +.Fn week +returns the number of the week which contains the day numbered +.Fa nd . +The argument +.Fa *year +is set with the year that contains (the greater part of) the week. +The weeks are numbered per year starting with week 1, which is the +first week in a year that includes more than three days of the year. +Weeks start on Monday. +This function is defined for Gregorian Calendar only. +.Pp +The function +.Fn weekday +returns the weekday (Mo = 0 ..\& Su = 6) of the day numbered +.Fa nd . +.Pp +The structure +.Fa date +is defined in +.In calendar.h . +It contains these fields: +.Bd -literal -offset indent +int y; /\(** year (0000 - ????) \(**/ +int m; /\(** month (1 - 12) \(**/ +int d; /\(** day of month (1 - 31) \(**/ +.Ed +.Pp +The year zero is written as "1 B.C." by historians and "0" by astronomers +and in this library. +.Sh SEE ALSO +.Xr ncal 1 , +.Xr strftime 3 +.Sh STANDARDS +The week number conforms to ISO 8601: 1988. +.Sh HISTORY +The +.Nm calendar +library first appeared in +.Fx 3.0 . +.Sh AUTHORS +This manual page and the library was written by +.An Wolfgang Helbig Aq Mt helbig@FreeBSD.org . +.Sh BUGS +The library was coded with great care so there are no bugs left. diff --git a/calendar.c b/calendar.c new file mode 100644 index 0000000..5920978 --- /dev/null +++ b/calendar.c @@ -0,0 +1,335 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause-FreeBSD + * + * Copyright (c) 1997 Wolfgang Helbig + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#include +__FBSDID("$FreeBSD: head/lib/libcalendar/calendar.c 326219 2017-11-26 02:00:33Z pfg $"); + +#include "calendar.h" +extern int weekstart; + +#ifndef NULL +#define NULL 0 +#endif + +/* + * For each month tabulate the number of days elapsed in a year before the + * month. This assumes the internal date representation, where a year + * starts on March 1st. So we don't need a special table for leap years. + * But we do need a special table for the year 1582, since 10 days are + * deleted in October. This is month1s for the switch from Julian to + * Gregorian calendar. + */ +static int const month1[] = + {0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337}; + /* M A M J J A S O N D J */ +static int const month1s[]= + {0, 31, 61, 92, 122, 153, 184, 214, 235, 265, 296, 327}; + +typedef struct date date; + +/* The last day of Julian calendar, in internal and ndays representation */ +static int nswitch; /* The last day of Julian calendar */ +static date jiswitch = {1582, 7, 3}; + +static date *date2idt(date *idt, date *dt); +static date *idt2date(date *dt, date *idt); +static int ndaysji(date *idt); +static int ndaysgi(date *idt); +static int firstweek(int year); + +/* + * Compute the Julian date from the number of days elapsed since + * March 1st of year zero. + */ +date * +jdate(int ndays, date *dt) +{ + date idt; /* Internal date representation */ + int r; /* hold the rest of days */ + + /* + * Compute the year by starting with an approximation not smaller + * than the answer and using linear search for the greatest + * year which does not begin after ndays. + */ + idt.y = ndays / 365; + idt.m = 0; + idt.d = 0; + while ((r = ndaysji(&idt)) > ndays) + idt.y--; + + /* + * Set r to the days left in the year and compute the month by + * linear search as the largest month that does not begin after r + * days. + */ + r = ndays - r; + for (idt.m = 11; month1[idt.m] > r; idt.m--) + ; + + /* Compute the days left in the month */ + idt.d = r - month1[idt.m]; + + /* return external representation of the date */ + return (idt2date(dt, &idt)); +} + +/* + * Return the number of days since March 1st of the year zero. + * The date is given according to Julian calendar. + */ +int +ndaysj(date *dt) +{ + date idt; /* Internal date representation */ + + if (date2idt(&idt, dt) == NULL) + return (-1); + else + return (ndaysji(&idt)); +} + +/* + * Same as above, where the Julian date is given in internal notation. + * This formula shows the beauty of this notation. + */ +static int +ndaysji(date * idt) +{ + + return (idt->d + month1[idt->m] + idt->y * 365 + idt->y / 4); +} + +/* + * Compute the date according to the Gregorian calendar from the number of + * days since March 1st, year zero. The date computed will be Julian if it + * is older than 1582-10-05. This is the reverse of the function ndaysg(). + */ +date * +gdate(int ndays, date *dt) +{ + int const *montht; /* month-table */ + date idt; /* for internal date representation */ + int r; /* holds the rest of days */ + + /* + * Compute the year by starting with an approximation not smaller + * than the answer and search linearly for the greatest year not + * starting after ndays. + */ + idt.y = ndays / 365; + idt.m = 0; + idt.d = 0; + while ((r = ndaysgi(&idt)) > ndays) + idt.y--; + + /* + * Set ndays to the number of days left and compute by linear + * search the greatest month which does not start after ndays. We + * use the table month1 which provides for each month the number + * of days that elapsed in the year before that month. Here the + * year 1582 is special, as 10 days are left out in October to + * resynchronize the calendar with the earth's orbit. October 4th + * 1582 is followed by October 15th 1582. We use the "switch" + * table month1s for this year. + */ + ndays = ndays - r; + if (idt.y == 1582) + montht = month1s; + else + montht = month1; + + for (idt.m = 11; montht[idt.m] > ndays; idt.m--) + ; + + idt.d = ndays - montht[idt.m]; /* the rest is the day in month */ + + /* Advance ten days deleted from October if after switch in Oct 1582 */ + if (idt.y == jiswitch.y && idt.m == jiswitch.m && jiswitch.d < idt.d) + idt.d += 10; + + /* return external representation of found date */ + return (idt2date(dt, &idt)); +} + +/* + * Return the number of days since March 1st of the year zero. The date is + * assumed Gregorian if younger than 1582-10-04 and Julian otherwise. This + * is the reverse of gdate. + */ +int +ndaysg(date *dt) +{ + date idt; /* Internal date representation */ + + if (date2idt(&idt, dt) == NULL) + return (-1); + return (ndaysgi(&idt)); +} + +/* + * Same as above, but with the Gregorian date given in internal + * representation. + */ +static int +ndaysgi(date *idt) +{ + int nd; /* Number of days--return value */ + + /* Cache nswitch if not already done */ + if (nswitch == 0) + nswitch = ndaysji(&jiswitch); + + /* + * Assume Julian calendar and adapt to Gregorian if necessary, i. e. + * younger than nswitch. Gregori deleted + * the ten days from Oct 5th to Oct 14th 1582. + * Thereafter years which are multiples of 100 and not multiples + * of 400 were not leap years anymore. + * This makes the average length of a year + * 365d +.25d - .01d + .0025d = 365.2425d. But the tropical + * year measures 365.2422d. So in 10000/3 years we are + * again one day ahead of the earth. Sigh :-) + * (d is the average length of a day and tropical year is the + * time from one spring point to the next.) + */ + if ((nd = ndaysji(idt)) == -1) + return (-1); + if (idt->y >= 1600) + nd = (nd - 10 - (idt->y - 1600) / 100 + (idt->y - 1600) / 400); + else if (nd > nswitch) + nd -= 10; + return (nd); +} + +/* + * Compute the week number from the number of days since March 1st year 0. + * The weeks are numbered per year starting with 1. If the first + * week of a year includes at least four days of that year it is week 1, + * otherwise it gets the number of the last week of the previous year. + * The variable y will be filled with the year that contains the greater + * part of the week. + */ +int +week(int nd, int *y) +{ + date dt; + int fw; /* 1st day of week 1 of previous, this and + * next year */ + gdate(nd, &dt); + for (*y = dt.y + 1; nd < (fw = firstweek(*y)); (*y)--) + ; + return ((nd - fw) / 7 + 1); +} + +/* return the first day of week 1 of year y */ +static int +firstweek(int y) +{ + date idt; + int nd, wd; + + idt.y = y - 1; /* internal representation of y-1-1 */ + idt.m = 10; + idt.d = 0; + + nd = ndaysgi(&idt); + /* + * If more than 3 days of this week are in the preceding year, the + * next week is week 1 (and the next sunday/monday is the answer), + * otherwise this week is week 1 and the last sunday/monday is the + * answer. + */ + /* 3 may or may not be correct, better use what the locale says */ + if ((wd = weekday(nd) + 1 - weekstart) >= *nl_langinfo(_NL_TIME_WEEK_1STWEEK)) + return (nd - wd + 7); + else + return (nd - wd); +} + +/* return the weekday (Mo = 0 .. Su = 6) */ +int +weekday(int nd) +{ + date dmondaygi = {1997, 8, 16}; /* Internal repr. of 1997-11-17 */ + static int nmonday; /* ... which is a monday */ + + /* Cache the daynumber of one monday */ + if (nmonday == 0) + nmonday = ndaysgi(&dmondaygi); + + /* return (nd - nmonday) modulo 7 which is the weekday */ + nd = (nd - nmonday) % 7; + if (nd < 0) + return (nd + 7); + else + return (nd); +} + +/* + * Convert a date to internal date representation: The year starts on + * March 1st, month and day numbering start at zero. E. g. March 1st of + * year zero is written as y=0, m=0, d=0. + */ +static date * +date2idt(date *idt, date *dt) +{ + + idt->d = dt->d - 1; + if (dt->m > 2) { + idt->m = dt->m - 3; + idt->y = dt->y; + } else { + idt->m = dt->m + 9; + idt->y = dt->y - 1; + } + if (idt->m < 0 || idt->m > 11 || idt->y < 0) + return (NULL); + else + return idt; +} + +/* Reverse of date2idt */ +static date * +idt2date(date *dt, date *idt) +{ + + dt->d = idt->d + 1; + if (idt->m < 10) { + dt->m = idt->m + 3; + dt->y = idt->y; + } else { + dt->m = idt->m - 9; + dt->y = idt->y + 1; + } + if (dt->m < 1) + return (NULL); + else + return (dt); +} diff --git a/calendar.h b/calendar.h new file mode 100644 index 0000000..1a3cb9d --- /dev/null +++ b/calendar.h @@ -0,0 +1,44 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause-FreeBSD + * + * Copyright (c) 1997 Wolfgang Helbig + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * $FreeBSD: head/lib/libcalendar/calendar.h 326219 2017-11-26 02:00:33Z pfg $ + */ +struct date { + int y; /* year */ + int m; /* month */ + int d; /* day */ +}; + +struct date *easterg(int _year, struct date *_dt); +struct date *easterog(int _year, struct date *_dt); +struct date *easteroj(int _year, struct date *_dt); +struct date *gdate(int _nd, struct date *_dt); +struct date *jdate(int _nd, struct date *_dt); +int ndaysg(struct date *_dt); +int ndaysj(struct date *_dt); +int week(int _nd, int *_year); +int weekday(int _nd); diff --git a/easter.c b/easter.c new file mode 100644 index 0000000..bc1942e --- /dev/null +++ b/easter.c @@ -0,0 +1,103 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause-FreeBSD + * + * Copyright (c) 1997 Wolfgang Helbig + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: head/lib/libcalendar/easter.c 326219 2017-11-26 02:00:33Z pfg $"); + +#include "calendar.h" + +typedef struct date date; + +static int easterodn(int y); + +/* Compute Easter Sunday in Gregorian Calendar */ +date * +easterg(int y, date *dt) +{ + int c, i, j, k, l, n; + + n = y % 19; + c = y / 100; + k = (c - 17) / 25; + i = (c - c/4 -(c-k)/3 + 19 * n + 15) % 30; + i = i -(i/28) * (1 - (i/28) * (29/(i + 1)) * ((21 - n)/11)); + j = (y + y/4 + i + 2 - c + c/4) % 7; + l = i - j; + dt->m = 3 + (l + 40) / 44; + dt->d = l + 28 - 31*(dt->m / 4); + dt->y = y; + return (dt); +} + +/* Compute the Gregorian date of Easter Sunday in Julian Calendar */ +date * +easterog(int y, date *dt) +{ + + return (gdate(easterodn(y), dt)); +} + +/* Compute the Julian date of Easter Sunday in Julian Calendar */ +date * +easteroj(int y, date * dt) +{ + + return (jdate(easterodn(y), dt)); +} + +/* Compute the day number of Easter Sunday in Julian Calendar */ +static int +easterodn(int y) +{ + /* + * Table for the easter limits in one metonic (19-year) cycle. 21 + * to 31 is in March, 1 through 18 in April. Easter is the first + * sunday after the easter limit. + */ + int mc[] = {5, 25, 13, 2, 22, 10, 30, 18, 7, 27, 15, 4, + 24, 12, 1, 21, 9, 29, 17}; + + /* Offset from a weekday to next sunday */ + int ns[] = {6, 5, 4, 3, 2, 1, 7}; + date dt; + int dn; + + /* Assign the easter limit of y to dt */ + dt.d = mc[y % 19]; + + if (dt.d < 21) + dt.m = 4; + else + dt.m = 3; + + dt.y = y; + + /* Return the next sunday after the easter limit */ + dn = ndaysj(&dt); + return (dn + ns[weekday(dn)]); +} diff --git a/ncal.1 b/ncal.1 new file mode 100644 index 0000000..3871c49 --- /dev/null +++ b/ncal.1 @@ -0,0 +1,250 @@ +.\" Copyright (c) 1997 Wolfgang Helbig +.\" All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" $FreeBSD: head/usr.bin/ncal/ncal.1 267773 2014-06-23 08:23:05Z bapt $ +.\" +.Dd March 14, 2009 +.Dt CAL 1 +.Os +.Sh NAME +.Nm cal , +.Nm ncal +.Nd displays a calendar and the date of Easter +.Sh SYNOPSIS +.Nm +.Op Fl 31jy +.Op Fl A Ar number +.Op Fl B Ar number +.Op Fl d Ar yyyy-mm +.Oo +.Op Ar month +.Ar year +.Oc +.Nm +.Op Fl 31j +.Op Fl A Ar number +.Op Fl B Ar number +.Op Fl d Ar yyyy-mm +.Fl m Ar month +.Op Ar year +.Nm ncal +.Op Fl C +.Op Fl 31jy +.Op Fl A Ar number +.Op Fl B Ar number +.Op Fl d Ar yyyy-mm +.Oo +.Op Ar month +.Ar year +.Oc +.Nm ncal +.Op Fl C +.Op Fl 31j +.Op Fl A Ar number +.Op Fl B Ar number +.Op Fl d Ar yyyy-mm +.Fl m Ar month +.Op Ar year +.Nm ncal +.Op Fl 31bhjJpwySM +.Op Fl A Ar number +.Op Fl B Ar number +.Op Fl H Ar yyyy-mm-dd +.Op Fl d Ar yyyy-mm +.Op Fl s Ar country_code +.Oo +.Op Ar month +.Ar year +.Oc +.Nm ncal +.Op Fl 31bhJeoSM +.Op Fl A Ar number +.Op Fl B Ar number +.Op Fl d Ar yyyy-mm +.Op Ar year +.Sh DESCRIPTION +The +.Nm +utility displays a simple calendar in traditional format and +.Nm ncal +offers an alternative layout, more options and the date of Easter. +The new format is a little cramped but it makes a year fit +on a 25x80 terminal. +If arguments are not specified, +the current month is displayed. +.Pp +The options are as follows: +.Bl -tag -width indent +.It Fl h +Turns off highlighting of today. +.It Fl J +Display Julian Calendar, if combined with the +.Fl o +option, display date of Orthodox Easter according to the Julian Calendar. +.It Fl e +Display date of Easter (for western churches). +.It Fl j +Display Julian days (days one-based, numbered from January 1). +.It Fl m Ar month +Display the specified +.Ar month . +If +.Ar month +is specified as a decimal number, appending +.Ql f +or +.Ql p +displays the same month of the following or previous year respectively. +.It Fl o +Display date of Orthodox Easter (Greek and Russian +Orthodox Churches). +.It Fl p +Print the country codes and switching days from Julian to Gregorian +Calendar as they are assumed by +.Nm ncal . +The country code as determined from the local environment is marked +with an asterisk. +.It Fl s Ar country_code +Assume the switch from Julian to Gregorian Calendar at the date +associated with the +.Ar country_code . +If not specified, +.Nm ncal +tries to guess the switch date from the local environment or +falls back to September 2, 1752. +This was when Great +Britain and her colonies switched to the Gregorian Calendar. +.It Fl w +Print the number of the week below each week column. +.It Fl y +Display a calendar for the specified year. This option is implied when +a year but no month are specified on the command line. +.It Fl 3 +Display the previous, current and next month surrounding today. +.It Fl 1 +Display only the current month. This is the default. +.It Fl A Ar number +Months to add after. The specified number of months is added to the +end of the display. This is in addition to any date range selected by the +.Fl y , +.Fl 3 , +or +.Fl 1 +options. For example, +.Dq Li cal -y -B2 -A2 +shows everything from November of the previous year to +February of the following year. Negative numbers are allowed, in which +case the specified number of months is subtracted. For example, +.Dq Li cal -y -B-6 +shows July to December. And +.Dq Li cal -A11 +simply shows the next 12 months. +.It Fl B Ar number +Months to add before. The specified number of months is added to the +beginning of the display. See +.Fl A +for examples. +.It Fl C +Completely switch to +.Nm cal +mode. For +.Nm cal +like output only, use +.Fl b +instead. +.It Fl N +Switch to +.Nm ncal +mode. +.It Fl d Ar yyyy-mm +Use +.Ar yyyy-mm +as the current date (for debugging of date selection). +.It Fl H Ar yyyy-mm-dd +Use +.Ar yyyy-mm-dd +as the current date (for debugging of highlighting). +.It Fl M +Weeks start on Monday. +.It Fl S +Weeks start on Sunday. +.It Fl b +Use oldstyle format for ncal output. +.El +.Pp +A single parameter specifies the year (1\(en9999) to be displayed; +note the year must be fully specified: +.Dq Li cal 89 +will +.Em not +display a calendar for 1989. Two parameters denote the month and +year; the month is either a number between 1 and 12, or a full or +abbreviated name as specified by the current locale. Month and +year default to those of the current system clock and time zone (so +.Dq Li cal -m 8 +will display a calendar for the month of August in the current +year). +.Pp +Not all options can be used together. For example, the options +.Fl y , 3 , +and +.Fl 1 +are mutually exclusive. If inconsistent options are given, the later +ones take precedence over the earlier ones. +.Pp +A year starts on January 1. +.Pp +Highlighting of dates is disabled if stdout is not a tty. +.Sh SEE ALSO +.Xr calendar 3 , +.Xr strftime 3 +.Sh HISTORY +A +.Nm +command appeared in +.At v5 . +The +.Nm ncal +command appeared in +.Fx 2.2.6 . +The output of the +.Nm cal +command is supposed to be bit for bit compatible to the original Unix +.Nm cal +command, because its output is processed by other programs like CGI scripts, +that should not be broken. Therefore it will always output 8 lines, even if +only 7 contain data. This extra blank line also appears with the original +.Nm cal +command, at least on Solaris 8 +.Sh AUTHORS +The +.Nm ncal +command and manual were written by +.An Wolfgang Helbig Aq Mt helbig@FreeBSD.org . +.Sh BUGS +The assignment of Julian\(enGregorian switching dates to country +codes is historically naive for many countries. +.Pp +Not all options are compatible and using them in different orders +will give varying results. diff --git a/ncal.c b/ncal.c new file mode 100644 index 0000000..8ecbb33 --- /dev/null +++ b/ncal.c @@ -0,0 +1,1292 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause-FreeBSD + * + * Copyright (c) 1997 Wolfgang Helbig + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: head/usr.bin/ncal/ncal.c 326276 2017-11-27 15:37:16Z pfg $"); + +#include "calendar.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#undef lines /* term.h defines this */ + +/* Width of one month with backward compatibility and in regular mode*/ +#define MONTH_WIDTH_B_J 27 +#define MONTH_WIDTH_B_NW 20 +#define MONTH_WIDTH_B_WW 25 + +#define MONTH_WIDTH_R_J 24 +#define MONTH_WIDTH_R 18 + +#define MAX_WIDTH 79 + +typedef struct date date; + +struct monthlines { + wchar_t name[MAX_WIDTH + 1]; + char lines[7][MAX_WIDTH + 1]; + char weeks[MAX_WIDTH + 1]; + unsigned int extralen[7]; +}; + +struct weekdays { + wchar_t names[7][4]; +}; + +/* The switches from Julian to Gregorian in some countries */ +static struct djswitch { + const char *cc; /* Country code according to ISO 3166 */ + const char *nm; /* Name of country */ + date dt; /* Last day of Julian calendar */ +} switches[] = { + {"AL", "Albania", {1912, 11, 30}}, + {"AT", "Austria", {1583, 10, 5}}, + {"AU", "Australia", {1752, 9, 2}}, + {"BE", "Belgium", {1582, 12, 14}}, + {"BG", "Bulgaria", {1916, 3, 18}}, + {"CA", "Canada", {1752, 9, 2}}, + {"CH", "Switzerland", {1655, 2, 28}}, + {"CN", "China", {1911, 12, 18}}, + {"CZ", "Czech Republic",{1584, 1, 6}}, + {"DE", "Germany", {1700, 2, 18}}, + {"DK", "Denmark", {1700, 2, 18}}, + {"ES", "Spain", {1582, 10, 4}}, + {"FI", "Finland", {1753, 2, 17}}, + {"FR", "France", {1582, 12, 9}}, + {"GB", "United Kingdom",{1752, 9, 2}}, + {"GR", "Greece", {1924, 3, 9}}, + {"HU", "Hungary", {1587, 10, 21}}, + {"IS", "Iceland", {1700, 11, 16}}, + {"IT", "Italy", {1582, 10, 4}}, + {"JP", "Japan", {1918, 12, 18}}, + {"LI", "Lithuania", {1918, 2, 1}}, + {"LN", "Latin", {9999, 05, 31}}, + {"LU", "Luxembourg", {1582, 12, 14}}, + {"LV", "Latvia", {1918, 2, 1}}, + {"NL", "Netherlands", {1582, 12, 14}}, + {"NO", "Norway", {1700, 2, 18}}, + {"PL", "Poland", {1582, 10, 4}}, + {"PT", "Portugal", {1582, 10, 4}}, + {"RO", "Romania", {1919, 3, 31}}, + {"RU", "Russia", {1918, 1, 31}}, + {"SI", "Slovenia", {1919, 3, 4}}, + {"SE", "Sweden", {1753, 2, 17}}, + {"TR", "Turkey", {1926, 12, 18}}, + {"US", "United States", {1752, 9, 2}}, + {"YU", "Yugoslavia", {1919, 3, 4}} +}; + +static struct djswitch *dftswitch = + switches + sizeof(switches) / sizeof(struct djswitch) - 2; + /* default switch (should be "US") */ + +/* Table used to print day of month and week numbers */ +static char daystr[] = " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15" + " 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31" + " 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47" + " 48 49 50 51 52 53"; + +/* Table used to print day of year and week numbers */ +static char jdaystr[] = " 1 2 3 4 5 6 7 8 9" + " 10 11 12 13 14 15 16 17 18 19" + " 20 21 22 23 24 25 26 27 28 29" + " 30 31 32 33 34 35 36 37 38 39" + " 40 41 42 43 44 45 46 47 48 49" + " 50 51 52 53 54 55 56 57 58 59" + " 60 61 62 63 64 65 66 67 68 69" + " 70 71 72 73 74 75 76 77 78 79" + " 80 81 82 83 84 85 86 87 88 89" + " 90 91 92 93 94 95 96 97 98 99" + " 100 101 102 103 104 105 106 107 108 109" + " 110 111 112 113 114 115 116 117 118 119" + " 120 121 122 123 124 125 126 127 128 129" + " 130 131 132 133 134 135 136 137 138 139" + " 140 141 142 143 144 145 146 147 148 149" + " 150 151 152 153 154 155 156 157 158 159" + " 160 161 162 163 164 165 166 167 168 169" + " 170 171 172 173 174 175 176 177 178 179" + " 180 181 182 183 184 185 186 187 188 189" + " 190 191 192 193 194 195 196 197 198 199" + " 200 201 202 203 204 205 206 207 208 209" + " 210 211 212 213 214 215 216 217 218 219" + " 220 221 222 223 224 225 226 227 228 229" + " 230 231 232 233 234 235 236 237 238 239" + " 240 241 242 243 244 245 246 247 248 249" + " 250 251 252 253 254 255 256 257 258 259" + " 260 261 262 263 264 265 266 267 268 269" + " 270 271 272 273 274 275 276 277 278 279" + " 280 281 282 283 284 285 286 287 288 289" + " 290 291 292 293 294 295 296 297 298 299" + " 300 301 302 303 304 305 306 307 308 309" + " 310 311 312 313 314 315 316 317 318 319" + " 320 321 322 323 324 325 326 327 328 329" + " 330 331 332 333 334 335 336 337 338 339" + " 340 341 342 343 344 345 346 347 348 349" + " 350 351 352 353 354 355 356 357 358 359" + " 360 361 362 363 364 365 366"; + +static int flag_nohighlight; /* user doesn't want a highlighted today */ +static int flag_weeks; /* user wants number of week */ +static int nswitch; /* user defined switch date */ +static int nswitchb; /* switch date for backward compatibility */ +static int highlightdate; +int weekstart = -1; /* day the week starts on (Sun [0] - Sat [6]) */ + +static char *center(char *s, char *t, int w); +static wchar_t *wcenter(wchar_t *s, wchar_t *t, int w); +static int firstday(int y, int m); +static void highlight(char *dst, char *src, int len, int *extraletters); +static void mkmonthr(int year, int month, int jd_flag, + struct monthlines * monthl); +static void mkmonthb(int year, int month, int jd_flag, + struct monthlines * monthl); +static void mkweekdays(struct weekdays * wds); +static void monthranger(int year, int m, int jd_flag, + int before, int after); +static void monthrangeb(int year, int m, int jd_flag, + int before, int after); +static int parsemonth(const char *s, int *m, int *y); +static void printcc(void); +static void printeaster(int year, int julian, int orthodox); +static date *sdater(int ndays, struct date * d); +static date *sdateb(int ndays, struct date * d); +static int sndaysr(struct date * d); +static int sndaysb(struct date * d); +static void usage(void); + +int +main(int argc, char *argv[]) +{ + struct djswitch *p, *q; /* to search user defined switch date */ + date never = {10000, 1, 1}; /* outside valid range of dates */ + date ukswitch = {1752, 9, 2};/* switch date for Great Britain */ + date dt; + int ch; /* holds the option character */ + int m = 0; /* month */ + int y = 0; /* year */ + int flag_backward = 0; /* user called cal--backward compat. */ + int ncal_backward = 0; /* make output of ncal backward compat. */ + int no_backward = 0; /* to make sure conflicting options really conflict */ + int flag_wholeyear = 0; /* user wants the whole year */ + int flag_julian_cal = 0; /* user wants Julian Calendar */ + int flag_julian_day = 0; /* user wants the Julian day numbers */ + int flag_orthodox = 0; /* user wants Orthodox easter */ + int flag_easter = 0; /* user wants easter date */ + int flag_3months = 0; /* user wants 3 month display (-3) */ + int flag_1month = 0; /* user wants 1 month display (-1) */ + int flag_after = 0; /* user wants to see months after */ + int flag_before = 0; /* user wants to see months before */ + int flag_givenmonth = 0; /* user has specified month */ + int flag_givenyear = 0; /* user has specified year */ + char *cp; /* character pointer */ + char *flag_today = NULL; /* debug: use date as being today */ + char *flag_month = NULL; /* requested month as string */ + char *flag_highlightdate = NULL; /* debug: date to highlight */ + int before, after; + const char *locale; /* locale to get country code */ + + flag_nohighlight = 0; + flag_weeks = 0; + + /* + * Use locale to determine the country code, + * and use the country code to determine the default + * switchdate and date format from the switches table. + */ + if (setlocale(LC_ALL, "") == NULL) + warn("setlocale"); + locale = setlocale(LC_TIME, NULL); + if (locale == NULL || + strcmp(locale, "C") == 0 || + strcmp(locale, "POSIX") == 0 || + strcmp(locale, "ASCII") == 0 || + strcmp(locale, "US-ASCII") == 0) + locale = "_US"; + q = switches + sizeof(switches) / sizeof(struct djswitch); + for (p = switches; p != q; p++) + if ((cp = strstr(locale, p->cc)) != NULL && *(cp - 1) == '_') + break; + if (p == q) { + nswitch = ndaysj(&dftswitch->dt); + } else { + nswitch = ndaysj(&p->dt); + dftswitch = p; + } + + + /* + * Get the filename portion of argv[0] and set flag_backward if + * this program is called "cal". + */ + if (strncmp(basename(argv[0]), "cal", strlen("cal")) == 0) + flag_backward = 1; + + /* Set the switch date to United Kingdom if backwards compatible */ + if (flag_backward) + nswitchb = ndaysj(&ukswitch); + + before = after = -1; + + while ((ch = getopt(argc, argv, "31A:B:Cd:eH:hjJm:ops:wySMb")) != -1) + switch (ch) { + case 'b': + if (flag_backward) + usage(); + else + no_backward = 1; + ncal_backward = 1; + break; + case '3': + flag_1month = 0; + flag_3months = 1; + flag_wholeyear = 0; + break; + case '1': + flag_1month = 1; + flag_3months = 0; + flag_wholeyear = 0; + break; + case 'A': + flag_after = strtol(optarg, NULL, 10); + break; + case 'B': + flag_before = strtol(optarg, NULL, 10); + break; + case 'J': + if (flag_backward) + usage(); + else + no_backward = 1; + nswitch = ndaysj(&never); + flag_julian_cal = 1; + break; + case 'C': + if (no_backward == 1) + usage(); + flag_backward = 1; + break; + case 'd': + flag_today = optarg; + break; + case 'H': + if (flag_backward) + usage(); + else + no_backward = 1; + flag_highlightdate = optarg; + break; + case 'h': + if (flag_backward) + usage(); + else + no_backward = 1; + flag_nohighlight = 1; + break; + case 'e': + if (flag_backward) + usage(); + else + no_backward = 1; + flag_easter = 1; + break; + case 'j': + flag_julian_day = 1; + break; + case 'm': + flag_month = optarg; + flag_givenmonth = 1; + break; + case 'o': + if (flag_backward) + usage(); + else + no_backward = 1; + flag_orthodox = 1; + flag_easter = 1; + break; + case 'p': + if (flag_backward) + usage(); + printcc(); + return (0); + break; + case 's': + if (flag_backward) + usage(); + else + no_backward = 1; + q = switches + + sizeof(switches) / sizeof(struct djswitch); + for (p = switches; + p != q && strcmp(p->cc, optarg) != 0; p++) + ; + if (p == q) + errx(EX_USAGE, + "%s: invalid country code", optarg); + nswitch = ndaysj(&(p->dt)); + break; + case 'w': + if (flag_backward) + usage(); + else + no_backward = 1; + flag_weeks = 1; + break; + case 'y': + flag_1month = 0; + flag_wholeyear = 1; + flag_3months = 0; + break; + case 'S': + if (flag_backward) + usage(); + else + no_backward = 1; + weekstart = 0; + break; + case 'M': + if (flag_backward) + usage(); + else + no_backward = 1; + weekstart = 1; + break; + default: + usage(); + } + + argc -= optind; + argv += optind; + + switch (argc) { + case 2: + if (flag_easter) + usage(); + flag_month = *argv++; + flag_givenmonth = 1; + m = strtol(flag_month, NULL, 10); + /* FALLTHROUGH */ + case 1: + y = strtol(*argv, &cp, 10); + if (*cp != '\0') + errx(EX_USAGE, "not a valid year %s", *argv); + if (y < 1 || y > 9999) + errx(EX_USAGE, "year `%s' not in range 1..9999", *argv); + argv++; + flag_givenyear = 1; + break; + case 0: + if (flag_today != NULL) { + y = strtol(flag_today, NULL, 10); + m = strtol(flag_today + 5, NULL, 10); + } else { + time_t t; + struct tm *tm; + + t = time(NULL); + tm = localtime(&t); + y = tm->tm_year + 1900; + m = tm->tm_mon + 1; + } + break; + default: + usage(); + } + + /* Technically not correct, but removes the need to add 1 later on */ + if (flag_backward) + weekstart = (weekstart == -1) ? 1 : weekstart + 1; + /* Determine on what day the week starts. */ +#ifdef __GLIBC__ + else if (weekstart == -1) + { + int first_week_i; + date first_week_d; + date sunday = { .y = 1997, .m = 11, .d = 30 }; + + union { char *str; unsigned int word; } u; + u.str = nl_langinfo(_NL_TIME_WEEK_1STDAY); + + first_week_i = u.word; + first_week_d.d = first_week_i % 100; + first_week_i /= 100; + first_week_d.m = first_week_i % 100; + first_week_i /= 100; + first_week_d.y = first_week_i; + weekstart = *nl_langinfo(_NL_TIME_FIRST_WEEKDAY) + (ndaysj(&first_week_d) - ndaysj(&sunday)) % 7 - 1; + } +#endif + + if (ncal_backward) + { + flag_backward = 1; + weekstart++; + } + + if (flag_month != NULL) { + if (parsemonth(flag_month, &m, &y)) { + errx(EX_USAGE, + "%s is neither a month number (1..12) nor a name", + flag_month); + } + } + + /* The base month and/or year can be specified by any of the + following: + + month year + year + -m month + + + In case of multiple specification of the same item (month + or year), the later one should override the earlier one. + (However, arguments are always evaluated after options). In + case neither month nor year is specified, use the current + month in the current year. + + The range of months to display can be specified by one of + the following three options: + + -y (display a calendar for the specified year - disregard month) + -3 (display 3 months - not possible if only year specified) + -1 (display 1 month - not possible if only year specified) + + The default is -1, unless a year and no month is specified, + in which case -y is implied. + + The options -1, -3, and -y methods are mutually exclusive; + if multiple ones are specified, the last one is used. + + In addition, the range of months can be modified with the + following options: + + -B n + -A m + + This modifies the range of months specified by the other + options, by adding n additional months at the beginning and + m additional months at the end. Negative numbers *are* + allowed, as long as the total number of months displayed is + at least 1. + */ + + /* if givenyear, but not givenmonth, then imply -y */ + + if (flag_givenyear && !flag_givenmonth) { + flag_wholeyear = 1; + if (flag_3months) { + errx(EX_USAGE, + "-3 together with a given year but no given month is " + "not supported."); + } + if (flag_1month) { + errx(EX_USAGE, + "-1 together with a given year but no given month is " + "not supported."); + } + } + + /* otherwise, default to -1 */ + if (!flag_wholeyear && !flag_3months) { + flag_1month = 1; + } + + /* Select the period to display, in order of increasing priority .*/ + if (flag_wholeyear) { + m = 1; + before = 0; + after = 11; + } else if (flag_3months) { + before = 1; + after = 1; + } else if (flag_1month) { + before = 0; + after = 0; + } + /* now add additional "before" and "after" values */ + if (flag_before) { + before += flag_before; + } + if (flag_after) { + after += flag_after; + } + /* don't allow a period of 0 or less months */ + if (before + after < 0) { + before = after = 0; + } + + /* Highlight a specified day or today .*/ + if (flag_highlightdate != NULL) { + dt.y = strtol(flag_highlightdate, NULL, 10); + dt.m = strtol(flag_highlightdate + 5, NULL, 10); + dt.d = strtol(flag_highlightdate + 8, NULL, 10); + } else { + time_t t; + struct tm *tm1; + + t = time(NULL); + tm1 = localtime(&t); + dt.y = tm1->tm_year + 1900; + dt.m = tm1->tm_mon + 1; + dt.d = tm1->tm_mday; + } + highlightdate = sndaysb(&dt); + + /* And now we finally start to calculate and output calendars. */ + if (flag_easter) + printeaster(y, flag_julian_cal, flag_orthodox); + else + if (flag_backward) + monthrangeb(y, m, flag_julian_day, before, after); + else + monthranger(y, m, flag_julian_day, before, after); + return (0); +} + +static void +usage(void) +{ + + fputs( +"Usage: cal [general options] [-jy] [[month] year]\n" +" cal [general options] [-j] [-m month] [year]\n" +" ncal -C [general options] [-jy] [[month] year]\n" +" ncal -C [general options] [-j] [-m month] [year]\n" +" ncal [general options] [-bhJjpwySM] [-H yyyy-mm-dd] [-s country_code] [[month] year]\n" +" ncal [general options] [-bhJeoSM] [year]\n" +"General options: [-31] [-A months] [-B months] [-d yyyy-mm]\n", + stderr); + exit(EX_USAGE); +} + +/* Print the assumed switches for all countries. */ +static void +printcc(void) +{ + struct djswitch *p; + int n; /* number of lines to print */ + int m; /* offset from left to right table entry on the same line */ + +#define FSTR L"%c%s %-15s%4d-%02d-%02d" +#define DFLT(p) ((p) == dftswitch ? '*' : ' ') +#define FSTRARG(p) DFLT(p), (p)->cc, (p)->nm, (p)->dt.y, (p)->dt.m, (p)->dt.d + + n = sizeof(switches) / sizeof(struct djswitch); + m = (n + 1) / 2; + n /= 2; + for (p = switches; p != switches + n; p++) + wprintf(FSTR" "FSTR"\n", FSTRARG(p), FSTRARG(p+m)); + if (m != n) + wprintf(FSTR"\n", FSTRARG(p)); +} + +/* Print the date of easter sunday. */ +static void +printeaster(int y, int julian, int orthodox) +{ + date dt; + struct tm tm; + char buf[MAX_WIDTH]; + /* force orthodox easter for years before 1583 */ + if (y < 1583) + orthodox = 1; + + if (orthodox) + if (julian) + easteroj(y, &dt); + else + easterog(y, &dt); + else + easterg(y, &dt); + + memset(&tm, 0, sizeof(tm)); + tm.tm_year = dt.y - 1900; + tm.tm_mon = dt.m - 1; + tm.tm_mday = dt.d; + strftime(buf, sizeof(buf), "%x", &tm); + wprintf(L"%s\n", buf); +} + +#define MW(mw, me) ((mw) + me) +#define DECREASEMONTH(m, y) \ + if (--m == 0) { \ + m = 12; \ + y--; \ + } +#define INCREASEMONTH(m, y) \ + if (++(m) == 13) { \ + (m) = 1; \ + (y)++; \ + } +#define M2Y(m) ((m) / 12) +#define M2M(m) (1 + (m) % 12) + +/* Print all months for the period in the range [ before .. y-m .. after ]. */ +static void +monthrangeb(int y, int m, int jd_flag, int before, int after) +{ + struct monthlines year[12]; + struct weekdays wds; + char s[MAX_WIDTH], t[MAX_WIDTH]; + wchar_t ws[MAX_WIDTH], ws1[MAX_WIDTH]; + const char *wdss; + int i, j; + int mpl; + int mw; + int m1, m2; + int printyearheader; + int prevyear = -1; + + mpl = jd_flag ? 2 : 3; + mw = jd_flag ? MONTH_WIDTH_B_J : (flag_weeks ? MONTH_WIDTH_B_WW : MONTH_WIDTH_B_NW ); + wdss = (mpl == 2) ? " " : ""; + + while (before > 0) { + DECREASEMONTH(m, y); + before--; + after++; + } + while (before < 0) { + INCREASEMONTH(m, y); + before++; + after--; + } + m1 = y * 12 + m - 1; + m2 = m1 + after; + + mkweekdays(&wds); + + /* + * The year header is printed when there are more than 'mpl' months + * and if the first month is a multitude of 'mpl'. + * If not, it will print the year behind every month. + */ + printyearheader = (after >= mpl - 1) && (M2M(m1) - 1) % mpl == 0; + + m = m1; + while (m <= m2) { + int count = 0; + for (i = 0; i != mpl && m + i <= m2; i++) { + mkmonthb(M2Y(m + i), M2M(m + i) - 1, jd_flag, year + i); + count++; + } + + /* Empty line between two rows of months */ + if (m != m1) + wprintf(L"\n"); + + /* Year at the top. */ + if (printyearheader && M2Y(m) != prevyear) { + sprintf(s, "%d", M2Y(m)); + wprintf(L"%s\n", center(t, s, mpl * mw)); + prevyear = M2Y(m); + } + + /* Month names. */ + for (i = 0; i < count; i++) + if (printyearheader) + wprintf(L"%-*ls ", + mw, wcenter(ws, year[i].name, mw)); + else { + swprintf(ws, sizeof(ws)/sizeof(ws[0]), + L"%-ls %d", year[i].name, M2Y(m + i)); + wprintf(L"%-*ls ", mw, wcenter(ws1, ws, mw)); + } + wprintf(L"\n"); + + /* Day of the week names. */ + for (i = 0; i < count; i++) { + if (flag_weeks) + wprintf(L" w| %s%ls%s%ls%s%ls%s%ls%s%ls%s%ls%s%ls ", + wdss, wds.names[6], wdss, wds.names[0], + wdss, wds.names[1], wdss, wds.names[2], + wdss, wds.names[3], wdss, wds.names[4], + wdss, wds.names[5]); + else + wprintf(L"%s%ls%s%ls%s%ls%s%ls%s%ls%s%ls%s%ls ", + wdss, wds.names[6], wdss, wds.names[0], + wdss, wds.names[1], wdss, wds.names[2], + wdss, wds.names[3], wdss, wds.names[4], + wdss, wds.names[5]); + } + wprintf(L"\n"); + + /* And the days of the month. */ + for (i = 0; i != 6; i++) { + for (j = 0; j < count; j++) + wprintf(L"%-*s ", + MW(mw, year[j].extralen[i]), + year[j].lines[i]+1); + wprintf(L"\n"); + } + + m += mpl; + } +} + +static void +monthranger(int y, int m, int jd_flag, int before, int after) +{ + struct monthlines year[12]; + struct weekdays wds; + char s[MAX_WIDTH], t[MAX_WIDTH]; + int i, j; + int mpl; + int mw; + int m1, m2; + int prevyear = -1; + int printyearheader; + + mpl = jd_flag ? 3 : 4; + mw = jd_flag ? MONTH_WIDTH_R_J : MONTH_WIDTH_R; + + while (before > 0) { + DECREASEMONTH(m, y); + before--; + after++; + } + while (before < 0) { + INCREASEMONTH(m, y); + before++; + after--; + } + m1 = y * 12 + m - 1; + m2 = m1 + after; + + mkweekdays(&wds); + + /* + * The year header is printed when there are more than 'mpl' months + * and if the first month is a multitude of 'mpl'. + * If not, it will print the year behind every month. + */ + printyearheader = (after >= mpl - 1) && (M2M(m1) - 1) % mpl == 0; + + m = m1; + while (m <= m2) { + int count = 0; + for (i = 0; i != mpl && m + i <= m2; i++) { + mkmonthr(M2Y(m + i), M2M(m + i) - 1, jd_flag, year + i); + count++; + } + + /* Empty line between two rows of months. */ + if (m != m1) + wprintf(L"\n"); + + /* Year at the top. */ + if (printyearheader && M2Y(m) != prevyear) { + sprintf(s, "%d", M2Y(m)); + wprintf(L"%s\n", center(t, s, mpl * mw)); + prevyear = M2Y(m); + } + + /* Month names. */ + wprintf(L" "); + for (i = 0; i < count; i++) + if (printyearheader) + wprintf(L"%-*ls", mw, year[i].name); + else + wprintf(L"%-ls %-*d", year[i].name, + mw - wcslen(year[i].name) - 1, M2Y(m + i)); + wprintf(L"\n"); + + /* And the days of the month. */ + for (i = 0; i != 7; i++) { + /* Week day */ + wprintf(L"%.2ls", wds.names[i]); + + /* Full months */ + for (j = 0; j < count; j++) + wprintf(L"%-*s", + MW(mw, year[j].extralen[i]), + year[j].lines[i]); + wprintf(L"\n"); + } + + /* Week numbers. */ + if (flag_weeks) { + wprintf(L" "); + for (i = 0; i < count; i++) + wprintf(L"%-*s", mw, year[i].weeks); + wprintf(L"\n"); + } + + m += mpl; + } + return; +} + +static void +mkmonthr(int y, int m, int jd_flag, struct monthlines *mlines) +{ + + struct tm tm; /* for strftime printing local names of + * months */ + date dt; /* handy date */ + int dw; /* width of numbers */ + int first; /* first day of month */ + int firstm; /* first day of first week of month */ + int i, j, k, l; /* just indices */ + int last; /* the first day of next month */ + int jan1 = 0; /* the first day of this year */ + char *ds; /* pointer to day strings (daystr or + * jdaystr) */ + + /* Set name of month. */ + memset(&tm, 0, sizeof(tm)); + tm.tm_mon = m; + wcsftime(mlines->name, sizeof(mlines->name) / sizeof(mlines->name[0]), + L"%B", &tm); + mlines->name[0] = towupper(mlines->name[0]); + + /* + * Set first and last to the day number of the first day of this + * month and the first day of next month respectively. Set jan1 to + * the day number of the first day of this year. + */ + first = firstday(y, m + 1); + if (m == 11) + last = firstday(y + 1, 1); + else + last = firstday(y, m + 2); + + if (jd_flag) + jan1 = firstday(y, 1); + + /* + * Set firstm to the day number of the day starting the first week of + * this month. (This might be in the last month) + */ + if (weekstart == 0) + firstm = first - (weekday(first) + 1) % 7; + else + firstm = first - weekday(first); + + /* Set ds (daystring) and dw (daywidth) according to the jd_flag. */ + if (jd_flag) { + ds = jdaystr; + dw = 4; + } else { + ds = daystr; + dw = 3; + } + + /* + * Fill the lines with day of month or day of year (julian day) + * line index: i, each line is one weekday. column index: j, each + * column is one day number. print column index: k. + */ + for (i = 0; i != 7; i++) { + l = 0; + for (j = firstm + i, k = 0; j < last; j += 7, k += dw) { + if (j >= first) { + if (jd_flag) + dt.d = j - jan1 + 1; + else + sdater(j, &dt); + if (j == highlightdate && !flag_nohighlight + && isatty(STDOUT_FILENO)) + highlight(mlines->lines[i] + k, + ds + dt.d * dw, dw, &l); + else + memcpy(mlines->lines[i] + k + l, + ds + dt.d * dw, dw); + } else + memcpy(mlines->lines[i] + k + l, " ", dw); + } + mlines->lines[i][k + l] = '\0'; + mlines->extralen[i] = l; + } + + /* fill the weeknumbers. */ + if (flag_weeks) { + for (j = firstm, k = 0; j < last; k += dw, j += 7) + if (j <= nswitch) + memset(mlines->weeks + k, ' ', dw); + else + memcpy(mlines->weeks + k, + ds + week(j, &i)*dw, dw); + mlines->weeks[k] = '\0'; + } +} + +static void +mkmonthb(int y, int m, int jd_flag, struct monthlines *mlines) +{ + + struct tm tm; /* for strftime printing local names of + * months */ + date dt; /* handy date */ + int dw; /* width of numbers */ + int first; /* first day of month */ + int firsts; /* first day of first week of month */ + int i, j, k, l; /* just indices */ + int jan1 = 0; /* the first day of this year */ + int last; /* the first day of next month */ + char *ds; /* pointer to day strings (daystr or + * jdaystr) */ + + /* Set ds (daystring) and dw (daywidth) according to the jd_flag */ + if (jd_flag) { + ds = jdaystr; + dw = 4; + } else { + ds = daystr; + dw = 3; + } + + /* Set name of month centered. */ + memset(&tm, 0, sizeof(tm)); + tm.tm_mon = m; + wcsftime(mlines->name, sizeof(mlines->name) / sizeof(mlines->name[0]), + L"%B", &tm); + mlines->name[0] = towupper(mlines->name[0]); + + /* + * Set first and last to the day number of the first day of this + * month and the first day of next month respectively. Set jan1 to + * the day number of Jan 1st of this year. + */ + dt.y = y; + dt.m = m + 1; + dt.d = 1; + first = sndaysb(&dt); + if (m == 11) { + dt.y = y + 1; + dt.m = 1; + dt.d = 1; + } else { + dt.y = y; + dt.m = m + 2; + dt.d = 1; + } + last = sndaysb(&dt); + + if (jd_flag) { + dt.y = y; + dt.m = 1; + dt.d = 1; + jan1 = sndaysb(&dt); + } + + /* + * Set firsts to the day number of the day starting the first week of + * this month. (This might be in the last month) + */ + if (weekstart == 1) + firsts = first - (weekday(first)+1) % 7; + else + firsts = first - weekday(first); + /* undo the shift from ncal_backward to correct week number assignment */ + weekstart--; + + /* + * Fill the lines with day of month or day of year (Julian day) + * line index: i, each line is one week. column index: j, each + * column is one day number. print column index: k. + */ + for (i = 0; i != 6; i++) { + /* additional shift to make space for weeks */ + l = flag_weeks ? 4 : 0; + for (j = firsts + 7 * i, k = 0; j < last && k != dw * 7; + j++, k += dw) { + if (j >= first) { + if (jd_flag) + dt.d = j - jan1 + 1; + else + sdateb(j, &dt); + if (j == highlightdate && !flag_nohighlight) + highlight(mlines->lines[i] + k + l, + ds + dt.d * dw, dw, &l); + else + memcpy(mlines->lines[i] + k + l, + ds + dt.d * dw, dw); + } else + memcpy(mlines->lines[i] + k + l, " ", dw); + } + if (k == 0) + mlines->lines[i][1] = '\0'; + else { + mlines->lines[i][k + l] = '\0'; + if (flag_weeks) { + int year; + memcpy(mlines->lines[i], ds + week(firsts + 7 * i, &year)*dw, dw); + memcpy(mlines->lines[i] + 3, "|", 1); + } + } + /* store only highlighting extralength */ + mlines->extralen[i] = l - (flag_weeks ? 4 : 0); + } + + /* redo the shift from ncal_backward to correct week number assignment */ + weekstart++; +} + +/* Put the local names of weekdays into the wds. */ +static void +mkweekdays(struct weekdays *wds) +{ + int i, len, width = 0; + struct tm tm; + wchar_t buf[20]; + + memset(&tm, 0, sizeof(tm)); + + for (i = 0; i != 7; i++) { + tm.tm_wday = (i+weekstart) % 7; + wcsftime(buf, sizeof(buf)/sizeof(buf[0]), L"%a", &tm); + for (len = 2; len > 0; --len) { + if ((width = wcswidth(buf, len)) <= 2) + break; + } + wmemset(wds->names[i], L'\0', 4); + if (width == 1) + wds->names[i][0] = L' '; + wcsncat(wds->names[i], buf, len); + wcsncat(wds->names[i], L" ", 1); + } +} + +/* + * Compute the day number of the first existing date after the first day in + * month. (the first day in month and even the month might not exist!) + */ +static int +firstday(int y, int m) +{ + date dt; + int nd; + + dt.y = y; + dt.m = m; + dt.d = 1; + nd = sndaysr(&dt); + for (;;) { + sdater(nd, &dt); + if ((dt.m >= m && dt.y == y) || dt.y > y) + return (nd); + else + nd++; + } + /* NEVER REACHED */ +} + +/* + * Compute the number of days from date, obey the local switch from + * Julian to Gregorian if specified by the user. + */ +static int +sndaysr(struct date *d) +{ + + if (nswitch != 0) + if (nswitch < ndaysj(d)) + return (ndaysg(d)); + else + return (ndaysj(d)); + else + return ndaysg(d); +} + +/* + * Compute the number of days from date, obey the switch from + * Julian to Gregorian as used by UK and her colonies. + */ +static int +sndaysb(struct date *d) +{ + + if (nswitchb < ndaysj(d)) + return (ndaysg(d)); + else + return (ndaysj(d)); +} + +/* Inverse of sndays. */ +static struct date * +sdater(int nd, struct date *d) +{ + + if (nswitch < nd) + return (gdate(nd, d)); + else + return (jdate(nd, d)); +} + +/* Inverse of sndaysb. */ +static struct date * +sdateb(int nd, struct date *d) +{ + + if (nswitchb < nd) + return (gdate(nd, d)); + else + return (jdate(nd, d)); +} + +/* Center string t in string s of length w by putting enough leading blanks. */ +static char * +center(char *s, char *t, int w) +{ + char blanks[MAX_WIDTH]; + + memset(blanks, ' ', sizeof(blanks)); + sprintf(s, "%.*s%s", (int)(w - strlen(t)) / 2, blanks, t); + return (s); +} + +/* Center string t in string s of length w by putting enough leading blanks. */ +static wchar_t * +wcenter(wchar_t *s, wchar_t *t, int w) +{ + char blanks[MAX_WIDTH]; + + memset(blanks, ' ', sizeof(blanks)); + swprintf(s, MAX_WIDTH, L"%.*s%ls", (int)(w - wcslen(t)) / 2, blanks, t); + return (s); +} + +static int +parsemonth(const char *s, int *m, int *y) +{ + int nm, ny; + char *cp; + struct tm tm; + + nm = (int)strtol(s, &cp, 10); + if (cp != s) { + ny = *y; + if (*cp == '\0') { + ; /* no special action */ + } else if (*cp == 'f' || *cp == 'F') { + if (nm <= *m) + ny++; + } else if (*cp == 'p' || *cp == 'P') { + if (nm >= *m) + ny--; + } else + return (1); + if (nm < 1 || nm > 12) + return 1; + *m = nm; + *y = ny; + return (0); + } + if (strptime(s, "%B", &tm) != NULL || strptime(s, "%b", &tm) != NULL) { + *m = tm.tm_mon + 1; + return (0); + } + return (1); +} + +static void +highlight(char *dst, char *src, int len, int *extralen) +{ + static int first = 1; + static const char *term_so, *term_se; + + if (first) { + static char cbuf[512]; + char tbuf[1024], *b; + + term_se = term_so = NULL; + + /* On how to highlight on this type of terminal (if any). */ + if (isatty(STDOUT_FILENO) && tgetent(tbuf, NULL) == 1) { + b = cbuf; + term_so = tgetstr("so", &b); + term_se = tgetstr("se", &b); + } + + first = 0; + } + + /* + * This check is not necessary, should have been handled before calling + * this function. + */ + if (flag_nohighlight) { + memcpy(dst, src, len); + return; + } + + /* + * If it is a real terminal, use the data from the termcap database. + */ + if (term_so != NULL && term_se != NULL) { + /* separator. */ + dst[0] = ' '; + dst++; + /* highlight on. */ + memcpy(dst, term_so, strlen(term_so)); + dst += strlen(term_so); + /* the actual text. (minus leading space) */ + len--; + src++; + memcpy(dst, src, len); + dst += len; + /* highlight off. */ + memcpy(dst, term_se, strlen(term_se)); + *extralen += strlen(term_so) + strlen(term_se); + return; + } + + /* + * Otherwise, print a _, backspace and the letter. + */ + *extralen = 0; + /* skip leading space. */ + src++; + len--; + /* separator. */ + dst[0] = ' '; + dst++; + while (len > 0) { + /* _ and backspace. */ + memcpy(dst, "_\010", 2); + dst += 2; + *extralen += 2; + /* the character. */ + *dst++ = *src++; + len--; + } + return; +}