Drop support for Mac OS.
[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 };
42 static struct i9e_private i9e_private, *i9ep = &i9e_private;
43
44 /**
45  * Return the error state of the i9e task.
46  *
47  * This is mainly useful for other tasks to tell whether the i9e task is still
48  * running.
49  *
50  * \return A negative return value of zero means the i9e task terminated. Only
51  * in this case it is safe to call ie9_close().
52  */
53 int i9e_get_error(void)
54 {
55         return task_status(i9ep->task);
56 }
57
58 static bool is_prefix(const char *partial, const char *full, size_t len)
59 {
60         if (len == 0)
61                 len = strlen(partial);
62         return !strncmp(partial, full, len);
63 }
64
65 /*
66  * Generator function for command completion. STATE lets us know whether
67  * to start from scratch; without any state (i.e. STATE == 0), then we
68  * start at the top of the list.
69  */
70 static char *command_generator(const char *text, int state)
71 {
72         static int list_index, len;
73         const char *name;
74         struct i9e_client_info *ici = i9ep->ici;
75
76         rl_attempted_completion_over = 1; /* disable filename completion */
77         /*
78          * If this is a new word to complete, initialize now. This includes
79          * saving the length of TEXT for efficiency, and initializing the index
80          * variable to 0.
81          */
82         if (state == 0) {
83                 list_index = 0;
84                 len = strlen(text);
85         }
86         /* Return the next name which partially matches from the command list. */
87         while ((name = ici->completers[list_index].name)) {
88                 list_index++;
89                 if (is_prefix(text, name, len))
90                         return para_strdup(name);
91         }
92         return NULL; /* no names matched */
93 }
94
95 static void reset_completion_result(struct i9e_completion_result *cr)
96 {
97         cr->dont_append_space = false;
98         cr->filename_completion_desired = false;
99         cr->matches = NULL;
100 }
101
102 static void create_matches(struct i9e_completion_info *ci,
103                 struct i9e_completer *completers,
104                 struct i9e_completion_result *cr)
105 {
106         int i, ret;
107
108         reset_completion_result(cr);
109
110         ret = create_argv(ci->buffer, " ", &ci->argv);
111         if (ret < 0 || !ci->argv[0])
112                 return;
113
114         ci->argc = ret;
115         ci->word_num = compute_word_num(ci->buffer, " ", ci->point);
116         for (i = 0; completers[i].name; i++) {
117                 if (strcmp(completers[i].name, ci->argv[0]) != 0)
118                         continue;
119                 completers[i].completer(ci, cr);
120                 break;
121         }
122         PARA_DEBUG_LOG("current word: %d (%s)\n", ci->word_num,
123                 ci->argv[ci->word_num]);
124         if (cr->matches)
125                 for (i = 0; cr->matches[i]; i++)
126                         PARA_DEBUG_LOG("match %d: %s\n", i, cr->matches[i]);
127 }
128
129 static char *completion_generator(const char *word, int state)
130 {
131         static int list_index;
132         static char **argv, **matches;
133         struct i9e_completer *completers = i9ep->ici->completers;
134         struct i9e_completion_info ci = {
135                 .word = (char *)word,
136                 .point = rl_point,
137                 .buffer = rl_line_buffer,
138         };
139         struct i9e_completion_result cr = {.matches = NULL};
140
141         if (state != 0)
142                 goto out;
143         /* clean up previous matches and set defaults */
144         free(matches);
145         matches = NULL;
146         free_argv(argv);
147         argv = NULL;
148         list_index = 0;
149         rl_completion_append_character = ' ';
150         rl_completion_suppress_append = false;
151         rl_attempted_completion_over = true;
152
153         create_matches(&ci, completers, &cr);
154
155         matches = cr.matches;
156         argv = ci.argv;
157         rl_completion_suppress_append = cr.dont_append_space;
158         rl_attempted_completion_over = !cr.filename_completion_desired;
159 out:
160         if (!matches)
161                 return NULL;
162         return matches[list_index++];
163 }
164
165 /*
166  * Attempt to complete on the contents of TEXT. START and END bound the
167  * region of rl_line_buffer that contains the word to complete.  TEXT is
168  * the word to complete.  We can use the entire contents of rl_line_buffer
169  * in case we want to do some simple parsing. Return the array of matches,
170  * or NULL if there aren't any.
171  */
172 static char **i9e_completer(const char *text, int start, __a_unused int end)
173 {
174         struct i9e_client_info *ici = i9ep->ici;
175
176         if (!ici->completers)
177                 return NULL;
178         /* Complete on command names if this is the first word in the line. */
179         if (start == 0)
180                 return rl_completion_matches(text, command_generator);
181         return rl_completion_matches(text, completion_generator);
182 }
183
184 /**
185  * Prepare writing to stdout.
186  *
187  * \param producer The buffer tree node which produces output.
188  *
189  * The i9e subsystem maintains a buffer tree node which may be attached to
190  * another node which generates output (a "producer"). When attached, the i9e
191  * buffer tree node copies the buffers generated by the producer to stdout.
192  *
193  * This function attaches the i9e input queue to an output queue of \a
194  * producer.
195  *
196  * \return Standard.
197  */
198 void i9e_attach_to_stdout(struct btr_node *producer)
199 {
200         btr_remove_node(&i9ep->stdout_btrn);
201         i9ep->stdout_btrn = btr_new_node(&(struct btr_node_description)
202                 EMBRACE(.name = "interactive_stdout", .parent = producer));
203         rl_set_keymap(i9ep->bare_km);
204 }
205
206 static void wipe_bottom_line(void)
207 {
208         fprintf(i9ep->stderr_stream, "\r%s\r", i9ep->empty_line);
209 }
210
211 #ifndef RL_FREE_KEYMAP_DECLARED
212 /**
213  * Free all storage associated with a keymap.
214  *
215  * This function is not declared in the readline headers although the symbol is
216  * exported and the function is documented in the readline info file. So we
217  * have to declare it here.
218  *
219  * \param keymap The keymap to deallocate.
220  */
221 void rl_free_keymap(Keymap keymap);
222 #endif
223
224 /**
225  * Reset the terminal and save the in-memory command line history.
226  *
227  * This should be called before the caller exits.
228  */
229 void i9e_close(void)
230 {
231         char *hf = i9ep->ici->history_file;
232
233         rl_free_keymap(i9ep->bare_km);
234         rl_callback_handler_remove();
235         if (hf)
236                 write_history(hf);
237         wipe_bottom_line();
238 }
239
240 static void clear_bottom_line(void)
241 {
242         int point;
243         char *text;
244
245         if (rl_point == 0 && rl_end == 0)
246                 return wipe_bottom_line();
247         /*
248          * We might have a multi-line input that needs to be wiped here, so the
249          * simple printf("\r<space>\r") is insufficient. To workaround this, we
250          * remove the whole line, redisplay and restore the killed text.
251          */
252         point = rl_point;
253         text = rl_copy_text(0, rl_end);
254         rl_kill_full_line(0, 0);
255         rl_redisplay();
256         wipe_bottom_line(); /* wipe out the prompt */
257         rl_insert_text(text);
258         free(text);
259         rl_point = point;
260 }
261
262 static bool input_available(void)
263 {
264         fd_set rfds;
265         struct timeval tv = {0, 0};
266         int ret;
267
268         FD_ZERO(&rfds);
269         FD_SET(i9ep->ici->fds[0], &rfds);
270         ret = para_select(1, &rfds, NULL, &tv);
271         return ret > 0;
272 }
273
274 static void i9e_line_handler(char *line)
275 {
276         int ret;
277         struct btr_node *dummy;
278
279         if (!line) {
280                 i9ep->input_eof = true;
281                 return;
282         }
283         if (!*line)
284                 goto free_line;
285         rl_set_prompt("");
286         dummy = btr_new_node(&(struct btr_node_description)
287                 EMBRACE(.name = "dummy line handler"));
288         i9e_attach_to_stdout(dummy);
289         ret = i9ep->ici->line_handler(line);
290         if (ret < 0)
291                 PARA_WARNING_LOG("%s\n", para_strerror(-ret));
292         add_history(line);
293         btr_remove_node(&dummy);
294 free_line:
295         free(line);
296 }
297
298 static int i9e_post_select(__a_unused struct sched *s, __a_unused void *context)
299 {
300         int ret;
301         struct i9e_client_info *ici = i9ep->ici;
302         char *buf;
303         size_t sz, consumed = 0;
304
305         ret = -E_I9E_EOF;
306         if (i9ep->input_eof)
307                 goto rm_btrn;
308         ret = -E_I9E_TERM_RQ;
309         if (i9ep->caught_sigterm)
310                 goto rm_btrn;
311         ret = 0;
312         if (i9ep->caught_sigint)
313                 goto rm_btrn;
314         while (input_available()) {
315                 if (i9ep->stdout_btrn) {
316                         unsigned len = i9ep->key_sequence_length;
317                         assert(len < sizeof(i9ep->key_sequence) - 1);
318                         buf = i9ep->key_sequence + len;
319                         ret = read(i9ep->ici->fds[0], buf, 1);
320                         if (ret < 0) {
321                                 ret = -ERRNO_TO_PARA_ERROR(errno);
322                                 goto rm_btrn;
323                         }
324                         ret = -E_I9E_EOF;
325                         if (ret == 0)
326                                 goto rm_btrn;
327                         buf[1] = '\0';
328                         i9ep->key_sequence_length++;
329                         rl_stuff_char((int)(unsigned char)*buf);
330                 }
331                 rl_callback_read_char();
332                 ret = 0;
333         }
334         if (!i9ep->stdout_btrn)
335                 goto out;
336         ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
337         if (ret < 0) {
338                 ret = 0;
339                 goto rm_btrn;
340         }
341         if (ret == 0)
342                 goto out;
343 again:
344         sz = btr_next_buffer(i9ep->stdout_btrn, &buf);
345         if (sz == 0)
346                 goto out;
347         if (i9ep->last_write_was_status)
348                 fprintf(i9ep->stderr_stream, "\n");
349         i9ep->last_write_was_status = false;
350         ret = xwrite(ici->fds[1], buf, sz);
351         if (ret < 0)
352                 goto rm_btrn;
353         btr_consume(i9ep->stdout_btrn, ret);
354         consumed += ret;
355         if (ret == sz && consumed < 10000)
356                 goto again;
357         goto out;
358 rm_btrn:
359         if (i9ep->stdout_btrn) {
360                 wipe_bottom_line();
361                 btr_remove_node(&i9ep->stdout_btrn);
362                 rl_set_keymap(i9ep->standard_km);
363                 rl_set_prompt(i9ep->ici->prompt);
364                 rl_redisplay();
365         }
366         if (ret < 0)
367                 wipe_bottom_line();
368 out:
369         i9ep->caught_sigint = false;
370         return ret;
371 }
372
373 static void i9e_pre_select(struct sched *s, __a_unused void *context)
374 {
375         int ret;
376
377         if (i9ep->input_eof || i9ep->caught_sigint || i9ep->caught_sigterm) {
378                 sched_min_delay(s);
379                 return;
380         }
381         if (i9ep->stdout_btrn) {
382                 ret = btr_node_status(i9ep->stdout_btrn, 0, BTR_NT_LEAF);
383                 if (ret < 0) {
384                         sched_min_delay(s);
385                         return;
386                 }
387                 if (ret > 0)
388                         para_fd_set(i9ep->ici->fds[1], &s->wfds, &s->max_fileno);
389         }
390         /*
391          * fd[0] might have been reset to blocking mode if our job was moved to
392          * the background due to CTRL-Z or SIGSTOP, so set the fd back to
393          * nonblocking mode.
394          */
395         ret = mark_fd_nonblocking(i9ep->ici->fds[0]);
396         if (ret < 0)
397                 PARA_WARNING_LOG("set to nonblock failed: (fd0 %d, %s)\n",
398                         i9ep->ici->fds[0], para_strerror(-ret));
399         para_fd_set(i9ep->ici->fds[0], &s->rfds, &s->max_fileno);
400 }
401
402 static void update_winsize(void)
403 {
404         struct winsize w;
405         int ret = ioctl(i9ep->ici->fds[2], TIOCGWINSZ, (char *)&w);
406
407         if (ret >= 0) {
408                 assert(w.ws_col < sizeof(i9ep->empty_line));
409                 i9ep->num_columns = w.ws_col;
410         } else
411                 i9ep->num_columns = 80;
412
413         memset(i9ep->empty_line, ' ', i9ep->num_columns);
414         i9ep->empty_line[i9ep->num_columns] = '\0';
415 }
416
417 static int dispatch_key(__a_unused int count, __a_unused int key)
418 {
419         int i, ret;
420
421 again:
422         if (i9ep->key_sequence_length == 0)
423                 return 0;
424         for (i = i9ep->num_key_bindings - 1; i >= 0; i--) {
425                 if (strcmp(i9ep->key_sequence, i9ep->ici->bound_keyseqs[i]))
426                         continue;
427                 i9ep->key_sequence[0] = '\0';
428                 i9ep->key_sequence_length = 0;
429                 ret = i9ep->ici->key_handler(i);
430                 return ret < 0? ret : 0;
431         }
432         PARA_WARNING_LOG("ignoring key %d\n", i9ep->key_sequence[0]);
433         /*
434          * We received an undefined key sequence. Throw away the first byte,
435          * and try to parse the remainder.
436          */
437         memmove(i9ep->key_sequence, i9ep->key_sequence + 1,
438                 i9ep->key_sequence_length); /* move also terminating zero byte */
439         i9ep->key_sequence_length--;
440         goto again;
441 }
442
443 /**
444  * Register the i9e task and initialize readline.
445  *
446  * \param ici The i9e configuration parameters set by the caller.
447  * \param s The scheduler instance to add the i9e task to.
448  *
449  * The caller must allocate and initialize the structure \a ici points to.
450  *
451  * \return Standard.
452  */
453 int i9e_open(struct i9e_client_info *ici, struct sched *s)
454 {
455         int ret;
456
457         memset(i9ep, 0, sizeof(struct i9e_private));
458         if (!isatty(ici->fds[0]))
459                 return -E_I9E_SETUPTERM;
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_select = i9e_pre_select,
469                 .post_select = i9e_post_select,
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 ie9_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 select(2) which does not restart on interrupts.
597  *
598  * \param n \sa \ref para_select().
599  * \param readfds \sa \ref para_select().
600  * \param writefds \sa \ref para_select().
601  * \param timeout_tv \sa \ref para_select().
602  *
603  * \return \sa \ref para_select().
604  *
605  * The only difference between this function and \ref para_select() is that
606  * \ref i9e_select() returns zero if the select call returned \p EINTR.
607  */
608 int i9e_select(int n, fd_set *readfds, fd_set *writefds,
609                 struct timeval *timeout_tv)
610 {
611         int ret = select(n, readfds, writefds, NULL, timeout_tv);
612
613         if (ret < 0) {
614                 if (errno == EINTR)
615                         ret = 0;
616                 else
617                         ret = -ERRNO_TO_PARA_ERROR(errno);
618         }
619         return ret;
620 }
621
622 /**
623  * Return the possible completions for a given word.
624  *
625  * \param word The word to complete.
626  * \param string_list All possible words in this context.
627  * \param result String list is returned here.
628  *
629  * This function never fails. If no completion was found, a string list of
630  * length zero is returned. In any case, the result must be freed by the caller
631  * using \ref free_argv().
632  *
633  * This function is independent of readline and may be called before
634  * i9e_open().
635  *
636  * \return The number of possible completions.
637  */
638 int i9e_extract_completions(const char *word, char **string_list,
639                 char ***result)
640 {
641         char **matches = para_malloc(sizeof(char *));
642         int match_count = 0, matches_len = 1;
643         char **p;
644         int len = strlen(word);
645
646         for (p = string_list; *p; p++) {
647                 if (!is_prefix(word, *p, len))
648                         continue;
649                 match_count++;
650                 if (match_count >= matches_len) {
651                         matches_len *= 2;
652                         matches = para_realloc(matches,
653                                 matches_len * sizeof(char *));
654                 }
655                 matches[match_count - 1] = para_strdup(*p);
656         }
657         matches[match_count] = NULL;
658         *result = matches;
659         return match_count;
660 }
661
662 /**
663  * Return the list of partially matching words.
664  *
665  * \param word The command to complete.
666  * \param completers The array containing all command names.
667  *
668  * This is similar to \ref i9e_extract_completions(), but completes on the
669  * command names in \a completers.
670  *
671  * \return See \ref i9e_extract_completions().
672  */
673 char **i9e_complete_commands(const char *word, struct i9e_completer *completers)
674 {
675         char **matches;
676         const char *cmd;
677         int i, match_count, len = strlen(word);
678
679         /*
680          * In contrast to completing against an arbitrary string list, here we
681          * know all possible completions and expect that there will not be many
682          * of them. So it should be OK to iterate twice over all commands which
683          * simplifies the code a bit.
684          */
685         for (i = 0, match_count = 0; (cmd = completers[i].name); i++) {
686                 if (is_prefix(word, cmd, len))
687                         match_count++;
688         }
689         matches = para_malloc((match_count + 1) * sizeof(*matches));
690         for (i = 0, match_count = 0; (cmd = completers[i].name); i++)
691                 if (is_prefix(word, cmd, len))
692                         matches[match_count++] = para_strdup(cmd);
693         matches[match_count] = NULL;
694         return matches;
695 }
696
697 /**
698  * Complete according to the given options.
699  *
700  * \param opts All available options.
701  * \param ci Information which was passed to the completer.
702  * \param cr Result pointer.
703  *
704  * This convenience helper can be used to complete an option. The array of all
705  * possible options is passed as the first argument. Flags, i.e. options
706  * without an argument, are expected to be listed as strings of type "-X" in \a
707  * opts while options which require an argument should be passed with a
708  * trailing "=" character like "-X=".
709  *
710  * If the word can be uniquely completed to a flag option, an additional space
711  * character is appended to the output. For non-flag options no space character
712  * is appended.
713  */
714 void i9e_complete_option(char **opts, struct i9e_completion_info *ci,
715                 struct i9e_completion_result *cr)
716 {
717         int num_matches;
718
719         num_matches = i9e_extract_completions(ci->word, opts, &cr->matches);
720         if (num_matches == 1) {
721                 char *opt = cr->matches[0];
722                 char c = opt[strlen(opt) - 1];
723                 if (c == '=')
724                         cr->dont_append_space = true;
725         }
726 }
727
728 /**
729  * Print possible completions to stdout.
730  *
731  * \param completers The array of completion functions.
732  *
733  * At the end of the output a line starting with "-o=", followed by the
734  * (possibly empty) list of completion options is printed. Currently, the only
735  * two completion options are "nospace" and "filenames". The former indicates
736  * that no space should be appended even for a unique match while the latter
737  * indicates that usual filename completion should be performed in addition to
738  * the previously printed options.
739  *
740  * \return Standard.
741  */
742 int i9e_print_completions(struct i9e_completer *completers)
743 {
744         struct i9e_completion_result cr;
745         struct i9e_completion_info ci;
746         char *buf;
747         const char *end, *p;
748         int i, n, ret;
749
750         reset_completion_result(&cr);
751         buf = getenv("COMP_POINT");
752         ci.point = buf? atoi(buf) : 0;
753         ci.buffer = para_strdup(getenv("COMP_LINE"));
754
755         ci.argc = create_argv(ci.buffer, " ", &ci.argv);
756         ci.word_num = compute_word_num(ci.buffer, " ", ci.point);
757
758         end = ci.buffer + ci.point;
759         for (p = end; p > ci.buffer && *p != ' '; p--)
760                 ; /* nothing */
761         if (*p == ' ')
762                 p++;
763
764         n = end - p + 1;
765         ci.word = para_malloc(n + 1);
766         strncpy(ci.word, p, n);
767         ci.word[n] = '\0';
768
769         PARA_DEBUG_LOG("line: %s, point: %d (%c), wordnum: %d, word: %s\n",
770                 ci.buffer, ci.point, ci.buffer[ci.point], ci.word_num, ci.word);
771         if (ci.word_num == 0)
772                 cr.matches = i9e_complete_commands(ci.word, completers);
773         else
774                 create_matches(&ci, completers, &cr);
775         ret = 0;
776         if (cr.matches && cr.matches[0]) {
777                 for (i = 0; cr.matches[i]; i++)
778                         printf("%s\n", cr.matches[i]);
779                 ret = 1;
780         }
781         printf("-o=");
782         if (cr.dont_append_space)
783                 printf("nospace");
784         if (cr.filename_completion_desired)
785                 printf(",filenames");
786         printf("\n");
787         free_argv(cr.matches);
788         free_argv(ci.argv);
789         free(ci.buffer);
790         free(ci.word);
791         return ret;
792 }