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