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