]> git.tuebingen.mpg.de Git - paraslash.git/blob - interactive.c
Merge topic branch t/openssl-3 into pu
[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 i9e_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 void i9e_attach_to_stdout(struct btr_node *producer)
194 {
195         btr_remove_node(&i9ep->stdout_btrn);
196         i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
197                 EMBRACE(.name = "interactive_stdout", .parent = producer));
198         rl_set_keymap(i9ep->bare_km);
199 }
200
201 static void wipe_bottom_line(void)
202 {
203         fprintf(i9ep->stderr_stream, "\r%s\r", i9ep->empty_line);
204 }
205
206 #ifndef RL_FREE_KEYMAP_DECLARED
207 /**
208  * Free all storage associated with a keymap.
209  *
210  * This function is not declared in the readline headers although the symbol is
211  * exported and the function is documented in the readline info file. So we
212  * have to declare it here.
213  *
214  * \param keymap The keymap to deallocate.
215  */
216 void rl_free_keymap(Keymap keymap);
217 #endif
218
219 /**
220  * Reset the terminal and save the in-memory command line history.
221  *
222  * This should be called before the caller exits.
223  */
224 void i9e_close(void)
225 {
226         char *hf = i9ep->ici->history_file;
227
228         rl_free_keymap(i9ep->bare_km);
229         rl_callback_handler_remove();
230         if (hf)
231                 write_history(hf);
232         clear_history();
233         wipe_bottom_line();
234         fcntl(i9ep->ici->fds[0], F_SETFL, i9ep->fd_flags[0]);
235         fcntl(i9ep->ici->fds[1], F_SETFL, i9ep->fd_flags[1]);
236 }
237
238 static void clear_bottom_line(void)
239 {
240         int point;
241         char *text;
242
243         if (rl_point == 0 && rl_end == 0)
244                 return wipe_bottom_line();
245         /*
246          * We might have a multi-line input that needs to be wiped here, so the
247          * simple printf("\r<space>\r") is insufficient. To workaround this, we
248          * remove the whole line, redisplay and restore the killed text.
249          */
250         point = rl_point;
251         text = rl_copy_text(0, rl_end);
252         rl_kill_full_line(0, 0);
253         rl_redisplay();
254         wipe_bottom_line(); /* wipe out the prompt */
255         rl_insert_text(text);
256         free(text);
257         rl_point = point;
258 }
259
260 static void i9e_line_handler(char *line)
261 {
262         int ret;
263         struct btr_node *dummy;
264
265         if (!line) {
266                 i9ep->input_eof = true;
267                 return;
268         }
269         if (!*line)
270                 goto free_line;
271         rl_set_prompt("");
272         dummy = btr_new_node(&(struct btr_node_description)
273                 EMBRACE(.name = "dummy line handler"));
274         i9e_attach_to_stdout(dummy);
275         ret = i9ep->ici->line_handler(line);
276         if (ret < 0)
277                 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
278         add_history(line);
279         btr_remove_node(&dummy);
280 free_line:
281         free(line);
282 }
283
284 static int i9e_post_monitor(__a_unused struct sched *s, __a_unused void *context)
285 {
286         int ret;
287         struct i9e_client_info *ici = i9ep->ici;
288         char *buf;
289         size_t sz, consumed = 0;
290
291         ret = -E_EOF;
292         if (i9ep->input_eof)
293                 goto rm_btrn;
294         ret = -E_I9E_TERM_RQ;
295         if (i9ep->caught_sigterm)
296                 goto rm_btrn;
297         ret = 0;
298         if (i9ep->caught_sigint)
299                 goto rm_btrn;
300         while (read_ok(i9ep->ici->fds[0]) > 0) {
301                 if (i9ep->stdout_btrn) {
302                         while (i9ep->key_sequence_length < sizeof(i9ep->key_sequence) - 1) {
303                                 buf = i9ep->key_sequence + i9ep->key_sequence_length;
304                                 ret = read(i9ep->ici->fds[0], buf, 1);
305                                 if (ret < 0) {
306                                         ret = -ERRNO_TO_PARA_ERROR(errno);
307                                         goto rm_btrn;
308                                 }
309                                 if (ret == 0) {
310                                         ret = -E_EOF;
311                                         goto rm_btrn;
312                                 }
313                                 buf[1] = '\0';
314                                 i9ep->key_sequence_length++;
315                                 rl_stuff_char((int)(unsigned char)*buf);
316                                 rl_callback_read_char();
317                                 if (read_ok(i9ep->ici->fds[0]) <= 0)
318                                         break;
319                         }
320                         i9ep->key_sequence_length = 0;
321                 } else
322                         rl_callback_read_char();
323                 ret = 0;
324         }
325         if (!i9ep->stdout_btrn)
326                 goto out;
327         ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
328         if (ret < 0) {
329                 ret = 0;
330                 goto rm_btrn;
331         }
332         if (ret == 0)
333                 goto out;
334 again:
335         sz = btr_next_buffer(i9ep->stdout_btrn, &buf);
336         if (sz == 0)
337                 goto out;
338         if (i9ep->last_write_was_status)
339                 fprintf(i9ep->stderr_stream, "\n");
340         i9ep->last_write_was_status = false;
341         ret = xwrite(ici->fds[1], buf, sz);
342         if (ret < 0)
343                 goto rm_btrn;
344         btr_consume(i9ep->stdout_btrn, ret);
345         consumed += ret;
346         if (ret == sz && consumed < 10000)
347                 goto again;
348         goto out;
349 rm_btrn:
350         if (i9ep->stdout_btrn) {
351                 wipe_bottom_line();
352                 btr_remove_node(&i9ep->stdout_btrn);
353                 rl_set_keymap(i9ep->standard_km);
354                 rl_set_prompt(i9ep->ici->prompt);
355                 rl_redisplay();
356         }
357         if (ret < 0)
358                 wipe_bottom_line();
359 out:
360         i9ep->caught_sigint = false;
361         return ret;
362 }
363
364 static void i9e_pre_monitor(struct sched *s, __a_unused void *context)
365 {
366         int ret;
367
368         if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
369                 sched_min_delay(s);
370                 return;
371         }
372         if (i9ep->stdout_btrn) {
373                 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
374                 if (ret < 0) {
375                         sched_min_delay(s);
376                         return;
377                 }
378                 if (ret > 0)
379                         sched_monitor_writefd(i9ep->ici->fds[1], s);
380         }
381         /*
382          * fd[0] might have been reset to blocking mode if our job was moved to
383          * the background due to CTRL-Z or SIGSTOP, so set the fd back to
384          * nonblocking mode.
385          */
386         ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
387         if (ret < 0)
388                 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
389                         i9ep->ici->fds[0], para_strerror(-ret));
390         sched_monitor_readfd(i9ep->ici->fds[0], s);
391 }
392
393 static void update_winsize(void)
394 {
395         struct winsize w;
396         int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
397
398         if (ret >= 0) {
399                 assert(w.ws_col < sizeof(i9ep->empty_line));
400                 i9ep->num_columns = w.ws_col;
401         } else
402                 i9ep->num_columns = 80;
403
404         memset(i9ep->empty_line, ' ', i9ep->num_columns);
405         i9ep->empty_line[i9ep->num_columns] = '\0';
406 }
407
408 static int dispatch_key(__a_unused int count, __a_unused int key)
409 {
410         int i, ret;
411
412 again:
413         if (i9ep->key_sequence_length == 0)
414                 return 0;
415         for (i = i9ep->num_key_bindings - 1; i >= 0; i--) {
416                 if (strcmp(i9ep->key_sequence, i9ep->ici->bound_keyseqs[i]))
417                         continue;
418                 i9ep->key_sequence[0] = '\0';
419                 i9ep->key_sequence_length = 0;
420                 ret = i9ep->ici->key_handler(i);
421                 return ret < 0? ret : 0;
422         }
423         PARA_WARNING_LOG("ignoring key %d\n", i9ep->key_sequence[0]);
424         /*
425          * We received an undefined key sequence. Throw away the first byte,
426          * and try to parse the remainder.
427          */
428         memmove(i9ep->key_sequence, i9ep->key_sequence + 1,
429                 i9ep->key_sequence_length); /* move also terminating zero byte */
430         i9ep->key_sequence_length--;
431         goto again;
432 }
433
434 /**
435  * Register the i9e task and initialize readline.
436  *
437  * \param ici The i9e configuration parameters set by the caller.
438  * \param s The scheduler instance to add the i9e task to.
439  *
440  * The caller must allocate and initialize the structure \a ici points to.
441  *
442  * \return Standard.
443  */
444 int i9e_open(struct i9e_client_info *ici, struct sched *s)
445 {
446         int ret;
447
448         memset(i9ep, 0, sizeof(struct i9e_private));
449         if (!isatty(ici->fds[0]))
450                 return -E_I9E_SETUPTERM;
451         ret = fcntl(ici->fds[0], F_GETFL);
452         if (ret < 0)
453                 return -E_I9E_SETUPTERM;
454         i9ep->fd_flags[0] = ret;
455         ret = fcntl(ici->fds[1], F_GETFL);
456         if (ret < 0)
457                 return -E_I9E_SETUPTERM;
458         i9ep->fd_flags[1] = ret;
459         ret = mark_fd_nonblocking(ici->fds[0]);
460         if (ret < 0)
461                 return ret;
462         ret = mark_fd_nonblocking(ici->fds[1]);
463         if (ret < 0)
464                 return ret;
465         i9ep->task = task_register(&(struct task_info) {
466                 .name = "i9e",
467                 .pre_monitor = i9e_pre_monitor,
468                 .post_monitor = i9e_post_monitor,
469                 .context = i9ep,
470         }, s);
471
472         rl_readline_name = "para_i9e";
473         rl_basic_word_break_characters = " ";
474         rl_attempted_completion_function = i9e_completer;
475         i9ep->ici = ici;
476         i9ep->stderr_stream = fdopen(ici->fds[2], "w");
477         setvbuf(i9ep->stderr_stream, NULL, _IONBF, 0);
478
479         i9ep->standard_km = rl_get_keymap();
480         i9ep->bare_km = rl_make_bare_keymap();
481         if (ici->bound_keyseqs) {
482                 char *seq;
483                 int i;
484                 /* bind each key sequence to our dispatcher */
485                 for (i = 0; (seq = ici->bound_keyseqs[i]); i++) {
486                         if (strlen(seq) >= sizeof(i9ep->key_sequence) - 1) {
487                                 PARA_WARNING_LOG("ignoring overlong key %s\n",
488                                         seq);
489                                 continue;
490                         }
491                         if (rl_bind_keyseq_in_map(seq,
492                                         dispatch_key, i9ep->bare_km) != 0)
493                                 PARA_WARNING_LOG("could not bind #%d: %s\n", i, seq);
494                 }
495                 i9ep->num_key_bindings = i;
496         }
497         if (ici->history_file)
498                 read_history(ici->history_file);
499         update_winsize();
500         if (ici->producer) {
501                 rl_callback_handler_install("", i9e_line_handler);
502                 i9e_attach_to_stdout(ici->producer);
503         } else
504                 rl_callback_handler_install(i9ep->ici->prompt, i9e_line_handler);
505         return 1;
506 }
507
508 static void reset_line_state(void)
509 {
510         if (i9ep->stdout_btrn)
511                 return;
512         rl_on_new_line();
513         rl_reset_line_state();
514         rl_forced_update_display();
515 }
516
517 /**
518  * The log function of the i9e subsystem.
519  *
520  * \param ll Severity log level.
521  * \param fmt Printf-like format string.
522  *
523  * This clears the bottom line of the terminal if necessary and writes the
524  * string given by \a fmt to fd[2], where fd[] is the array provided earlier in
525  * \ref i9e_open().
526  */
527 __printf_2_3 void i9e_log(int ll, const char* fmt,...)
528 {
529         va_list argp;
530
531         if (ll < i9ep->ici->loglevel)
532                 return;
533         clear_bottom_line();
534         va_start(argp, fmt);
535         vfprintf(i9ep->stderr_stream, fmt, argp);
536         va_end(argp);
537         reset_line_state();
538         i9ep->last_write_was_status = false;
539 }
540
541 /**
542  * Print the current status to stderr.
543  *
544  * \param buf The text to print.
545  * \param len The number of bytes in \a buf.
546  *
547  * This clears the bottom line, moves to the beginning of the line and prints
548  * the given text. If the length of this text exceeds the width of the
549  * terminal, the text is shortened by leaving out a part in the middle.
550  */
551 void i9e_print_status_bar(char *buf, unsigned len)
552 {
553         size_t x = i9ep->num_columns, y = (x - 4) / 2;
554
555         assert(x >= 6);
556         if (len > x) {
557                 buf[y] = '\0';
558                 fprintf(i9ep->stderr_stream, "\r%s", buf);
559                 fprintf(i9ep->stderr_stream, " .. ");
560                 fprintf(i9ep->stderr_stream, "%s", buf + len - y);
561         } else {
562                 char scratch[1000];
563
564                 y = x - len;
565                 scratch[0] = '\r';
566                 strcpy(scratch + 1, buf);
567                 memset(scratch + 1 + len, ' ', y);
568                 scratch[1 + len + y] = '\r';
569                 scratch[2 + len + y] = '\0';
570                 fprintf(i9ep->stderr_stream, "\r%s", scratch);
571         }
572         i9ep->last_write_was_status = true;
573 }
574
575 /**
576  * Tell i9e that the caller received a signal.
577  *
578  * \param sig_num The number of the signal received.
579  */
580 void i9e_signal_dispatch(int sig_num)
581 {
582         if (sig_num == SIGWINCH)
583                 return update_winsize();
584         if (sig_num == SIGINT) {
585                 fprintf(i9ep->stderr_stream, "\n");
586                 rl_replace_line ("", false /* clear_undo */);
587                 reset_line_state();
588                 i9ep->caught_sigint = true;
589         }
590         if (sig_num == SIGTERM)
591                 i9ep->caught_sigterm = true;
592 }
593
594 /**
595  * Wrapper for poll(2) which handles EINTR and returns paraslash error codes.
596  *
597  * \param fds See poll(2).
598  * \param nfds See poll(2).
599  * \param timeout See poll(2).
600  *
601  * \return See poll(2).
602  *
603  * The only difference between this function and \ref xpoll() is that \ref
604  * i9e_poll() returns zero if the system call was interrupted while xpoll()
605  * restarts the system call in this case.
606  */
607 int i9e_poll(struct pollfd *fds, nfds_t nfds, int timeout)
608 {
609         int ret = poll(fds, nfds, timeout);
610         if (ret < 0) {
611                 if (errno == EINTR)
612                         ret = 0;
613                 else
614                         ret = -ERRNO_TO_PARA_ERROR(errno);
615         }
616         return ret;
617 }
618
619 /**
620  * Return the possible completions for a given word.
621  *
622  * \param word The word to complete.
623  * \param string_list All possible words in this context.
624  * \param result String list is returned here.
625  *
626  * This function never fails. If no completion was found, a string list of
627  * length zero is returned. In any case, the result must be freed by the caller
628  * using \ref free_argv().
629  *
630  * This function is independent of readline and may be called before
631  * i9e_open().
632  *
633  * \return The number of possible completions.
634  */
635 int i9e_extract_completions(const char *word, char **string_list,
636                 char ***result)
637 {
638         char **matches = alloc(sizeof(char *));
639         int match_count = 0, matches_len = 1;
640         char **p;
641         int len = strlen(word);
642
643         for (p = string_list; *p; p++) {
644                 if (!is_prefix(word, *p, len))
645                         continue;
646                 match_count++;
647                 if (match_count >= matches_len) {
648                         matches_len *= 2;
649                         matches = arr_realloc(matches, matches_len,
650                                 sizeof(char *));
651                 }
652                 matches[match_count - 1] = para_strdup(*p);
653         }
654         matches[match_count] = NULL;
655         *result = matches;
656         return match_count;
657 }
658
659 /**
660  * Return the list of partially matching words.
661  *
662  * \param word The command to complete.
663  * \param completers The array containing all command names.
664  *
665  * This is similar to \ref i9e_extract_completions(), but completes on the
666  * command names in \a completers.
667  *
668  * \return See \ref i9e_extract_completions().
669  */
670 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
671 {
672         char **matches;
673         const char *cmd;
674         int i, match_count, len = strlen(word);
675
676         /*
677          * In contrast to completing against an arbitrary string list, here we
678          * know all possible completions and expect that there will not be many
679          * of them. So it should be OK to iterate twice over all commands which
680          * simplifies the code a bit.
681          */
682         for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
683                 if (is_prefix(word, cmd, len))
684                         match_count++;
685         }
686         matches = arr_alloc(match_count + 1, sizeof(*matches));
687         for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
688                 if (is_prefix(word, cmd, len))
689                         matches[match_count++] = para_strdup(cmd);
690         matches[match_count] = NULL;
691         return matches;
692 }
693
694 /**
695  * Complete according to the given options.
696  *
697  * \param opts All available options.
698  * \param ci Information which was passed to the completer.
699  * \param cr Result pointer.
700  *
701  * This convenience helper can be used to complete an option. The array of all
702  * possible options is passed as the first argument. Flags, i.e. options
703  * without an argument, are expected to be listed as strings of type "-X" in \a
704  * opts while options which require an argument should be passed with a
705  * trailing "=" character like "-X=".
706  *
707  * If the word can be uniquely completed to a flag option, an additional space
708  * character is appended to the output. For non-flag options no space character
709  * is appended.
710  */
711 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
712                 struct i9e_completion_result *cr)
713 {
714         int num_matches;
715
716         num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
717         if (num_matches == 1) {
718                 char *opt = cr->matches[0];
719                 char c = opt[strlen(opt) - 1];
720                 if (c == '=')
721                         cr->dont_append_space = true;
722         }
723 }
724
725 /**
726  * Print possible completions to stdout.
727  *
728  * \param completers The array of completion functions.
729  *
730  * At the end of the output a line starting with "-o=", followed by the
731  * (possibly empty) list of completion options is printed. Currently, the only
732  * two completion options are "nospace" and "filenames". The former indicates
733  * that no space should be appended even for a unique match while the latter
734  * indicates that usual filename completion should be performed in addition to
735  * the previously printed options.
736  *
737  * \return Standard.
738  */
739 int i9e_print_completions(struct i9e_completer *completers)
740 {
741         struct i9e_completion_result cr;
742         struct i9e_completion_info ci;
743         char *buf;
744         const char *end, *p;
745         int i, n, ret;
746
747         reset_completion_result(&cr);
748         buf = getenv("COMP_POINT");
749         ci.point = buf? atoi(buf) : 0;
750         ci.buffer = para_strdup(getenv("COMP_LINE"));
751
752         ci.argc = create_argv(ci.buffer, " ", &ci.argv);
753         ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
754
755         /* determine the current word to complete */
756         end = ci.buffer + ci.point;
757
758         if (*end == ' ') {
759                 if (ci.point == 0 || ci.buffer[ci.point - 1] == ' ') {
760                         ci.word = para_strdup(NULL);
761                         goto create_matches;
762                 } else /* The cursor is positioned right after a word */
763                         end--;
764         }
765         for (p = end; p > ci.buffer && *p != ' '; p--)
766                 ; /* nothing */
767         if (*p == ' ')
768                 p++;
769         n = end - p + 1;
770         ci.word = alloc(n + 1);
771         strncpy(ci.word, p, n);
772         ci.word[n] = '\0';
773 create_matches:
774         PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
775                 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
776         if (ci.word_num == 0)
777                 cr.matches = i9e_complete_commands(ci.word, completers);
778         else
779                 create_matches(&ci, completers, &cr);
780         ret = 0;
781         if (cr.matches && cr.matches[0]) {
782                 for (i = 0; cr.matches[i]; i++)
783                         printf("%s\n", cr.matches[i]);
784                 ret = 1;
785         }
786         printf("-o=");
787         if (cr.dont_append_space)
788                 printf("nospace");
789         if (cr.filename_completion_desired)
790                 printf(",filenames");
791         printf("\n");
792         free_argv(cr.matches);
793         free_argv(ci.argv);
794         free(ci.buffer);
795         free(ci.word);
796         return ret;
797 }
798
799 /**
800  * Complete on severity strings.
801  *
802  * \param ci See struct \ref i9e_completer.
803  * \param cr See struct \ref i9e_completer.
804  *
805  * This is used by para_client and para_audioc which need the same completion
806  * primitive for the ll server/audiod command. Both define their own completer
807  * which is implemented as a trivial wrapper that calls this function.
808  */
809 void i9e_ll_completer(struct i9e_completion_info *ci,
810                 struct i9e_completion_result *cr)
811 {
812         char *sev[] = {SEVERITIES, NULL};
813
814         if (ci->word_num != 1) {
815                 cr->matches = NULL;
816                 return;
817         }
818         i9e_extract_completions(ci->word, sev, &cr->matches);
819 }