fzy

terminal fuzzy finder picker

git clone https://9o.is/git/fzy.git

commit 2e91e53da849e489503ea1e4c58e581b02ad3bcd
parent 8e027a6af3b0b33cbbe6326bef63e2a0f36034bb
Author: John Hawthorn <john.hawthorn@gmail.com>
Date:   Mon,  4 Aug 2014 00:08:10 -0700

Extract ANSI CSI SGR calls into tty.c

Diffstat:
Mfzy.c | 11++++++-----
Mtty.c | 22++++++++++++++++++++++
Mtty.h | 6++++++
3 files changed, 34 insertions(+), 5 deletions(-)

diff --git a/fzy.c b/fzy.c @@ -106,17 +106,20 @@ void draw_match(tty_t *tty, const char *choice, int selected){ match_positions(search, choice, &positions[0]); + if(selected) + tty_setinvert(tty); + for(size_t i = 0, p = 0; choice[i] != '\0'; i++){ if(positions[p] == i){ - fprintf(tty->fout, "%c%c33m", 0x1b, '['); + tty_setfg(tty, 3); p++; }else{ - fprintf(tty->fout, "%c%c39;49m", 0x1b, '['); + tty_setfg(tty, 9); } fprintf(tty->fout, "%c", choice[i]); } fprintf(tty->fout, "\n"); - fprintf(tty->fout, "%c%c0m", 0x1b, '['); + tty_setnormal(tty); } void draw(tty_t *tty){ @@ -125,8 +128,6 @@ void draw(tty_t *tty){ clear(tty); fprintf(tty->fout, "%s%s\n", prompt, search); for(size_t i = 0; line < NUMLINES && i < choices_available; i++){ - if(i == current_selection) - fprintf(tty->fout, "%c%c7m", 0x1b, '['); draw_match(tty, choices[choices_sorted[i]], i == current_selection); line++; } diff --git a/tty.c b/tty.c @@ -20,6 +20,8 @@ void tty_init(tty_t *tty){ new_termios.c_lflag &= ~(ICANON | ECHO); tcsetattr(tty->fdin, TCSANOW, &new_termios); + + tty_setnormal(tty); } char tty_getchar(tty_t *tty){ @@ -36,3 +38,23 @@ char tty_getchar(tty_t *tty){ } } +static void tty_sgr(tty_t *tty, int code){ + fprintf(tty->fout, "%c%c%im", 0x1b, '[', code); +} + +void tty_setfg(tty_t *tty, int fg){ + if(tty->fgcolor != fg){ + tty_sgr(tty, 30 + fg); + tty->fgcolor = fg; + } +} + +void tty_setinvert(tty_t *tty){ + tty_sgr(tty, 7); +} + +void tty_setnormal(tty_t *tty){ + tty_sgr(tty, 0); + tty->fgcolor = 9; +} + diff --git a/tty.h b/tty.h @@ -7,10 +7,16 @@ typedef struct{ int fdin; FILE *fout; struct termios original_termios; + int fgcolor; } tty_t; void tty_reset(tty_t *tty); void tty_init(tty_t *tty); char tty_getchar(tty_t *tty); +void tty_setfg(tty_t *tty, int fg); +void tty_setinvert(tty_t *tty); +void tty_setnormal(tty_t *tty); + + #endif