13 /* add abstraction at no cost, but may add more complexity as well? */
14 enum { FALSE
= 0, TRUE
= 1 };
15 enum { NEXT
= 0, PREV
= 1, BOTH
= 2 };
17 /* preprocessor macros */
18 #define LENGTH(x) (sizeof(x) / sizeof(*x))
19 #define CONTROL(char) (char ^ 0x40)
20 #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
21 #define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
23 /* command line options */
24 int opt_line_numbers
= FALSE
;
25 int opt_complete_mode
= FALSE
;
26 int opt_print_numbers
= FALSE
;
27 char opt_validate_key
= CONTROL('M');
28 char* opt_separator
= NULL
;
30 char* opt_prompt
= "";
33 * Fill the buffer apropriately with the lines and headers.
36 fill_buffer(char *separator
)
38 /* fill buffer with string */
39 char string
[LINE_SIZE
];
41 Buffer
*buffer
= malloc(sizeof(Buffer
));
42 FILE *fp
= fopen("/dev/stdin", "r");
45 die("Can not open file for reading.");
48 /* read the file into a doubly linked list of lines */
49 while (fgets(string
, LINE_SIZE
, fp
)) {
51 last
= add_line(buffer
, buffer
->total
, string
, separator
, last
);
54 /* set the buffer stats */
55 buffer
->current
= buffer
->first
;
58 buffer
->empty
= malloc(sizeof(Line
));
59 buffer
->empty
->content
= "";
60 buffer
->empty
->comment
= "";
61 buffer
->empty
->number
= 0;
62 buffer
->empty
->matches
= 0;
63 buffer
->empty
->next
= buffer
->first
;
64 buffer
->empty
->prev
= buffer
->first
;
70 * Add a line to the end of the current buffer.
72 * This requires to create a new line with a link to the previous line
73 * and to NULL as the next line.
75 * The previous line's 'next' should be relinked to this new line.
77 * The header's last line have to point to this last line
80 add_line(Buffer
*buffer
, int number
, char *string
, char *separator
, Line
*prev
)
82 /* allocate new line */
83 Line
*line
= malloc(sizeof(Line
));
84 line
= parse_line(string
, separator
);
88 line
->number
= number
;
90 /* interlink with previous line if exists */
102 * Parse the line content to determine if it is a header and identify the
106 parse_line(char *s
, char *separator
)
108 Line
*line
= malloc(sizeof(Line
));
109 char *sep
= separator
? strstr(s
, separator
) : NULL
;
110 int pos
= sep
? (int) (sep
- s
) : (int) strlen(s
) - 1;
112 /* strip trailing newline */
113 s
[strlen(s
) - 1] = '\0';
115 /* fill line->content */
116 line
->content
= malloc((pos
+ 1) * sizeof(char));
117 strncpy(line
->content
, s
, pos
);
119 /* fill line->comment */
121 line
->comment
= malloc((strlen(s
) - pos
) * sizeof(char));
122 strcpy(line
->comment
, s
+ pos
);
131 * Set buffer->candidates to an array of lines that match and update
132 * buffer->matching to number of matching candidates.
135 filter_lines(Buffer
*buffer
)
137 Line
* line
= buffer
->first
;
138 buffer
->matching
= 0;
141 line
->matches
= line_match_input(line
, buffer
->input
);
142 buffer
->matching
+= line
->matches
;
149 * Check if line matches and return TRUE or FALSE
152 line_match_input(Line
*line
, char *input
)
154 if (opt_complete_mode
) {
155 if (!strncmp(input
, line
->content
, strlen(input
))) {
159 if (strstr(line
->content
, input
)) {
168 * Seek the previous matching line, or NULL if none matches.
171 matching_prev(Line
*line
)
173 while ((line
= line
->prev
) && !line
->matches
)
179 * Seek the next matching line, or NULL if none matches.
182 matching_next(Line
*line
)
184 while ((line
= line
->next
) && !line
->matches
)
190 * Replace tab as a multiple of 8 spaces in a line.
193 expand_tabs(char *line
)
196 char *converted
= malloc(sizeof(char) * (strlen(line
) * 8 + 1));
198 for (i
= 0, n
= 0; i
< strlen(line
); i
++, n
++) {
199 if (line
[i
] == '\t') {
203 for (; (n
) % 8 != 0; n
++) {
209 converted
[n
] = line
[i
];
219 * Print a line to stderr.
222 print_line(Line
*line
, int current
, int cols
)
226 char *content
= expand_tabs(line
->content
);
227 char *comment
= expand_tabs(line
->comment
);
229 /* clean the line in case it was not empty */
230 fputs("\033[K", stderr
);
232 /* line number if option set */
233 if (opt_line_numbers
) {
235 fputs("\033[1m", stderr
);
237 fputs("\033[1;30m", stderr
);
240 fprintf(stderr
, "%7d\033[0m ", line
->number
);
246 /* highlight current line */
248 fputs("\033[1;33m", stderr
);
251 /* print content without overflowing terminal width */
252 for (i
= 0; i
< strlen(content
) && n
< cols
; n
++, i
++) {
253 fputc(content
[i
], stderr
);
256 /* print spaces without overflowing terminal width */
257 for (i
= n
; i
<= 40 && n
< cols
; n
++, i
++) {
261 /* comments in grey */
262 fputs("\033[1;30m", stderr
);
264 /* print comment without overflowing terminal width */
265 for (i
= 0; i
< strlen(comment
) && n
< cols
; n
++, i
++) {
266 fputc(comment
[i
], stderr
);
269 fputs("\033[0m\n", stderr
);
276 * Print a header title.
284 * Print all the lines from an array of pointer to lines.
286 * The total number oflines printed shall not excess 'count'.
289 print_lines(Buffer
*buffer
, int count
, int offset
, int cols
)
291 Line
*line
= buffer
->current
;
295 /* seek back from current line to the first line to print */
296 while (line
&& i
< count
- offset
) {
297 i
= line
->matches
? i
+ 1 : i
;
300 line
= line
? line
: buffer
->first
;
302 /* print up to count lines that match the input */
303 while (line
&& j
< count
) {
305 print_line(line
, line
== buffer
->current
, cols
);
312 /* continue up to the end of the screen clearing it */
313 for (; j
< count
; j
++) {
314 fputs("\r\033[K\n", stderr
);
319 * Update the screen interface and print all candidates.
321 * This also has to clear the previous lines.
324 update_screen(Buffer
*buffer
, int count
, int offset
, int tty
)
327 ioctl(tty
, TIOCGWINSZ
, &w
);
330 print_lines(buffer
, count
, offset
, w
.ws_col
);
332 /* go up to the prompt position and update it */
333 fprintf(stderr
, "\033[%dA", count
+ 1);
334 print_prompt(buffer
, w
.ws_col
);
337 void clear_screen(int count
)
340 for (i
= 0; i
< count
+ 1; i
++) {
341 fputs("\r\033[K\n", stderr
);
344 fprintf(stderr
, "\033[%dA", count
+ 1);
348 * Set terminal to send one char at a time for interactive mode, and return the
349 * last terminal state.
352 terminal_set(int tty
)
354 struct termios termio_old
;
355 struct termios termio_new
;
357 /* set the terminal to send one key at a time. */
359 /* get the terminal's state */
360 if (tcgetattr(tty
, &termio_old
) < 0) {
361 die("Can not get terminal attributes with tcgetattr().");
364 /* create a new modified state by switching the binary flags */
365 termio_new
= termio_old
;
366 termio_new
.c_lflag
&= ~(ICANON
| ECHO
| IGNBRK
);
368 /* apply this state to current terminal now (TCSANOW) */
369 tcsetattr(tty
, TCSANOW
, &termio_new
);
375 * Listen for the user input and call the appropriate functions.
378 get_input(Buffer
*buffer
, int count
, int offset
, int tty
)
380 FILE *tty_fd
= fopen("/dev/tty", "r");
382 /* receive one character at a time from the terminal */
383 struct termios termio_old
= terminal_set(tty
);
385 /* get input char by char from the keyboard. */
386 while (do_key(fgetc(tty_fd
), buffer
)) {
387 update_screen(buffer
, count
, offset
, tty
);
390 /* resets the terminal to the previous state. */
391 tcsetattr(tty
, TCSANOW
, &termio_old
);
397 * Perform action associated with key
400 do_key(char key
, Buffer
*buffer
)
402 if (key
== opt_validate_key
) {
403 do_print_selection(buffer
);
413 buffer
->input
[0] = '\0';
414 buffer
->current
= buffer
->first
;
415 filter_lines(buffer
);
419 do_remove_word_input(buffer
);
420 filter_lines(buffer
);
424 case CONTROL('H'): /* backspace */
425 buffer
->input
[strlen(buffer
->input
) - 1] = '\0';
426 filter_lines(buffer
);
428 if (!buffer
->current
->matches
) {
429 do_jump(buffer
, BOTH
);
434 do_jump(buffer
, NEXT
);
438 do_jump(buffer
, PREV
);
441 case CONTROL('I'): /* tab */
442 strcpy(buffer
->input
, buffer
->current
->content
);
443 filter_lines(buffer
);
447 case CONTROL('J'): /* enter */
448 do_print_selection(buffer
);
452 do_add_character(buffer
, key
);
459 * Set the current line to the next/previous/closest matching line.
462 do_jump(Buffer
*buffer
, int direction
)
464 Line
* line
= buffer
->current
;
466 if (direction
== BOTH
) {
467 line
= matching_next(buffer
->current
);
468 line
= (line
) ? line
: matching_prev(buffer
->current
);
469 } else if (direction
== NEXT
) {
470 line
= matching_next(line
);
471 } else if (direction
== PREV
) {
472 line
= matching_prev(line
);
475 buffer
->current
= (line
) ? line
: buffer
->current
;
477 if (opt_print_numbers
)
478 do_print_selection(buffer
);
482 * Send the selection to stdout.
485 do_print_selection(Buffer
*buffer
)
487 fputs("\r\033[K", stderr
);
489 if (opt_print_numbers
) {
490 printf("%d\n", buffer
->current
->number
);
492 if (opt_complete_mode
) {
495 puts(buffer
->current
->content
);
501 * Remove the last word from the buffer's input
504 do_remove_word_input(Buffer
*buffer
)
506 size_t length
= strlen(buffer
->input
) - 1;
509 for (i
= length
; i
>= 0 && isspace(buffer
->input
[i
]); i
--) {
510 buffer
->input
[i
] = '\0';
513 length
= strlen(buffer
->input
) - 1;
514 for (i
= length
; i
>= 0 && !isspace(buffer
->input
[i
]); i
--) {
515 buffer
->input
[i
] = '\0';
520 * Add a character to the buffer input and filter lines again.
523 do_add_character(Buffer
*buffer
, char key
)
525 size_t length
= strlen(buffer
->input
);
528 buffer
->input
[length
] = key
;
529 buffer
->input
[length
+ 1] = '\0';
532 filter_lines(buffer
);
534 if (!buffer
->current
->matches
) {
535 do_jump(buffer
, BOTH
);
538 if (!buffer
->current
->matches
) {
539 buffer
->current
= buffer
->empty
;
544 * Print the prompt, before the input, with the number of candidates that
548 print_prompt(Buffer
*buffer
, int cols
)
551 int matching
= buffer
->matching
;
552 int total
= buffer
->total
;
553 char *input
= expand_tabs(buffer
->input
);
554 char *suggest
= expand_tabs(buffer
->current
->content
);
556 /* for the '/' separator between the numbers */
559 /* number of digits */
560 for (i
= matching
; i
; i
/= 10, cols
--)
562 for (i
= total
; i
; i
/= 10, cols
--)
565 /* 0 also has one digit*/
566 cols
-= !matching
? 1 : 0;
569 fprintf(stderr
, "\r%s\033[K> ", opt_prompt
);
570 cols
-= 2 + strlen(opt_prompt
);
572 /* input without overflowing terminal width */
573 for (i
= 0; i
< strlen(input
) && cols
> 0; cols
--, i
++) {
574 fputc(input
[i
], stderr
);
577 /* save the cursor position at the end of the input */
578 fputs("\033[s", stderr
);
581 fputs("\033[1;30m", stderr
);
583 /* suggest without overflowing terminal width */
584 if (opt_complete_mode
) {
585 for (; i
< strlen(suggest
) && cols
> 0; cols
--, i
++) {
586 fputc(suggest
[i
], stderr
);
590 /* go to the end of the line */
591 for (i
= 0; cols
> 0; cols
--, i
++) {
595 /* total match and line count at the end of the line */
596 fprintf(stderr
, "%d/%d", matching
, total
);
598 /* restore cursor position at the end of the input */
599 fputs("\033[0m\033[u", stderr
);
606 * Reset the terminal state and exit with error.
608 void die(const char *s
)
610 /* tcsetattr(STDIN_FILENO, TCSANOW, &termio_old); */
611 fprintf(stderr
, "%s\n", s
);
617 main(int argc
, char *argv
[])
620 Buffer
*buffer
= NULL
;
622 int tty
= open("/dev/tty", O_RDWR
);
624 /* command line arguments */
625 for (i
= 0; i
< argc
; i
++) {
626 if (argv
[i
][0] == '-') {
627 switch (argv
[i
][1]) {
629 opt_line_numbers
= TRUE
;
632 opt_complete_mode
= TRUE
;
635 opt_print_numbers
= TRUE
;
636 opt_line_numbers
= TRUE
;
639 opt_validate_key
= (argv
[i
++][0] == '^') ?
644 opt_separator
= argv
[++i
];
647 if (sscanf(argv
[++i
], "%d", &opt_lines
) <= 0)
648 die("Wrong number format after -l.");
651 opt_prompt
= argv
[++i
];
657 /* command line arguments */
658 buffer
= fill_buffer(opt_separator
);
660 /* set the interface */
661 filter_lines(buffer
);
662 update_screen(buffer
, opt_lines
, offset
, tty
);
664 /* listen and interact to input */
665 get_input(buffer
, opt_lines
, offset
, tty
);
667 clear_screen(opt_lines
);