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