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