From 1198dda7ce916af5a5d0a08f37d4888a66d2989e Mon Sep 17 00:00:00 2001 From: Elliott Hughes Date: Sun, 19 Jan 2020 16:13:57 -0800 Subject: cal: highlight current day. This isn't in POSIX, but Debian and macOS' cal(1)s both do this, and it's annoying to have to run date(1) separately. --- toys/posix/cal.c | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/toys/posix/cal.c b/toys/posix/cal.c index bd3afad4..aaed5933 100644 --- a/toys/posix/cal.c +++ b/toys/posix/cal.c @@ -4,7 +4,7 @@ * * See http://opengroup.org/onlinepubs/9699919799/utilities/cal.html -USE_CAL(NEWTOY(cal, ">2", TOYFLAG_USR|TOYFLAG_BIN)) +USE_CAL(NEWTOY(cal, ">2h", TOYFLAG_USR|TOYFLAG_BIN)) config CAL bool "cal" @@ -16,10 +16,17 @@ config CAL With one argument, prints all months of the specified year. With two arguments, prints calendar for month and year. + + -h Don't highlight today */ +#define FOR_cal #include "toys.h" +GLOBALS( + struct tm *now; +) + // Write calendar into buffer: each line is 20 chars wide, end indicated // by empty string. @@ -54,6 +61,10 @@ static char *calstrings(char *buf, struct tm *tm) char *pat = " "; if (!mday ? wday==start : mdaytm_year == TT.now->tm_year && + tm->tm_mon == TT.now->tm_mon && mday == TT.now->tm_mday-1) { + pat = "\x1b[7m%2d\x1b[m "; + } mday++; } buf += sprintf(buf, pat, mday); @@ -65,13 +76,18 @@ static char *calstrings(char *buf, struct tm *tm) } // Worst case scenario toybuf usage: sizeof(struct tm) plus 21 bytes/line -// plus 8 lines/month plus 12 months, comes to a bit over 2k of our 4k buffer. +// plus 8 lines/month plus 12 months, plus the escape sequences to highlight +// today comes to a bit over 2k of our 4k buffer. void cal_main(void) { - struct tm *tm; + time_t now = time(0); + struct tm *tm = localtime(&now); char *buf = toybuf; + TT.now = tm; + if (!isatty(1)) toys.optflags |= FLAG_h; + if (toys.optc) { // Conveniently starts zeroed tm = (struct tm *)toybuf; @@ -113,11 +129,6 @@ void cal_main(void) // What day of the week does that start on? mktime(tm); - - } else { - time_t now; - time(&now); - tm = localtime(&now); } calstrings(buf, tm); -- cgit v1.2.3