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