-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlibedit4pl.c
More file actions
3619 lines (3069 loc) · 93.1 KB
/
Copy pathlibedit4pl.c
File metadata and controls
3619 lines (3069 loc) · 93.1 KB
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: jan@swi-prolog.org
WWW: http://www.swi-prolog.org
Copyright (c) 2017-2026, VU University Amsterdam
CWI, Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#define SWIPL_WINDOWS_NATIVE_ACCESS 1 /* get Swinhandle() */
#include <string.h>
#include <stdlib.h>
#include <SWI-Stream.h>
#include <SWI-Prolog.h>
#include <config.h>
#include <signal.h>
#include <assert.h>
#include <histedit.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#ifdef O_PLMT
#include <pthread.h>
#endif
#if defined(HAVE_POLL_H) && defined(HAVE_POLL)
#include <poll.h>
#elif defined(HAVE_SYS_SELECT_H)
#include <sys/select.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_UXNT_H
#include <uxnt.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifndef __WINDOWS__
#include <termios.h> /* reclaim_tty() */
#endif
#ifdef __WINDOWS__
#include <io.h>
#endif
/* libedit's included config.h doesn't carry a SIZEOF_WCHAR_T define on
* every platform. Fall back to the compiler-provided intrinsic so
* the `#if SIZEOF_WCHAR_T == 2` branches here actually fire where they
* should (e.g. MinGW/MSVC Windows with 16-bit wchar_t). */
#ifndef SIZEOF_WCHAR_T
# ifdef __SIZEOF_WCHAR_T__
# define SIZEOF_WCHAR_T __SIZEOF_WCHAR_T__
# else
# define SIZEOF_WCHAR_T 4
# endif
#endif
#ifndef EPILOG
#define EPILOG 0x400 /* Windows: Epilog using pipes */
#endif
static atom_t ATOM_norm;
static atom_t ATOM_newline;
static atom_t ATOM_eof;
static atom_t ATOM_arghack;
static atom_t ATOM_refresh;
static atom_t ATOM_refresh_beep;
static atom_t ATOM_cursor;
static atom_t ATOM_redisplay;
static atom_t ATOM_error;
static atom_t ATOM_fatal;
static atom_t ATOM_clear;
static atom_t ATOM_setsize;
static atom_t ATOM_getsize;
static atom_t ATOM_setunique;
static atom_t ATOM_set;
static atom_t ATOM_prev_str;
static atom_t ATOM_next_str;
static atom_t ATOM_event;
static atom_t ATOM_wordchars;
static atom_t ATOM_editor;
static atom_t ATOM_bracketed_paste;
static atom_t ATOM_prompt_marks;
static atom_t ATOM_attrs;
static functor_t FUNCTOR_error2;
static functor_t FUNCTOR_editline1;
static functor_t FUNCTOR_line2;
static functor_t FUNCTOR_electric3;
static functor_t FUNCTOR_pair2;
#ifdef __WINDOWS__
#define REP_EL REP_UTF8
#else
#define REP_EL REP_MB
#endif
#ifdef _MSC_VER
#define strdup(s) _strdup(s)
#endif
#define MAX_LINE_TAIL 512 /* Longer than a prompt ever is. See
THE UNFINISHED LINE below. */
#define STR_OPTIONS (CVT_ATOM|CVT_STRING|CVT_LIST|REP_EL|CVT_EXCEPTION)
/*******************************
* PAINT LOCK *
*******************************/
/* Serialise painting the input line between the thread that reads it
* and any thread that writes to the terminal. A single threaded build
* has no second writer, so the lock compiles away and the binding does
* not need pthreads at all. See Swrite_libedit().
*/
#ifdef O_PLMT
typedef pthread_mutex_t paint_lock_t;
#define paint_lock_init(l) pthread_mutex_init(l, NULL)
#define paint_lock_destroy(l) pthread_mutex_destroy(l)
#define paint_lock(l) pthread_mutex_lock(l)
#define paint_unlock(l) pthread_mutex_unlock(l)
#else
typedef char paint_lock_t;
#define paint_lock_init(l) ((void)0)
#define paint_lock_destroy(l) ((void)0)
#define paint_lock(l) ((void)0)
#define paint_unlock(l) ((void)0)
#endif
/*******************************
* WIN/UNIX *
*******************************/
#ifdef __WINDOWS__
typedef HANDLE os_handle;
#define Soshandle(s) Swinhandle(s)
#define OSNOHANDLE NULL
#define isatty(fd) isconsole(fd)
static bool
isconsole(HANDLE h)
{ DWORD mode;
return GetConsoleMode(h, &mode);
}
#undef EL_GETFP /* avoid accidental use */
#else/*__WINDOWS__*/
typedef int os_handle;
#define OSNOHANDLE (-1)
#define Soshandle(s) Sfileno(s)
#endif/*__WINDOWS__*/
/*******************************
* CONTEXT *
*******************************/
typedef struct command
{ struct command *next;
atom_t name; /* name of the command */
record_t closure; /* called goal */
module_t module; /* target module */
} command;
typedef struct binding
{ struct binding *next;
int ch;
command *command;
} binding;
typedef enum electric_state
{ E_NONE = 0, /* idle state */
E_WAIT, /* Wait for timeout */
E_COMMAND /* get second char */
} electric_state;
#define EL_CTX_MAGIC 1329760607
typedef struct el_context
{ struct el_context *next; /* Next in list */
int magic; /* EL_CTX_MAGIC */
os_handle fd; /* Input file we are attached to */
IOSTREAM *istream; /* Input stream */
IOSTREAM *ostream; /* Output stream */
IOSTREAM *estream; /* Error stream */
EditLine *el; /* EditLine context */
char * buffered; /* Buffered long line */
int sig_no; /* For read_char() */
HistEvent ev; /* History event */
History *history; /* Complete history */
char *prompt_raw; /* Prompt as Prolog gave it */
char *prompt; /* Same, with literals delimited */
IOFUNCTIONS *orig_functions; /* Original functions */
IOFUNCTIONS functions; /* SIO function block */
command *commands; /* User commands */
binding *bindings; /* Bindings to user commands */
int reader; /* Current reader thread */
bool is_stdin; /* Reading from file 0 */
bool bracketed_paste;/* Keep bracketed paste mode enabled */
bool prompt_marks; /* Mark prompt and input (OSC 133) */
bool output_open; /* Wrote OSC 133 C, owe a D */
bool prompt_cont; /* ... and it continues an input */
short dispatching; /* We are dispatching an event */
short cols; /* Terminal size we told libedit */
short rows; /* about. See check_terminal_size() */
paint_lock_t paint_lock; /* Serialise painting the input line */
bool line_hidden; /* Input line is off the screen */
bool at_bol; /* Foreign output ended a line */
char *line_tail; /* Output on the line it did not end */
size_t line_tail_len; /* Bytes of it we hold */
size_t line_tail_cols; /* Roughly what it paints; only
used to refuse a long one */
bool line_tail_ok; /* ... and we can hand it to libedit */
bool prompt_from_bol;/* The prompt holds it, so paint from
column 0 */
unsigned int flags; /* Misc flags */
int histsize; /* History size */
struct
{ int timeout; /* Time to wait */
int move; /* Amount to move */
electric_state state;
} electric;
#ifndef HAVE_EL_CURSOR
int move_cursor; /* Amount to move the cursor */
#endif
#if SIZEOF_WCHAR_T == 2
int pending_trail; /* Queued UTF-16 trail surrogate;
0 if none. Needed when the
decoded input is a supplementary
code point but wchar_t holds only
16 bits: read_char returns the
lead first and the trail on the
next call. */
#endif
} el_context;
static el_context *el_clist = NULL;
static el_context *
get_context(os_handle fd)
{ el_context *c;
for(c=el_clist; c; c=c->next)
{ if ( c->fd == fd )
return c;
}
return NULL;
}
#ifdef O_SIGNALS
static el_context *
get_std_context(void)
{ el_context *c;
for(c=el_clist; c; c=c->next)
{ if ( c->is_stdin )
return c;
}
return NULL;
}
#endif
static el_context *
get_context_from_handle(void *handle)
{ el_context *c;
for(c=el_clist; c; c=c->next)
{ IOSTREAM *s;
if ( (s=c->istream) && s->handle == handle )
return c;
}
return NULL;
}
static el_context *
get_context_from_ohandle(void *handle)
{ el_context *c;
for(c=el_clist; c; c=c->next)
{ IOSTREAM *s;
if ( (s=c->ostream) && s->handle == handle )
return c;
if ( (s=c->estream) && s->handle == handle )
return c;
}
return NULL;
}
static el_context *
alloc_context(os_handle fd)
{ el_context *c = PL_malloc(sizeof(*c));
memset(c, 0, sizeof(*c));
c->fd = fd;
c->magic = EL_CTX_MAGIC;
c->at_bol = true;
c->line_tail = malloc(MAX_LINE_TAIL+1);
c->line_tail_ok = (c->line_tail != NULL);
paint_lock_init(&c->paint_lock);
c->next = el_clist;
el_clist = c;
return c;
}
/*******************************
* THE UNFINISHED LINE *
*******************************/
/* The text on the output line the client has not ended.
*
* A read that starts where the output left the caret has no prompt of
* its own. `format("name: "), read_line_to_string(user_input, S)' puts
* `name: ' on the screen as ordinary output and then reads, so libedit
* is handed an empty prompt and takes the line to start in column 0 --
* six columns to the left of where it does. While it moves the caret
* relatively that goes unseen, but a full refresh (a SIGWINCH, a resize
* it notices at a keypress, ^L) redraws the input over `name: ' and
* leaves the caret six columns out.
*
* The column alone would not mend it: libedit repaints the columns it
* counts, so it has to be given the text. Remember what went on the
* line and hand it to libedit as the front of its prompt. libedit then
* counts those columns, paints them itself, and puts them back whenever
* it redraws. See update_prompt() and the `\r' before el_siggets().
*
* What arrives here is what a stream write handler is given: bytes in
* the stream's encoding, while a prompt is UTF-8 (PL_prompt_string()).
* Only the encodings that convert without a decoder are taken; the rest
* give up, and give up is also what a line too long to put back on one
* row does. Either way the line stays as it is today.
*/
/* How the units of a write become the UTF-8 of a prompt. */
typedef enum
{ TAIL_UTF8, /* already UTF-8; copy the bytes */
TAIL_CODE, /* one code point per unit */
TAIL_ASCII /* the same, if it stays ASCII */
} tail_encoding;
static tail_encoding
tail_encoding_of(IOSTREAM *s)
{ switch(s ? s->encoding : ENC_ANSI)
{ case ENC_UTF8:
return TAIL_UTF8;
case ENC_ISO_LATIN_1:
case ENC_OCTET:
case ENC_WCHAR:
return TAIL_CODE;
default: /* ENC_ANSI and friends: a decoder */
return TAIL_ASCII; /* we do not have */
}
}
static void
line_tail_clear(el_context *ctx)
{ ctx->line_tail_len = 0;
ctx->line_tail_cols = 0;
ctx->line_tail_ok = true;
}
/* Append one unit, or give up on the line. Giving up is sticky until
* the line ends: half a prompt is worse than none.
*/
static void
line_tail_add(el_context *ctx, int c, tail_encoding enc, bool visible)
{ char buf[6];
size_t len, at;
if ( !ctx->line_tail_ok )
return;
if ( enc == TAIL_UTF8 || (c >= 0 && c < 0x80) )
{ buf[0] = (char)c;
len = 1;
} else if ( enc == TAIL_ASCII ||
c < 0 || c > 0x10ffff || /* not a code point, or half of */
(c >= 0xd800 && c <= 0xdfff) ) /* one: a UTF-16 surrogate */
{ ctx->line_tail_ok = false; /* we cannot name this character */
return;
} else /* TAIL_CODE: encode as UTF-8 */
{ len = 0;
if ( c < 0x800 )
{ buf[len++] = (char)(0xc0|(c>>6));
} else if ( c < 0x10000 )
{ buf[len++] = (char)(0xe0|(c>>12));
buf[len++] = (char)(0x80|((c>>6)&0x3f));
} else
{ buf[len++] = (char)(0xf0|(c>>18));
buf[len++] = (char)(0x80|((c>>12)&0x3f));
buf[len++] = (char)(0x80|((c>>6)&0x3f));
}
buf[len++] = (char)(0x80|(c&0x3f));
}
at = ctx->line_tail_len; /* read once: two threads may write */
if ( at+len > MAX_LINE_TAIL ) /* to the same line, and neither */
{ ctx->line_tail_ok = false; /* may run off the buffer */
return;
}
memcpy(ctx->line_tail+at, buf, len);
ctx->line_tail[at+len] = '\0';
ctx->line_tail_len = at+len;
if ( visible )
ctx->line_tail_cols++;
}
/* The text to put in front of the prompt, or NULL to leave the line as
* the client left it. A tail that does not fit on a row is refused:
* the `\r' that puts libedit at the start of it would land on the wrong
* one.
*/
static const char *
adopted_line_tail(el_context *ctx)
{ if ( !ctx->line_tail_ok || ctx->line_tail_len == 0 )
return NULL;
if ( ctx->cols > 0 && ctx->line_tail_cols >= (size_t)ctx->cols )
return NULL;
return ctx->line_tail;
}
/* The OSC 133 "semantic prompt" marks of FinalTerm, as spoken by
* iTerm2, kitty, WezTerm, VS Code and the Epilog terminal: `A' starts a
* prompt, `B' ends the prompt and starts the line the user edits, `C'
* ends that line and starts the output of what was entered, and `D' ends
* that output. A terminal that reads them knows what is prompt, what
* the user typed and what came out of it. Epilog uses `B' and `C' to
* know that there is a line being edited and where it starts, so that a
* click in it can ask us to move the caret there, and the four together
* to hand the whole command over to <-blocks.
*
* `A' and `B' are part of the prompt rather than written from here, so
* that libedit emits them from its display, at the place where the
* prompt and the input really start. See marked_prompt(). A read that
* asks for a single character is not marked at all: there is no line
* being edited there.
*
* `D' is written before the next prompt rather than when the output
* stops, because nothing tells us that it has: the caret sits where the
* output left it until something asks for another line. ctx->output_open
* keeps each `C' to one `D', so a read from inside a read -- the
* debugger, a nested toplevel -- cannot close a command that is still
* running.
*/
#define OSC133_PROMPT "\033]133;A\033\\"
#define OSC133_PROMPT2 "\033]133;A;k=s\033\\"
#define OSC133_INPUT "\033]133;B\033\\"
#define OSC133_ENTERED "\033]133;C\033\\"
#define OSC133_DONE "\033]133;D\033\\"
#define PROMPT_LITERAL '\001' /* our EL_PROMPT_ESC delimiter */
/* escape_length() returns the length of the ANSI escape sequence starting
* at `in' or 0 if there is none. Recognised are CSI (ESC [ ... final
* byte), OSC (ESC ] ... BEL or ESC \) and two-character sequences.
*/
static size_t
escape_length(const char *in)
{ const char *s = in;
if ( *s != '\033' )
return 0;
switch(*++s)
{ case '[': /* CSI */
while ( *++s >= 0x20 && *s <= 0x3f )
;
return (*s >= 0x40 && *s <= 0x7e) ? (size_t)(s+1-in) : 0;
case ']': /* OSC */
while ( *++s )
{ if ( *s == '\007' )
return (size_t)(s+1-in);
if ( *s == '\033' && s[1] == '\\' )
return (size_t)(s+2-in);
}
return 0;
default:
while ( *s >= 0x20 && *s <= 0x2f ) /* intermediate bytes */
s++;
return *s ? (size_t)(s+1-in) : 0;
}
}
/* prompt_with_literals() surrounds each run of escape sequences with the
* EL_PROMPT_ESC delimiter, so libedit emits them without counting them as
* columns. Delimiters already present are honoured (\002 is mapped to
* \001, as readline uses two different ones). Adjacent runs are merged:
* libedit attaches the character following a group to it, so two groups
* in a row would make the delimiter itself that character.
*/
static char *
prompt_with_literals(const char *in)
{ char *out = malloc(strlen(in)*2+1); /* worst case: all escapes */
const char *s;
char *o;
bool literal = false; /* inside a delimited run */
if ( !out )
return NULL;
for(s=in, o=out; *s; )
{ size_t esclen;
if ( *s == PROMPT_LITERAL || *s == '\002' )
{ *o++ = PROMPT_LITERAL;
literal = !literal;
s++;
} else if ( !literal && (esclen=escape_length(s)) )
{ if ( o > out && o[-1] == PROMPT_LITERAL )
o--; /* merge with the previous run */
else
*o++ = PROMPT_LITERAL;
do
{ memcpy(o, s, esclen);
o += esclen;
s += esclen;
} while ( (esclen=escape_length(s)) );
*o++ = PROMPT_LITERAL;
} else
{ *o++ = *s++;
}
}
*o = '\0';
return out;
}
/* marked_prompt() surrounds the prompt with the OSC 133 marks that say
* where a prompt starts and where the line the user edits starts, and
* delimits the result for libedit. The marks ride along in the prompt
* rather than being written once because libedit emits the prompt from
* its display: that puts each mark at the place it talks about, and
* puts it there again whenever the prompt is drawn somewhere else.
*/
static char *
marked_prompt(const char *prompt, bool continuation)
{ const char *a = continuation ? OSC133_PROMPT2 : OSC133_PROMPT;
size_t len = strlen(a)+strlen(prompt)+strlen(OSC133_INPUT);
char *marked = malloc(len+1);
char *delimited;
if ( !marked )
return NULL;
snprintf(marked, len+1, "%s%s%s", a, prompt, OSC133_INPUT);
delimited = prompt_with_literals(marked);
free(marked);
return delimited;
}
/* The prompt libedit is to draw, which is what Prolog asked for behind
* whatever the client already put on the line. Both are prompt as far
* as the user is concerned, and taking them together is what puts
* libedit's columns where the screen's are; see MAX_LINE_TAIL.
*/
static char *
raw_prompt(el_context *ctx)
{ const char *pre = adopted_line_tail(ctx);
const char *np = PL_prompt_string(ctx->istream);
ctx->prompt_from_bol = (pre != NULL);
if ( !pre )
return np ? strdup(np) : NULL;
if ( !np )
return strdup(pre);
{ size_t len = strlen(pre)+strlen(np);
char *raw = malloc(len+1);
if ( raw )
snprintf(raw, len+1, "%s%s", pre, np);
return raw;
}
}
static void
update_prompt(el_context *ctx)
{ bool cont = PL_prompt_is_continuation(ctx->istream);
char *np;
/* Before raw_prompt(), which is what asks for the prompt: asking is
what makes the one of a first line used up, and after that every
prompt is a continuation. */
np = raw_prompt(ctx);
if ( ctx->prompt_raw && np && strcmp(np, ctx->prompt_raw) == 0 &&
ctx->prompt_cont == cont )
{ free(np);
return;
}
free(ctx->prompt);
free(ctx->prompt_raw);
ctx->prompt = ctx->prompt_raw = NULL;
ctx->prompt_cont = cont;
if ( ctx->prompt_marks )
{ /* Prolog writes no prompt for a read that starts where the output
left the caret. The input still starts there and is still
edited, so it is still marked.
*/
ctx->prompt = marked_prompt(np ? np : "", cont);
} else if ( np )
{ ctx->prompt = prompt_with_literals(np);
}
ctx->prompt_raw = np;
}
static bool
el_error(const char *msg)
{ term_t ex;
return ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex, PL_FUNCTOR, FUNCTOR_error2,
PL_FUNCTOR, FUNCTOR_editline1,
PL_STRING, msg,
PL_VARIABLE) &&
PL_raise_exception(ex) );
}
/*******************************
* PORT *
*******************************/
#ifndef HAVE_EL_CURSOR
#define el_cursor(el, cnt) el_cursor_emulated(el, cnt)
static int
el_cursor_emulated(EditLine *el, int count)
{ el_context *ctx;
const LineInfo *li;
el_get(el, EL_CLIENTDATA, (void**)&ctx);
li = el_line(ctx->el);
if ( count < 0 ) /* backward */
{ if ( -count > li->cursor - li->buffer )
count = li->buffer - li->cursor;
} else
{ if ( count > li->lastchar - li->cursor )
count = li->lastchar - li->cursor;
}
ctx->move_cursor = count;
return li->cursor - li->buffer + count;
}
#endif
/* el_cursor_cp_delta():
* Translate a CODE-POINT delta (the count Prolog hands us via
* `string_length` and matching_open's index) into a WCHAR_T
* delta, which is what the underlying el_cursor() takes.
*
* On Linux with sizeof(wchar_t) == 4 the two are equal and this
* is the identity. On Windows wchar_t is 16 bits and a non-BMP
* code point lives as a UTF-16 surrogate pair (two wchar_t),
* so the wchar_t step is bigger than the code-point step.
* Without translating, electric-caret jumps over emoji / CJK
* Ext B land mid-surrogate.
*/
#if SIZEOF_WCHAR_T == 2
# define IS_UTF16_LEAD_(c) ((c) >= 0xD800 && (c) <= 0xDBFF)
# define IS_UTF16_TRAIL_(c) ((c) >= 0xDC00 && (c) <= 0xDFFF)
#endif
static int
el_cursor_cp_delta(EditLine *el, int cp_delta)
{
#if SIZEOF_WCHAR_T == 2
const LineInfoW *li = el_wline(el);
const wchar_t *p = li->cursor;
int wchar_delta = 0;
if ( cp_delta == 0 )
return 0;
if ( cp_delta > 0 )
{ for(int i = 0; i < cp_delta && p < li->lastchar; i++)
{ if ( IS_UTF16_LEAD_(p[0]) && p+1 < li->lastchar &&
IS_UTF16_TRAIL_(p[1]) )
{ p += 2; wchar_delta += 2;
} else
{ p += 1; wchar_delta += 1;
}
}
} else
{ for(int i = 0; i < -cp_delta && p > li->buffer; i++)
{ p -= 1; wchar_delta -= 1;
if ( p > li->buffer && IS_UTF16_TRAIL_(*p) &&
IS_UTF16_LEAD_(p[-1]) )
{ p -= 1; wchar_delta -= 1;
}
}
}
return wchar_delta;
#else
(void)el;
return cp_delta;
#endif
}
/* el_write_terminal():
* Write a control sequence straight to the terminal, behind the
* editor's display. On Windows the output handle is obtained via
* EL_GETHANDLE; on Unix via EL_GETFP.
*/
static void
el_write_terminal(EditLine *el, const char *seq)
{ size_t len = strlen(seq);
#ifdef __WINDOWS__
{ HANDLE hOut;
DWORD written;
if ( el_get(el, EL_GETHANDLE, 1, &hOut) == 0 )
WriteFile(hOut, seq, (DWORD)len, &written, NULL);
}
#else
{ FILE *fout;
if ( el_get(el, EL_GETFP, 1, &fout) == 0 )
{ fwrite(seq, 1, len, fout);
fflush(fout);
}
}
#endif
}
/* el_bracketed_paste():
* Ask the terminal to bracket pasted text (enable=1) or to stop
* doing so (enable=0).
*/
static void
el_bracketed_paste(EditLine *el, bool enable)
{ el_write_terminal(el, enable ? "\033[?2004h" : "\033[?2004l");
}
/*******************************
* SIGNAL HANDLING *
*******************************/
#ifdef O_SIGNALS
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Signal handling. The original design sets up and tears down signal
handlers while inside libedit's main function el_gets(). See
el_siggets() in this file. Signal handling is only setup for the main
thread, i.e., for `swipl`.
We must ensure Epilog windows handle resizing properly. On an Epilog
window resize, Epilog updates the size in the PTY and sends SIGWINCH
to the Prolog client thread using pthread_kill(). We must ensure that
SIGWINCH is always handled.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
typedef struct
{ int signo; /* number of the signal */
bool prepared; /* Is currently prepared */
struct sigaction old_state; /* old state for the signal */
} sigstate;
static void el_sighandler(int sig);
/* Signals that should always be handled by this library */
static sigstate always_signals[] =
{ { SIGWINCH },
{ -1 }
};
static bool always_signals_prepared = false;
/* Signals handled while we are inside el_gets().
* el_signals[0] is SWI-Prolog's _alert_ signal, i.e., the signal
* used to make blocking system calls return using EINTR such that
* we can process synchronous Prolog signals.
*/
static sigstate el_signals[] =
{ { SIGUSR2 }, /* See above. Must be first */
{ SIGINT },
#ifdef SIGTSTP
{ SIGTSTP },
{ SIGCONT },
{ SIGTTOU },
{ SIGTTIN },
#endif
{ SIGALRM },
{ SIGTERM },
{ SIGQUIT },
{ -1 }
};
/* Signals after we were stopped by SIGTSTP */
static sigstate cont_signals[] =
{
#ifdef SIGCONT
{ SIGCONT },
#endif
{ -1 }
};
static void
prepare_signals(sigstate *s)
{ for(; s->signo != -1; s++)
{ if ( !s->prepared )
{ struct sigaction new;
memset(&new, 0, sizeof(new));
new.sa_handler = el_sighandler;
sigaction(s->signo, &new, &s->old_state);
s->prepared = true;
}
}
}
static void
restore_signals(sigstate *s)
{ for(; s->signo != -1; s++)
{ sigaction(s->signo, &s->old_state, NULL);
s->prepared = false;
}
}
/** Our signal handler. Deals with
*
* - SIGWINCH
* Just causes read() to return.
* - SIGTSTP/SIGCONT
* Restores terminal around ^Z/fg
* - SIGINT
* Clears accumulated line
* - SWI-Prolog alert signal
* Just causes a return. This implies the synchronous
* interrupt handler is executed while editline is enabled,
* but there is little we can do about that. Possibly we
* need a hook in Prolog to save/restore the terminal during
* the actual synchronous signal handling?
* - Other signals
* Restores terminal while calling the default handler.
*/
static void
el_sighandler(int sig)
{ sigstate *s;
el_context *ctx;
for(ctx=el_clist; ctx; ctx=ctx->next)
ctx->sig_no = sig;
switch(sig)
{ case SIGWINCH:
return;
case SIGCONT:
if ( (ctx = get_std_context()) )
el_set(ctx->el, EL_PREP_TERM, 1);
restore_signals(cont_signals);
prepare_signals(el_signals);
return;
case SIGTSTP:
restore_signals(el_signals);
prepare_signals(cont_signals);
if ( (ctx = get_std_context()) )
el_set(ctx->el, EL_PREP_TERM, 0);
kill(getpid(), sig);
return;
case SIGINT:
{ if ( (ctx = get_std_context()) )
{ FILE *err;
int size = el_cursor(ctx->el, 10000);
el_deletestr(ctx->el, size);
el_get(ctx->el, EL_GETFP, 2, &err);
fprintf(err, "^C\n");
}
}
default:
/* The Prolog alert signal */
if ( sig == el_signals[0].signo )
return;
}
restore_signals(el_signals);
if ( (ctx = get_std_context()) )
el_set(ctx->el, EL_PREP_TERM, 0);
for(s=el_signals; s->signo != -1; s++)
{ if ( s->signo == sig )
{ void (*func)(int) = s->old_state.sa_handler;
if ( func == SIG_DFL )
{ PL_raise(sig); /* was: kill(getpid(), sig); */
} else if ( func != SIG_IGN )
{ (*func)(sig);
}
break;
}
}
if ( (ctx = get_std_context()) )
el_set(ctx->el, EL_PREP_TERM, 1);
prepare_signals(el_signals);
}
static const char *
el_siggets(EditLine *el, int *count)
{ el_context *ctx;
const char *line;
el_get(el, EL_CLIENTDATA, (void**)&ctx);
/* Re-enable bracketed paste mode in case a subprocess or a single
character read (see Sread_libedit()) disabled it. */
if ( ctx->bracketed_paste )
el_bracketed_paste(el, true);
if ( ctx->is_stdin )
{ prepare_signals(el_signals);
line = el_gets(el, count);
restore_signals(el_signals);
} else
{ line = el_gets(el, count);
}
return line;
}
static void
update_always_signals(void)
{ if ( el_clist && !always_signals_prepared )
{ prepare_signals(always_signals);
always_signals_prepared = true;
} else if ( !el_clist && always_signals_prepared )
{ restore_signals(always_signals);
always_signals_prepared = false;
}
}
#else /* O_SIGNALS */