a568d3c5c82fb065eaaff9c86aeed02ff5310094
[paraslash.git] / interactive.c
1 /*
2  * Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file interactive.c Readline abstraction for interactive sessions. */
8
9 #include "para.h"
10
11 #include <regex.h>
12 #include <readline/readline.h>
13 #include <readline/history.h>
14 #include <sys/ioctl.h>
15 #include <signal.h>
16
17 #include "fd.h"
18 #include "buffer_tree.h"
19 #include "list.h"
20 #include "sched.h"
21 #include "interactive.h"
22 #include "string.h"
23 #include "error.h"
24
25 struct i9e_private {
26         struct i9e_client_info *ici;
27         FILE *stderr_stream;
28         int num_columns;
29         int num_key_bindings;
30         char empty_line[1000];
31         char key_sequence[32];
32         unsigned key_sequence_length;
33         struct task *task;
34         struct btr_node *stdout_btrn;
35         bool last_write_was_status;
36         bool input_eof;
37         bool caught_sigint;
38         bool caught_sigterm;
39         Keymap standard_km;
40         Keymap bare_km;
41 };
42 static struct i9e_private i9e_private, *i9ep = &i9e_private;
43
44 /**
45  * Return the error state of the i9e task.
46  *
47  * This is mainly useful for other tasks to tell whether the i9e task is still
48  * running.
49  *
50  * \return A negative return value of zero means the i9e task terminated. Only
51  * in this case it is safe to call ie9_close().
52  */
53 int i9e_get_error(void)
54 {
55         return task_status(i9ep->task);
56 }
57
58 static bool is_prefix(const char *partial, const char *full, size_t len)
59 {
60         if (len == 0)
61                 len = strlen(partial);
62         return !strncmp(partial, full, len);
63 }
64
65 /*
66  * Generator function for command completion. STATE lets us know whether
67  * to start from scratch; without any state (i.e. STATE == 0), then we
68  * start at the top of the list.
69  */
70 static char *command_generator(const char *text, int state)
71 {
72         static int list_index, len;
73         const char *name;
74         struct i9e_client_info *ici = i9ep->ici;
75
76         rl_attempted_completion_over = 1; /* disable filename completion */
77         /*
78          * If this is a new word to complete, initialize now. This includes
79          * saving the length of TEXT for efficiency, and initializing the index
80          * variable to 0.
81          */
82         if (state == 0) {
83                 list_index = 0;
84                 len = strlen(text);
85         }
86         /* Return the next name which partially matches from the command list. */
87         while ((name = ici->completers[list_index].name)) {
88                 list_index++;
89                 if (is_prefix(text, name, len))
90                         return para_strdup(name);
91         }
92         return NULL; /* no names matched */
93 }
94
95 static void reset_completion_result(struct i9e_completion_result *cr)
96 {
97         cr->dont_append_space = false;
98         cr->filename_completion_desired = false;
99         cr->matches = NULL;
100 }
101
102 static void create_matches(struct i9e_completion_info *ci,
103                 struct i9e_completer *completers,
104                 struct i9e_completion_result *cr)
105 {
106         int i, ret;
107
108         reset_completion_result(cr);
109
110         ret = create_argv(ci->buffer, " ", &ci->argv);
111         if (ret < 0 || !ci->argv[0])
112                 return;
113
114         ci->argc = ret;
115         ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
116         for (i = 0; completers[i].name; i++) {
117                 if (strcmp(completers[i].name, ci->argv[0]) != 0)
118                         continue;
119                 completers[i].completer(ci, cr);
120                 break;
121         }
122         PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
123                 ci->argv[ci->word_num]);
124         if (cr->matches)
125                 for (i = 0; cr->matches[i]; i++)
126                         PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
127 }
128
129 static char *completion_generator(const char *word, int state)
130 {
131         static int list_index;
132         static char **argv, **matches;
133         struct i9e_completer *completers = i9ep->ici->completers;
134         struct i9e_completion_info ci = {
135                 .word = (char *)word,
136                 .point = rl_point,
137                 .buffer = rl_line_buffer,
138         };
139         struct i9e_completion_result cr = {.matches = NULL};
140
141         if (state != 0)
142                 goto out;
143         /* clean up previous matches and set defaults */
144         free(matches);
145         matches = NULL;
146         free_argv(argv);
147         argv = NULL;
148         list_index = 0;
149         rl_completion_append_character = ' ';
150         rl_completion_suppress_append = false;
151         rl_attempted_completion_over = true;
152
153         create_matches(&ci, completers, &cr);
154
155         matches = cr.matches;
156         argv = ci.argv;
157         rl_completion_suppress_append = cr.dont_append_space;
158         rl_attempted_completion_over = !cr.filename_completion_desired;
159 out:
160         if (!matches)
161                 return NULL;
162         return matches[list_index++];
163 }
164
165 /*
166  * Attempt to complete on the contents of TEXT. START and END bound the
167  * region of rl_line_buffer that contains the word to complete.  TEXT is
168  * the word to complete.  We can use the entire contents of rl_line_buffer
169  * in case we want to do some simple parsing. Return the array of matches,
170  * or NULL if there aren't any.
171  */
172 static char **i9e_completer(const char *text, int start, __a_unused int end)
173 {
174         struct i9e_client_info *ici = i9ep->ici;
175
176         if (!ici->completers)
177                 return NULL;
178         /* Complete on command names if this is the first word in the line. */
179         if (start == 0)
180                 return rl_completion_matches(text, command_generator);
181         return rl_completion_matches(text, completion_generator);
182 }
183
184 /**
185  * Prepare writing to stdout.
186  *
187  * \param producer The buffer tree node which produces output.
188  *
189  * The i9e subsystem maintains a buffer tree node which may be attached to
190  * another node which generates output (a "producer"). When attached, the i9e
191  * buffer tree node copies the buffers generated by the producer to stdout.
192  *
193  * This function attaches the i9e input queue to an output queue of \a
194  * producer.
195  *
196  * \return Standard.
197  */
198 void i9e_attach_to_stdout(struct btr_node *producer)
199 {
200         btr_remove_node(&i9ep->stdout_btrn);
201         i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
202                 EMBRACE(.name = "interactive_stdout", .parent = producer));
203         rl_set_keymap(i9ep->bare_km);
204 }
205
206 static void wipe_bottom_line(void)
207 {
208         char x[] = "          ";
209         int n = i9ep->num_columns;
210
211         /*
212          * For reasons beyond my understanding, writing more than 68 characters
213          * here causes MacOS to mess up the terminal. Writing a line of spaces
214          * in smaller chunks works fine though. Weird.
215          */
216         fprintf(i9ep->stderr_stream, "\r");
217         while (n > 0) {
218                 if (n >= sizeof(x)) {
219                         fprintf(i9ep->stderr_stream, "%s", x);
220                         n -= sizeof(x);
221                         continue;
222                 }
223                 x[n] = '\0';
224                 fprintf(i9ep->stderr_stream, "%s", x);
225                 break;
226         }
227         fprintf(i9ep->stderr_stream, "\r");
228 }
229
230 #ifndef RL_FREE_KEYMAP_DECLARED
231 /**
232  * Free all storage associated with a keymap.
233  *
234  * This function is not declared in the readline headers although the symbol is
235  * exported and the function is documented in the readline info file. So we
236  * have to declare it here.
237  *
238  * \param keymap The keymap to deallocate.
239  */
240 void rl_free_keymap(Keymap keymap);
241 #endif
242
243 /**
244  * Reset the terminal and save the in-memory command line history.
245  *
246  * This should be called before the caller exits.
247  */
248 void i9e_close(void)
249 {
250         char *hf = i9ep->ici->history_file;
251
252         rl_free_keymap(i9ep->bare_km);
253         rl_callback_handler_remove();
254         if (hf)
255                 write_history(hf);
256         wipe_bottom_line();
257 }
258
259 static void clear_bottom_line(void)
260 {
261         int point;
262         char *text;
263
264         if (rl_point == 0 && rl_end == 0)
265                 return wipe_bottom_line();
266         /*
267          * We might have a multi-line input that needs to be wiped here, so the
268          * simple printf("\r<space>\r") is insufficient. To workaround this, we
269          * remove the whole line, redisplay and restore the killed text.
270          */
271         point = rl_point;
272         text = rl_copy_text(0, rl_end);
273         rl_kill_full_line(0, 0);
274         rl_redisplay();
275         wipe_bottom_line(); /* wipe out the prompt */
276         rl_insert_text(text);
277         free(text);
278         rl_point = point;
279 }
280
281 static bool input_available(void)
282 {
283         fd_set rfds;
284         struct timeval tv = {0, 0};
285         int ret;
286
287         FD_ZERO(&rfds);
288         FD_SET(i9ep->ici->fds[0], &rfds);
289         ret = para_select(1, &rfds, NULL, &tv);
290         return ret > 0;
291 }
292
293 static void i9e_line_handler(char *line)
294 {
295         int ret;
296         struct btr_node *dummy;
297
298         if (!line) {
299                 i9ep->input_eof = true;
300                 return;
301         }
302         if (!*line)
303                 goto free_line;
304         rl_set_prompt("");
305         dummy = btr_new_node(&(struct btr_node_description)
306                 EMBRACE(.name = "dummy line handler"));
307         i9e_attach_to_stdout(dummy);
308         ret = i9ep->ici->line_handler(line);
309         if (ret < 0)
310                 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
311         add_history(line);
312         btr_remove_node(&dummy);
313 free_line:
314         free(line);
315 }
316
317 static int i9e_post_select(__a_unused struct sched *s, __a_unused void *context)
318 {
319         int ret;
320         struct i9e_client_info *ici = i9ep->ici;
321         char *buf;
322         size_t sz, consumed = 0;
323
324         ret = -E_I9E_EOF;
325         if (i9ep->input_eof)
326                 goto rm_btrn;
327         ret = -E_I9E_TERM_RQ;
328         if (i9ep->caught_sigterm)
329                 goto rm_btrn;
330         ret = 0;
331         if (i9ep->caught_sigint)
332                 goto rm_btrn;
333         while (input_available()) {
334                 if (i9ep->stdout_btrn) {
335                         unsigned len = i9ep->key_sequence_length;
336                         assert(len < sizeof(i9ep->key_sequence) - 1);
337                         buf = i9ep->key_sequence + len;
338                         ret = read(i9ep->ici->fds[0], buf, 1);
339                         if (ret < 0) {
340                                 ret = -ERRNO_TO_PARA_ERROR(errno);
341                                 goto rm_btrn;
342                         }
343                         ret = -E_I9E_EOF;
344                         if (ret == 0)
345                                 goto rm_btrn;
346                         buf[1] = '\0';
347                         i9ep->key_sequence_length++;
348                         rl_stuff_char((int)(unsigned char)*buf);
349                 }
350                 rl_callback_read_char();
351                 ret = 0;
352         }
353         if (!i9ep->stdout_btrn)
354                 goto out;
355         ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
356         if (ret < 0) {
357                 ret = 0;
358                 goto rm_btrn;
359         }
360         if (ret == 0)
361                 goto out;
362 again:
363         sz = btr_next_buffer(i9ep->stdout_btrn, &buf);
364         if (sz == 0)
365                 goto out;
366         if (i9ep->last_write_was_status)
367                 fprintf(i9ep->stderr_stream, "\n");
368         i9ep->last_write_was_status = false;
369         ret = xwrite(ici->fds[1], buf, sz);
370         if (ret < 0)
371                 goto rm_btrn;
372         btr_consume(i9ep->stdout_btrn, ret);
373         consumed += ret;
374         if (ret == sz && consumed < 10000)
375                 goto again;
376         goto out;
377 rm_btrn:
378         if (i9ep->stdout_btrn) {
379                 wipe_bottom_line();
380                 btr_remove_node(&i9ep->stdout_btrn);
381                 rl_set_keymap(i9ep->standard_km);
382                 rl_set_prompt(i9ep->ici->prompt);
383                 rl_redisplay();
384         }
385         if (ret < 0)
386                 wipe_bottom_line();
387 out:
388         i9ep->caught_sigint = false;
389         return ret;
390 }
391
392 static void i9e_pre_select(struct sched *s, __a_unused void *context)
393 {
394         int ret;
395
396         if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
397                 sched_min_delay(s);
398                 return;
399         }
400         if (i9ep->stdout_btrn) {
401                 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
402                 if (ret < 0) {
403                         sched_min_delay(s);
404                         return;
405                 }
406                 if (ret > 0)
407                         para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
408         }
409         /*
410          * fd[0] might have been reset to blocking mode if our job was moved to
411          * the background due to CTRL-Z or SIGSTOP, so set the fd back to
412          * nonblocking mode.
413          */
414         ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
415         if (ret < 0)
416                 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
417                         i9ep->ici->fds[0], para_strerror(-ret));
418         para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
419 }
420
421 static void update_winsize(void)
422 {
423         struct winsize w;
424         int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
425
426         if (ret >= 0) {
427                 assert(w.ws_col < sizeof(i9ep->empty_line));
428                 i9ep->num_columns = w.ws_col;
429         } else
430                 i9ep->num_columns = 80;
431
432         memset(i9ep->empty_line, ' ', i9ep->num_columns);
433         i9ep->empty_line[i9ep->num_columns] = '\0';
434 }
435
436 static int dispatch_key(__a_unused int count, __a_unused int key)
437 {
438         int i, ret;
439
440         for (i = i9ep->num_key_bindings - 1; i >= 0; i--) {
441                 if (strcmp(i9ep->key_sequence, i9ep->ici->bound_keyseqs[i]))
442                         continue;
443                 i9ep->key_sequence[0] = '\0';
444                 i9ep->key_sequence_length = 0;
445                 ret = i9ep->ici->key_handler(i);
446                 return ret < 0? ret : 0;
447         }
448         assert(0);
449 }
450
451 /**
452  * Register the i9e task and initialize readline.
453  *
454  * \param ici The i9e configuration parameters set by the caller.
455  * \param s The scheduler instance to add the i9e task to.
456  *
457  * The caller must allocate and initialize the structure \a ici points to.
458  *
459  * \return Standard.
460  */
461 int i9e_open(struct i9e_client_info *ici, struct sched *s)
462 {
463         int ret;
464
465         memset(i9ep, 0, sizeof(struct i9e_private));
466         if (!isatty(ici->fds[0]))
467                 return -E_I9E_SETUPTERM;
468         ret = mark_fd_nonblocking(ici->fds[0]);
469         if (ret < 0)
470                 return ret;
471         ret = mark_fd_nonblocking(ici->fds[1]);
472         if (ret < 0)
473                 return ret;
474         i9ep->task = task_register(&(struct task_info) {
475                 .name = "i9e",
476                 .pre_select = i9e_pre_select,
477                 .post_select = i9e_post_select,
478                 .context = i9ep,
479         }, s);
480
481         rl_readline_name = "para_i9e";
482         rl_basic_word_break_characters = " ";
483         rl_attempted_completion_function = i9e_completer;
484         i9ep->ici = ici;
485         i9ep->stderr_stream = fdopen(ici->fds[2], "w");
486         setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
487
488         i9ep->standard_km = rl_get_keymap();
489         i9ep->bare_km = rl_make_bare_keymap();
490         if (ici->bound_keyseqs) {
491                 char *seq;
492                 int i;
493                 /* bind each key sequence to our dispatcher */
494                 for (i = 0; (seq = ici->bound_keyseqs[i]); i++) {
495                         if (strlen(seq) >= sizeof(i9ep->key_sequence) - 1) {
496                                 PARA_WARNING_LOG("ignoring overlong key %s\n",
497                                         seq);
498                                 continue;
499                         }
500                         if (rl_bind_keyseq_in_map(seq,
501                                         dispatch_key, i9ep->bare_km) != 0)
502                                 PARA_WARNING_LOG("could not bind #%d: %s\n", i, seq);
503                 }
504                 i9ep->num_key_bindings = i;
505         }
506         if (ici->history_file)
507                 read_history(ici->history_file);
508         update_winsize();
509         if (ici->producer) {
510                 rl_callback_handler_install("", i9e_line_handler);
511                 i9e_attach_to_stdout(ici->producer);
512         } else
513                 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
514         return 1;
515 }
516
517 static void reset_line_state(void)
518 {
519         if (i9ep->stdout_btrn)
520                 return;
521         rl_on_new_line();
522         rl_reset_line_state();
523         rl_forced_update_display();
524 }
525
526 /**
527  * The log function of the i9e subsystem.
528  *
529  * \param ll Severity log level.
530  * \param fmt Printf-like format string.
531  *
532  * This clears the bottom line of the terminal if necessary and writes the
533  * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
534  * \ref i9e_open().
535  */
536 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
537 {
538         va_list argp;
539
540         if (ll < i9ep->ici->loglevel)
541                 return;
542         clear_bottom_line();
543         va_start(argp, fmt);
544         vfprintf(i9ep->stderr_stream, fmt, argp);
545         va_end(argp);
546         reset_line_state();
547         i9ep->last_write_was_status = false;
548 }
549
550 /**
551  * Print the current status to stderr.
552  *
553  * \param buf The text to print.
554  * \param len The number of bytes in \a buf.
555  *
556  * This clears the bottom line, moves to the beginning of the line and prints
557  * the given text. If the length of this text exceeds the width of the
558  * terminal, the text is shortened by leaving out a part in the middle.
559  */
560 void ie9_print_status_bar(char *buf, unsigned len)
561 {
562         size_t x = i9ep->num_columns, y = (x - 4) / 2;
563
564         assert(x >= 6);
565         if (len > x) {
566                 buf[y] = '\0';
567                 fprintf(i9ep->stderr_stream, "\r%s", buf);
568                 fprintf(i9ep->stderr_stream, " .. ");
569                 fprintf(i9ep->stderr_stream, "%s", buf + len - y);
570         } else {
571                 char scratch[1000];
572
573                 y = x - len;
574                 scratch[0] = '\r';
575                 strcpy(scratch + 1, buf);
576                 memset(scratch + 1 + len, ' ', y);
577                 scratch[1 + len + y] = '\r';
578                 scratch[2 + len + y] = '\0';
579                 fprintf(i9ep->stderr_stream, "\r%s", scratch);
580         }
581         i9ep->last_write_was_status = true;
582 }
583
584 /**
585  * Tell i9e that the caller received a signal.
586  *
587  * \param sig_num The number of the signal received.
588  */
589 void i9e_signal_dispatch(int sig_num)
590 {
591         if (sig_num == SIGWINCH)
592                 return update_winsize();
593         if (sig_num == SIGINT) {
594                 fprintf(i9ep->stderr_stream, "\n");
595                 rl_replace_line ("", false /* clear_undo */);
596                 reset_line_state();
597                 i9ep->caught_sigint = true;
598         }
599         if (sig_num == SIGTERM)
600                 i9ep->caught_sigterm = true;
601 }
602
603 /**
604  * Wrapper for select(2) which does not restart on interrupts.
605  *
606  * \param n \sa \ref para_select().
607  * \param readfds \sa \ref para_select().
608  * \param writefds \sa \ref para_select().
609  * \param timeout_tv \sa \ref para_select().
610  *
611  * \return \sa \ref para_select().
612  *
613  * The only difference between this function and \ref para_select() is that
614  * \ref i9e_select() returns zero if the select call returned \p EINTR.
615  */
616 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
617                 struct timeval *timeout_tv)
618 {
619         int ret = select(n, readfds, writefds, NULL, timeout_tv);
620
621         if (ret < 0) {
622                 if (errno == EINTR)
623                         ret = 0;
624                 else
625                         ret = -ERRNO_TO_PARA_ERROR(errno);
626         }
627         return ret;
628 }
629
630 /**
631  * Return the possible completions for a given word.
632  *
633  * \param word The word to complete.
634  * \param string_list All possible words in this context.
635  * \param result String list is returned here.
636  *
637  * This function never fails. If no completion was found, a string list of
638  * length zero is returned. In any case, the result must be freed by the caller
639  * using \ref free_argv().
640  *
641  * This function is independent of readline and may be called before
642  * i9e_open().
643  *
644  * \return The number of possible completions.
645  */
646 int i9e_extract_completions(const char *word, char **string_list,
647                 char ***result)
648 {
649         char **matches = para_malloc(sizeof(char *));
650         int match_count = 0, matches_len = 1;
651         char **p;
652         int len = strlen(word);
653
654         for (p = string_list; *p; p++) {
655                 if (!is_prefix(word, *p, len))
656                         continue;
657                 match_count++;
658                 if (match_count >= matches_len) {
659                         matches_len *= 2;
660                         matches = para_realloc(matches,
661                                 matches_len * sizeof(char *));
662                 }
663                 matches[match_count - 1] = para_strdup(*p);
664         }
665         matches[match_count] = NULL;
666         *result = matches;
667         return match_count;
668 }
669
670 /**
671  * Return the list of partially matching words.
672  *
673  * \param word The command to complete.
674  * \param completers The array containing all command names.
675  *
676  * This is similar to \ref i9e_extract_completions(), but completes on the
677  * command names in \a completers.
678  *
679  * \return See \ref i9e_extract_completions().
680  */
681 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
682 {
683         char **matches;
684         const char *cmd;
685         int i, match_count, len = strlen(word);
686
687         /*
688          * In contrast to completing against an arbitrary string list, here we
689          * know all possible completions and expect that there will not be many
690          * of them. So it should be OK to iterate twice over all commands which
691          * simplifies the code a bit.
692          */
693         for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
694                 if (is_prefix(word, cmd, len))
695                         match_count++;
696         }
697         matches = para_malloc((match_count + 1) * sizeof(*matches));
698         for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
699                 if (is_prefix(word, cmd, len))
700                         matches[match_count++] = para_strdup(cmd);
701         matches[match_count] = NULL;
702         return matches;
703 }
704
705 /**
706  * Complete according to the given options.
707  *
708  * \param opts All available options.
709  * \param ci Information which was passed to the completer.
710  * \param cr Result pointer.
711  *
712  * This convenience helper can be used to complete an option. The array of all
713  * possible options is passed as the first argument. Flags, i.e. options
714  * without an argument, are expected to be listed as strings of type "-X" in \a
715  * opts while options which require an argument should be passed with a
716  * trailing "=" character like "-X=".
717  *
718  * If the word can be uniquely completed to a flag option, an additional space
719  * character is appended to the output. For non-flag options no space character
720  * is appended.
721  */
722 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
723                 struct i9e_completion_result *cr)
724 {
725         int num_matches;
726
727         num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
728         if (num_matches == 1) {
729                 char *opt = cr->matches[0];
730                 char c = opt[strlen(opt) - 1];
731                 if (c == '=')
732                         cr->dont_append_space = true;
733         }
734 }
735
736 /**
737  * Print possible completions to stdout.
738  *
739  * \param completers The array of completion functions.
740  *
741  * At the end of the output a line starting with "-o=", followed by the
742  * (possibly empty) list of completion options is printed. Currently, the only
743  * two completion options are "nospace" and "filenames". The former indicates
744  * that no space should be appended even for a unique match while the latter
745  * indicates that usual filename completion should be performed in addition to
746  * the previously printed options.
747  *
748  * \return Standard.
749  */
750 int i9e_print_completions(struct i9e_completer *completers)
751 {
752         struct i9e_completion_result cr;
753         struct i9e_completion_info ci;
754         char *buf;
755         const char *end, *p;
756         int i, n, ret;
757
758         reset_completion_result(&cr);
759         buf = getenv("COMP_POINT");
760         ci.point = buf? atoi(buf) : 0;
761         ci.buffer = para_strdup(getenv("COMP_LINE"));
762
763         ci.argc = create_argv(ci.buffer, " ", &ci.argv);
764         ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
765
766         end = ci.buffer + ci.point;
767         for (p = end; p > ci.buffer && *p != ' '; p--)
768                 ; /* nothing */
769         if (*p == ' ')
770                 p++;
771
772         n = end - p + 1;
773         ci.word = para_malloc(n + 1);
774         strncpy(ci.word, p, n);
775         ci.word[n] = '\0';
776
777         PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
778                 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
779         if (ci.word_num == 0)
780                 cr.matches = i9e_complete_commands(ci.word, completers);
781         else
782                 create_matches(&ci, completers, &cr);
783         ret = 0;
784         if (cr.matches && cr.matches[0]) {
785                 for (i = 0; cr.matches[i]; i++)
786                         printf("%s\n", cr.matches[i]);
787                 ret = 1;
788         }
789         printf("-o=");
790         if (cr.dont_append_space)
791                 printf("nospace");
792         if (cr.filename_completion_desired)
793                 printf(",filenames");
794         printf("\n");
795         free_argv(cr.matches);
796         free_argv(ci.argv);
797         free(ci.buffer);
798         free(ci.word);
799         return ret;
800 }