- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathreadline.c
1230 lines (1021 loc) · 32.4 KB
/
readline.c
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
/* This module makes GNU readline available to Python. It has ideas
* contributed by Lee Busby, LLNL, and William Magro, Cornell Theory
* Center. The completer interface was inspired by Lele Gaifax. More
* recently, it was largely rewritten by Guido van Rossum.
*/
/* Standard definitions */
#include"Python.h"
#include<setjmp.h>
#include<signal.h>
#include<errno.h>
#include<sys/time.h>
#if defined(HAVE_SETLOCALE)
/* GNU readline() mistakenly sets the LC_CTYPE locale.
* This is evil. Only the user or the app's main() should do this!
* We must save and restore the locale around the rl_initialize() call.
*/
#defineSAVE_LOCALE
#include<locale.h>
#endif
#ifdefSAVE_LOCALE
# defineRESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); }
#else
# defineRESTORE_LOCALE(sl)
#endif
/* GNU readline definitions */
#undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
#include<readline/readline.h>
#include<readline/history.h>
#ifdefHAVE_RL_COMPLETION_MATCHES
#definecompletion_matches(x, y) \
rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
#else
#if defined(_RL_FUNCTION_TYPEDEF)
externchar**completion_matches(char*, rl_compentry_func_t*);
#else
#if !defined(__APPLE__)
externchar**completion_matches(char*, CPFunction*);
#endif
#endif
#endif
#ifdef__APPLE__
/*
* It is possible to link the readline module to the readline
* emulation library of editline/libedit.
*
* On OSX this emulation library is not 100% API compatible
* with the "real" readline and cannot be detected at compile-time,
* hence we use a runtime check to detect if we're using libedit
*
* Currently there is one known API incompatibility:
* - 'get_history' has a 1-based index with GNU readline, and a 0-based
* index with older versions of libedit's emulation.
* - Note that replace_history and remove_history use a 0-based index
* with both implementations.
*/
staticintusing_libedit_emulation=0;
staticconstcharlibedit_version_tag[] ="EditLine wrapper";
staticintlibedit_history_start=0;
#endif/* __APPLE__ */
#ifdefHAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
staticvoid
on_completion_display_matches_hook(char**matches,
intnum_matches, intmax_length);
#endif
/* Memory allocated for rl_completer_word_break_characters
(see issue #17289 for the motivation). */
staticchar*completer_word_break_characters;
/* Exported function to send one line to readline's init file parser */
staticPyObject*
parse_and_bind(PyObject*self, PyObject*args)
{
char*s, *copy;
if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
returnNULL;
/* Make a copy -- rl_parse_and_bind() modifies its argument */
/* Bernard Herzog */
copy=malloc(1+strlen(s));
if (copy==NULL)
returnPyErr_NoMemory();
strcpy(copy, s);
rl_parse_and_bind(copy);
free(copy); /* Free the copy */
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_parse_and_bind,
"parse_and_bind(string) -> None\n\
Execute the init line provided in the string argument.");
/* Exported function to parse a readline init file */
staticPyObject*
read_init_file(PyObject*self, PyObject*args)
{
char*s=NULL;
if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
returnNULL;
errno=rl_read_init_file(s);
if (errno)
returnPyErr_SetFromErrno(PyExc_IOError);
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_read_init_file,
"read_init_file([filename]) -> None\n\
Execute a readline initialization file.\n\
The default filename is the last filename used.");
/* Exported function to load a readline history file */
staticPyObject*
read_history_file(PyObject*self, PyObject*args)
{
char*s=NULL;
if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
returnNULL;
errno=read_history(s);
if (errno)
returnPyErr_SetFromErrno(PyExc_IOError);
Py_RETURN_NONE;
}
staticint_history_length=-1; /* do not truncate history by default */
PyDoc_STRVAR(doc_read_history_file,
"read_history_file([filename]) -> None\n\
Load a readline history file.\n\
The default filename is ~/.history.");
/* Exported function to save a readline history file */
staticPyObject*
write_history_file(PyObject*self, PyObject*args)
{
char*s=NULL;
if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
returnNULL;
errno=write_history(s);
if (!errno&&_history_length >= 0)
history_truncate_file(s, _history_length);
if (errno)
returnPyErr_SetFromErrno(PyExc_IOError);
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_write_history_file,
"write_history_file([filename]) -> None\n\
Save a readline history file.\n\
The default filename is ~/.history.");
/* Set history length */
staticPyObject*
set_history_length(PyObject*self, PyObject*args)
{
intlength=_history_length;
if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
returnNULL;
_history_length=length;
Py_RETURN_NONE;
}
PyDoc_STRVAR(set_history_length_doc,
"set_history_length(length) -> None\n\
set the maximal number of lines which will be written to\n\
the history file. A negative length is used to inhibit\n\
history truncation.");
/* Get history length */
staticPyObject*
get_history_length(PyObject*self, PyObject*noarg)
{
returnPyInt_FromLong(_history_length);
}
PyDoc_STRVAR(get_history_length_doc,
"get_history_length() -> int\n\
return the maximum number of lines that will be written to\n\
the history file.");
/* Generic hook function setter */
staticPyObject*
set_hook(constchar*funcname, PyObject**hook_var, PyObject*args)
{
PyObject*function=Py_None;
charbuf[80];
PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
if (!PyArg_ParseTuple(args, buf, &function))
returnNULL;
if (function==Py_None) {
Py_CLEAR(*hook_var);
}
elseif (PyCallable_Check(function)) {
PyObject*tmp=*hook_var;
Py_INCREF(function);
*hook_var=function;
Py_XDECREF(tmp);
}
else {
PyOS_snprintf(buf, sizeof(buf),
"set_%.50s(func): argument not callable",
funcname);
PyErr_SetString(PyExc_TypeError, buf);
returnNULL;
}
Py_RETURN_NONE;
}
/* Exported functions to specify hook functions in Python */
staticPyObject*completion_display_matches_hook=NULL;
staticPyObject*startup_hook=NULL;
#ifdefHAVE_RL_PRE_INPUT_HOOK
staticPyObject*pre_input_hook=NULL;
#endif
staticPyObject*
set_completion_display_matches_hook(PyObject*self, PyObject*args)
{
PyObject*result=set_hook("completion_display_matches_hook",
&completion_display_matches_hook, args);
#ifdefHAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
/* We cannot set this hook globally, since it replaces the
default completion display. */
rl_completion_display_matches_hook=
completion_display_matches_hook ?
#if defined(_RL_FUNCTION_TYPEDEF)
(rl_compdisp_func_t*)on_completion_display_matches_hook : 0;
#else
(VFunction*)on_completion_display_matches_hook : 0;
#endif
#endif
returnresult;
}
PyDoc_STRVAR(doc_set_completion_display_matches_hook,
"set_completion_display_matches_hook([function]) -> None\n\
Set or remove the completion display function.\n\
The function is called as\n\
function(substitution, [matches], longest_match_length)\n\
once each time matches need to be displayed.");
staticPyObject*
set_startup_hook(PyObject*self, PyObject*args)
{
returnset_hook("startup_hook", &startup_hook, args);
}
PyDoc_STRVAR(doc_set_startup_hook,
"set_startup_hook([function]) -> None\n\
Set or remove the function invoked by the rl_startup_hook callback.\n\
The function is called with no arguments just\n\
before readline prints the first prompt.");
#ifdefHAVE_RL_PRE_INPUT_HOOK
/* Set pre-input hook */
staticPyObject*
set_pre_input_hook(PyObject*self, PyObject*args)
{
returnset_hook("pre_input_hook", &pre_input_hook, args);
}
PyDoc_STRVAR(doc_set_pre_input_hook,
"set_pre_input_hook([function]) -> None\n\
Set or remove the function invoked by the rl_pre_input_hook callback.\n\
The function is called with no arguments after the first prompt\n\
has been printed and just before readline starts reading input\n\
characters.");
#endif
/* Exported function to specify a word completer in Python */
staticPyObject*completer=NULL;
staticPyObject*begidx=NULL;
staticPyObject*endidx=NULL;
/* Get the completion type for the scope of the tab-completion */
staticPyObject*
get_completion_type(PyObject*self, PyObject*noarg)
{
returnPyInt_FromLong(rl_completion_type);
}
PyDoc_STRVAR(doc_get_completion_type,
"get_completion_type() -> int\n\
Get the type of completion being attempted.");
/* Get the beginning index for the scope of the tab-completion */
staticPyObject*
get_begidx(PyObject*self, PyObject*noarg)
{
Py_INCREF(begidx);
returnbegidx;
}
PyDoc_STRVAR(doc_get_begidx,
"get_begidx() -> int\n\
get the beginning index of the completion scope");
/* Get the ending index for the scope of the tab-completion */
staticPyObject*
get_endidx(PyObject*self, PyObject*noarg)
{
Py_INCREF(endidx);
returnendidx;
}
PyDoc_STRVAR(doc_get_endidx,
"get_endidx() -> int\n\
get the ending index of the completion scope");
/* Set the tab-completion word-delimiters that readline uses */
staticPyObject*
set_completer_delims(PyObject*self, PyObject*args)
{
char*break_chars;
if (!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
returnNULL;
}
/* Keep a reference to the allocated memory in the module state in case
some other module modifies rl_completer_word_break_characters
(see issue #17289). */
break_chars=strdup(break_chars);
if (break_chars) {
free(completer_word_break_characters);
completer_word_break_characters=break_chars;
rl_completer_word_break_characters=break_chars;
Py_RETURN_NONE;
}
else
returnPyErr_NoMemory();
}
PyDoc_STRVAR(doc_set_completer_delims,
"set_completer_delims(string) -> None\n\
set the word delimiters for completion");
/* _py_free_history_entry: Utility function to free a history entry. */
#if defined(RL_READLINE_VERSION) &&RL_READLINE_VERSION >= 0x0500
/* Readline version >= 5.0 introduced a timestamp field into the history entry
structure; this needs to be freed to avoid a memory leak. This version of
readline also introduced the handy 'free_history_entry' function, which
takes care of the timestamp. */
staticvoid
_py_free_history_entry(HIST_ENTRY*entry)
{
histdata_tdata=free_history_entry(entry);
free(data);
}
#else
/* No free_history_entry function; free everything manually. */
staticvoid
_py_free_history_entry(HIST_ENTRY*entry)
{
if (entry->line)
free((void*)entry->line);
if (entry->data)
free(entry->data);
free(entry);
}
#endif
staticPyObject*
py_remove_history(PyObject*self, PyObject*args)
{
intentry_number;
HIST_ENTRY*entry;
if (!PyArg_ParseTuple(args, "i:remove_history_item", &entry_number))
returnNULL;
if (entry_number<0) {
PyErr_SetString(PyExc_ValueError,
"History index cannot be negative");
returnNULL;
}
entry=remove_history(entry_number);
if (!entry) {
PyErr_Format(PyExc_ValueError,
"No history item at position %d",
entry_number);
returnNULL;
}
/* free memory allocated for the history entry */
_py_free_history_entry(entry);
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_remove_history,
"remove_history_item(pos) -> None\n\
remove history item given by its position");
staticPyObject*
py_replace_history(PyObject*self, PyObject*args)
{
intentry_number;
char*line;
HIST_ENTRY*old_entry;
if (!PyArg_ParseTuple(args, "is:replace_history_item", &entry_number,
&line)) {
returnNULL;
}
if (entry_number<0) {
PyErr_SetString(PyExc_ValueError,
"History index cannot be negative");
returnNULL;
}
old_entry=replace_history_entry(entry_number, line, (void*)NULL);
if (!old_entry) {
PyErr_Format(PyExc_ValueError,
"No history item at position %d",
entry_number);
returnNULL;
}
/* free memory allocated for the old history entry */
_py_free_history_entry(old_entry);
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_replace_history,
"replace_history_item(pos, line) -> None\n\
replaces history item given by its position with contents of line");
/* Add a line to the history buffer */
staticPyObject*
py_add_history(PyObject*self, PyObject*args)
{
char*line;
if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
returnNULL;
}
add_history(line);
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_add_history,
"add_history(string) -> None\n\
add an item to the history buffer");
/* Get the tab-completion word-delimiters that readline uses */
staticPyObject*
get_completer_delims(PyObject*self, PyObject*noarg)
{
returnPyString_FromString(rl_completer_word_break_characters);
}
PyDoc_STRVAR(doc_get_completer_delims,
"get_completer_delims() -> string\n\
get the word delimiters for completion");
/* Set the completer function */
staticPyObject*
set_completer(PyObject*self, PyObject*args)
{
returnset_hook("completer", &completer, args);
}
PyDoc_STRVAR(doc_set_completer,
"set_completer([function]) -> None\n\
Set or remove the completer function.\n\
The function is called as function(text, state),\n\
for state in 0, 1, 2, ..., until it returns a non-string.\n\
It should return the next possible completion starting with 'text'.");
staticPyObject*
get_completer(PyObject*self, PyObject*noargs)
{
if (completer==NULL) {
Py_RETURN_NONE;
}
Py_INCREF(completer);
returncompleter;
}
PyDoc_STRVAR(doc_get_completer,
"get_completer() -> function\n\
\n\
Returns current completer function.");
/* Private function to get current length of history. XXX It may be
* possible to replace this with a direct use of history_length instead,
* but it's not clear whether BSD's libedit keeps history_length up to date.
* See issue #8065.*/
staticint
_py_get_history_length(void)
{
HISTORY_STATE*hist_st=history_get_history_state();
intlength=hist_st->length;
/* the history docs don't say so, but the address of hist_st changes each
time history_get_history_state is called which makes me think it's
freshly malloc'd memory... on the other hand, the address of the last
line stays the same as long as history isn't extended, so it appears to
be malloc'd but managed by the history package... */
free(hist_st);
returnlength;
}
/* Exported function to get any element of history */
staticPyObject*
get_history_item(PyObject*self, PyObject*args)
{
intidx=0;
HIST_ENTRY*hist_ent;
if (!PyArg_ParseTuple(args, "i:get_history_item", &idx))
returnNULL;
#ifdef__APPLE__
if (using_libedit_emulation) {
/* Older versions of libedit's readline emulation
* use 0-based indexes, while readline and newer
* versions of libedit use 1-based indexes.
*/
intlength=_py_get_history_length();
idx=idx-1+libedit_history_start;
/*
* Apple's readline emulation crashes when
* the index is out of range, therefore
* test for that and fail gracefully.
*/
if (idx< (0+libedit_history_start)
||idx >= (length+libedit_history_start)) {
Py_RETURN_NONE;
}
}
#endif/* __APPLE__ */
if ((hist_ent=history_get(idx)))
returnPyString_FromString(hist_ent->line);
else {
Py_RETURN_NONE;
}
}
PyDoc_STRVAR(doc_get_history_item,
"get_history_item() -> string\n\
return the current contents of history item at index.");
/* Exported function to get current length of history */
staticPyObject*
get_current_history_length(PyObject*self, PyObject*noarg)
{
returnPyInt_FromLong((long)_py_get_history_length());
}
PyDoc_STRVAR(doc_get_current_history_length,
"get_current_history_length() -> integer\n\
return the current (not the maximum) length of history.");
/* Exported function to read the current line buffer */
staticPyObject*
get_line_buffer(PyObject*self, PyObject*noarg)
{
returnPyString_FromString(rl_line_buffer);
}
PyDoc_STRVAR(doc_get_line_buffer,
"get_line_buffer() -> string\n\
return the current contents of the line buffer.");
#ifdefHAVE_RL_COMPLETION_APPEND_CHARACTER
/* Exported function to clear the current history */
staticPyObject*
py_clear_history(PyObject*self, PyObject*noarg)
{
clear_history();
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_clear_history,
"clear_history() -> None\n\
Clear the current readline history.");
#endif
/* Exported function to insert text into the line buffer */
staticPyObject*
insert_text(PyObject*self, PyObject*args)
{
char*s;
if (!PyArg_ParseTuple(args, "s:insert_text", &s))
returnNULL;
rl_insert_text(s);
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_insert_text,
"insert_text(string) -> None\n\
Insert text into the line buffer at the cursor position.");
/* Redisplay the line buffer */
staticPyObject*
redisplay(PyObject*self, PyObject*noarg)
{
rl_redisplay();
Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_redisplay,
"redisplay() -> None\n\
Change what's displayed on the screen to reflect the current\n\
contents of the line buffer.");
/* Table of functions exported by the module */
staticstructPyMethodDefreadline_methods[] =
{
{"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
{"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
{"insert_text", insert_text, METH_VARARGS, doc_insert_text},
{"redisplay", redisplay, METH_NOARGS, doc_redisplay},
{"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
{"read_history_file", read_history_file,
METH_VARARGS, doc_read_history_file},
{"write_history_file", write_history_file,
METH_VARARGS, doc_write_history_file},
{"get_history_item", get_history_item,
METH_VARARGS, doc_get_history_item},
{"get_current_history_length", (PyCFunction)get_current_history_length,
METH_NOARGS, doc_get_current_history_length},
{"set_history_length", set_history_length,
METH_VARARGS, set_history_length_doc},
{"get_history_length", get_history_length,
METH_NOARGS, get_history_length_doc},
{"set_completer", set_completer, METH_VARARGS, doc_set_completer},
{"get_completer", get_completer, METH_NOARGS, doc_get_completer},
{"get_completion_type", get_completion_type,
METH_NOARGS, doc_get_completion_type},
{"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
{"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
{"set_completer_delims", set_completer_delims,
METH_VARARGS, doc_set_completer_delims},
{"add_history", py_add_history, METH_VARARGS, doc_add_history},
{"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
{"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
{"get_completer_delims", get_completer_delims,
METH_NOARGS, doc_get_completer_delims},
{"set_completion_display_matches_hook", set_completion_display_matches_hook,
METH_VARARGS, doc_set_completion_display_matches_hook},
{"set_startup_hook", set_startup_hook,
METH_VARARGS, doc_set_startup_hook},
#ifdefHAVE_RL_PRE_INPUT_HOOK
{"set_pre_input_hook", set_pre_input_hook,
METH_VARARGS, doc_set_pre_input_hook},
#endif
#ifdefHAVE_RL_COMPLETION_APPEND_CHARACTER
{"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
#endif
{0, 0}
};
/* C function to call the Python hooks. */
staticint
on_hook(PyObject*func)
{
intresult=0;
if (func!=NULL) {
PyObject*r;
#ifdefWITH_THREAD
PyGILState_STATEgilstate=PyGILState_Ensure();
#endif
r=PyObject_CallFunction(func, NULL);
if (r==NULL)
goto error;
if (r==Py_None)
result=0;
else {
result=PyInt_AsLong(r);
if (result==-1&&PyErr_Occurred())
goto error;
}
Py_DECREF(r);
goto done;
error:
PyErr_Clear();
Py_XDECREF(r);
done:
#ifdefWITH_THREAD
PyGILState_Release(gilstate);
#endif
returnresult;
}
returnresult;
}
staticint
#if defined(_RL_FUNCTION_TYPEDEF)
on_startup_hook(void)
#else
on_startup_hook()
#endif
{
returnon_hook(startup_hook);
}
#ifdefHAVE_RL_PRE_INPUT_HOOK
staticint
#if defined(_RL_FUNCTION_TYPEDEF)
on_pre_input_hook(void)
#else
on_pre_input_hook()
#endif
{
returnon_hook(pre_input_hook);
}
#endif
/* C function to call the Python completion_display_matches */
#ifdefHAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
staticvoid
on_completion_display_matches_hook(char**matches,
intnum_matches, intmax_length)
{
inti;
PyObject*m=NULL, *s=NULL, *r=NULL;
#ifdefWITH_THREAD
PyGILState_STATEgilstate=PyGILState_Ensure();
#endif
m=PyList_New(num_matches);
if (m==NULL)
goto error;
for (i=0; i<num_matches; i++) {
s=PyString_FromString(matches[i+1]);
if (s==NULL)
goto error;
PyList_SET_ITEM(m, i, s);
}
r=PyObject_CallFunction(completion_display_matches_hook,
"sOi", matches[0], m, max_length);
Py_DECREF(m); m=NULL;
if (r==NULL||
(r!=Py_None&&PyInt_AsLong(r) ==-1&&PyErr_Occurred())) {
goto error;
}
Py_XDECREF(r); r=NULL;
if (0) {
error:
PyErr_Clear();
Py_XDECREF(m);
Py_XDECREF(r);
}
#ifdefWITH_THREAD
PyGILState_Release(gilstate);
#endif
}
#endif
#ifdefHAVE_RL_RESIZE_TERMINAL
staticvolatilesig_atomic_tsigwinch_received;
staticPyOS_sighandler_tsigwinch_ohandler;
staticvoid
readline_sigwinch_handler(intsignum)
{
sigwinch_received=1;
if (sigwinch_ohandler&&
sigwinch_ohandler!=SIG_IGN&&sigwinch_ohandler!=SIG_DFL)
sigwinch_ohandler(signum);
#ifndefHAVE_SIGACTION
/* If the handler was installed with signal() rather than sigaction(),
we need to reinstall it. */
PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
#endif
}
#endif
/* C function to call the Python completer. */
staticchar*
on_completion(constchar*text, intstate)
{
char*result=NULL;
if (completer!=NULL) {
PyObject*r;
#ifdefWITH_THREAD
PyGILState_STATEgilstate=PyGILState_Ensure();
#endif
rl_attempted_completion_over=1;
r=PyObject_CallFunction(completer, "si", text, state);
if (r==NULL)
goto error;
if (r==Py_None) {
result=NULL;
}
else {
char*s=PyString_AsString(r);
if (s==NULL)
goto error;
result=strdup(s);
}
Py_DECREF(r);
goto done;
error:
PyErr_Clear();
Py_XDECREF(r);
done:
#ifdefWITH_THREAD
PyGILState_Release(gilstate);
#endif
returnresult;
}
returnresult;
}
/* A more flexible constructor that saves the "begidx" and "endidx"
* before calling the normal completer */
staticchar**
flex_complete(constchar*text, intstart, intend)
{
#ifdefHAVE_RL_COMPLETION_APPEND_CHARACTER
rl_completion_append_character='\0';
#endif
#ifdefHAVE_RL_COMPLETION_SUPPRESS_APPEND
rl_completion_suppress_append=0;
#endif
Py_XDECREF(begidx);
Py_XDECREF(endidx);
begidx=PyInt_FromLong((long) start);
endidx=PyInt_FromLong((long) end);
returncompletion_matches(text, *on_completion);
}
/* Helper to initialize GNU readline properly. */
staticvoid
setup_readline(void)
{
#ifdefSAVE_LOCALE
char*saved_locale=strdup(setlocale(LC_CTYPE, NULL));
if (!saved_locale)
Py_FatalError("not enough memory to save locale");
#endif
#ifdef__APPLE__
/* the libedit readline emulation resets key bindings etc
* when calling rl_initialize. So call it upfront
*/
if (using_libedit_emulation)
rl_initialize();
/* Detect if libedit's readline emulation uses 0-based
* indexing or 1-based indexing.
*/
add_history("1");
if (history_get(1) ==NULL) {
libedit_history_start=0;
} else {
libedit_history_start=1;
}
clear_history();
#endif/* __APPLE__ */
using_history();
rl_readline_name="python";
#if defined(PYOS_OS2) && defined(PYCC_GCC)
/* Allow $if term= in .inputrc to work */
rl_terminal_name=getenv("TERM");
#endif
/* Force rebind of TAB to insert-tab */
rl_bind_key('\t', rl_insert);
/* Bind both ESC-TAB and ESC-ESC to the completion function */
rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
#ifdefHAVE_RL_RESIZE_TERMINAL
/* Set up signal handler for window resize */
sigwinch_ohandler=PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
#endif
/* Set our hook functions */
rl_startup_hook=on_startup_hook;
#ifdefHAVE_RL_PRE_INPUT_HOOK
rl_pre_input_hook=on_pre_input_hook;
#endif
/* Set our completion function */
rl_attempted_completion_function=flex_complete;
/* Set Python word break characters */
completer_word_break_characters=
rl_completer_word_break_characters=
strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
/* All nonalphanums except '.' */
begidx=PyInt_FromLong(0L);
endidx=PyInt_FromLong(0L);
#ifdef__APPLE__
if (!using_libedit_emulation)
#endif
{
if (!isatty(STDOUT_FILENO)) {
/* Issue #19884: stdout is not a terminal. Disable meta modifier
keys to not write the ANSI sequence "\033[1034h" into stdout. On
terminals supporting 8 bit characters like TERM=xterm-256color
(which is now the default Fedora since Fedora 18), the meta key is
used to enable support of 8 bit characters (ANSI sequence
"\033[1034h").
With libedit, this call makes readline() crash. */
rl_variable_bind ("enable-meta-key", "off");
}
}
/* Initialize (allows .inputrc to override)
*
* XXX: A bug in the readline-2.2 library causes a memory leak
* inside this function. Nothing we can do about it.
*/
#ifdef__APPLE__
if (using_libedit_emulation)
rl_read_init_file(NULL);
else
#endif/* __APPLE__ */
rl_initialize();
RESTORE_LOCALE(saved_locale)
}
/* Wrapper around GNU readline that handles signals differently. */
#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
staticchar*completed_input_string;