-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGnu.pm
2339 lines (1617 loc) · 68.9 KB
/
Gnu.pm
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
#
# Gnu.pm --- The GNU Readline/History Library wrapper module
#
# Copyright (c) 1996-2023 Hiroo Hayashi. All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Some of documentation strings in this file are cited from the
# GNU Readline/History Library Manual.
package Term::ReadLine::Gnu;
=head1 NAME
Term::ReadLine::Gnu - Perl extension for the GNU Readline/History Library
=head1 SYNOPSIS
use Term::ReadLine; # Do not "use Term::ReadLine::Gnu;"
$term = new Term::ReadLine 'ProgramName';
while ( defined ($_ = $term->readline('prompt>')) ) {
...
}
=head1 DESCRIPTION
=head2 Overview
This is an implementation of
L<Term::ReadLine|http://search.cpan.org/dist/Term-ReadLine/> using
L<the GNU ReadlineE<sol>History
Library|https://tiswww.cwru.edu/php/chet/readline/rltop.html>.
For basic functions object oriented interface is provided. These are
described in the section L</"Standard Methods"> and
L</"C<Term::ReadLine::Gnu> Functions">.
This package also has the interface with the almost all functions and
variables which are documented in the GNU Readline/History Library
Manual. They are documented in the section
L</"C<Term::ReadLine::Gnu> Functions">
and
L</"C<Term::ReadLine::Gnu>
Variables"> briefly. For further details of the GNU Readline/History
Library, see L<GNU Readline Library
Manual|https://tiswww.cwru.edu/php/chet/readline/readline.html> and
L<GNU History Library
Manual|https://tiswww.cwru.edu/php/chet/readline/history.html>.
There are some C<Term::ReadLine::Gnu> original features. They are
described in the section L</"C<Term::ReadLine::Gnu> Specific
Features">
The sample programs under F<eg/> directory and test programs under
F<t/> directory in L<the C<Term::ReadLine::Gnu> distribution|http://search.cpan.org/dist/Term-ReadLine-Gnu/> include
many examples of this module.
=head2 Standard Methods
These are standard methods defined by
L<Term::ReadLine|http://search.cpan.org/dist/Term-ReadLine/>.
=cut
use strict;
use warnings;
use Carp;
# use version TRG-1.22 for perl 5.7.x, or TRG-1.09 for older Perl
use 5.8.1;
# This module can't be loaded directly.
BEGIN {
if (not defined $Term::ReadLine::VERSION) {
croak <<END;
It is invalid to load Term::ReadLine::Gnu directly. Please consult
the Term::ReadLine documentation for more information.
END
}
}
BEGIN {
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=99843
$ENV{TERM} = 'dumb' unless defined($ENV{TERM});
# Use Term::ReadLine::Stub in Emacs
# as bash does not do line-editing in the case.
# https://rt.cpan.org/Ticket/Display.html?id=123398
# https://github.com/hirooih/perl-trg/issues/11
# https://github.com/hirooih/perl-trg/issues/28
# https://git.savannah.gnu.org/cgit/bash.git/tree/shell.c#n595
my $in_emacs = defined($ENV{INSIDE_EMACS})
|| (defined($ENV{EMACS})
&& ($ENV{EMACS} =~ / \(term:/ || $ENV{EMACS} eq "t"));
if ($ENV{TERM} eq "emacs" || $in_emacs && $ENV{TERM} eq "dumb") {
croak "Use Term::ReadLine::Stub.";
}
}
{
use Exporter ();
use DynaLoader;
our $VERSION = '1.46'; # update Gnu::XS::VERSION also.
# Term::ReadLine::Gnu::AU makes a function in
# `Term::ReadLine::Gnu::XS' as a method.
# The namespace of Term::ReadLine::Gnu::AU is searched before ones
# of other classes
our @ISA = qw(Term::ReadLine::Gnu::AU Term::ReadLine::Stub
Exporter DynaLoader);
our %EXPORT_TAGS = (
readerr => [qw(READERR)],
prompt => [qw(RL_PROMPT_START_IGNORE RL_PROMPT_END_IGNORE)],
match_type => [qw(NO_MATCH SINGLE_MATCH MULT_MATCH)],
keymap_type => [qw(ISFUNC ISKMAP ISMACR)],
undo_code => [qw(UNDO_DELETE UNDO_INSERT UNDO_BEGIN UNDO_END)],
rl_state => [qw(RL_STATE_NONE RL_STATE_INITIALIZING
RL_STATE_INITIALIZED RL_STATE_TERMPREPPED
RL_STATE_READCMD RL_STATE_METANEXT
RL_STATE_DISPATCHING RL_STATE_MOREINPUT
RL_STATE_ISEARCH RL_STATE_NSEARCH
RL_STATE_SEARCH RL_STATE_NUMERICARG
RL_STATE_MACROINPUT RL_STATE_MACRODEF
RL_STATE_OVERWRITE RL_STATE_COMPLETING
RL_STATE_SIGHANDLER RL_STATE_UNDOING
RL_STATE_INPUTPENDING RL_STATE_TTYCSAVED
RL_STATE_CALLBACK RL_STATE_VIMOTION
RL_STATE_MULTIKEY RL_STATE_VICMDONCE
RL_STATE_CHARSEARCH RL_STATE_REDISPLAYING
RL_STATE_DONE RL_STATE_TIMEOUT
RL_STATE_EOF
)],
);
Exporter::export_ok_tags('readerr');
Exporter::export_ok_tags('prompt');
Exporter::export_ok_tags('match_type');
Exporter::export_ok_tags('keymap_type');
Exporter::export_ok_tags('undo_code');
Exporter::export_ok_tags('rl_state');
bootstrap Term::ReadLine::Gnu $VERSION; # DynaLoader
}
require Term::ReadLine::Gnu::XS;
# Global Variables
our($readline_version);
# Each variable in the GNU Readline Library is tied to an entry of
# this hash (%Attribs). By accessing the hash entry, you can read
# and/or write the variable in the GNU Readline Library. See the
# package definition of Term::ReadLine::Gnu::Var and following code
# for further details.
# Normal (non-tied) entries
our %Attribs = (
MinLength => 1,
do_expand => 0,
completion_word => [],
term_set => ['', '', '', ''],
);
our %Features = (
appname => 1, minline => 1, autohistory => 1,
getHistory => 1, setHistory => 1, addHistory => 1,
readHistory => 1, writeHistory => 1,
preput => 1, attribs => 1, newTTY => 1,
tkRunning => Term::ReadLine::Stub->Features->{'tkRunning'},
ornaments => Term::ReadLine::Stub->Features->{'ornaments'},
stiflehistory => 1,
);
#
# GNU Readline/History Library constant definition
# These are included in @EXPORT_OK.
# I can define these variables in XS code to use the value defined in
# readline.h, etc. But it needs some calling convention change and
# will cause compatiblity problem. I hope the definition of these
# constant value will not be changed.
# Input error; can be returned by (*rl_getc_function) if readline is reading
# a top-level command (RL_ISSTATE (RL_STATE_READCMD)).
sub READERR { -2; }
# for non-printing characters in prompt string
sub RL_PROMPT_START_IGNORE { "\001"; }
sub RL_PROMPT_END_IGNORE { "\002"; }
# for rl_filename_quoting_function
sub NO_MATCH { 0; }
sub SINGLE_MATCH { 1; }
sub MULT_MATCH { 2; }
# for rl_generic_bind, rl_function_of_keyseq
sub ISFUNC { 0; }
sub ISKMAP { 1; }
sub ISMACR { 2; }
# for rl_add_undo
sub UNDO_DELETE { 0; }
sub UNDO_INSERT { 1; }
sub UNDO_BEGIN { 2; }
sub UNDO_END { 3; }
# for rl_readline_state which was implemented since 4.2
sub RL_STATE_NONE { 0x00000; } # no state; before first call
sub RL_STATE_INITIALIZING { 0x00001; } # initializing
sub RL_STATE_INITIALIZED { 0x00002; } # initialization done
sub RL_STATE_TERMPREPPED { 0x00004; } # terminal is prepped
sub RL_STATE_READCMD { 0x00008; } # reading a command key
sub RL_STATE_METANEXT { 0x00010; } # reading input after ESC
sub RL_STATE_DISPATCHING { 0x00020; } # dispatching to a command
sub RL_STATE_MOREINPUT { 0x00040; } # reading more input in a command function
sub RL_STATE_ISEARCH { 0x00080; } # doing incremental search
sub RL_STATE_NSEARCH { 0x00100; } # doing non-inc search
sub RL_STATE_SEARCH { 0x00200; } # doing a history search
sub RL_STATE_NUMERICARG { 0x00400; } # reading numeric argument
sub RL_STATE_MACROINPUT { 0x00800; } # getting input from a macro
sub RL_STATE_MACRODEF { 0x01000; } # defining keyboard macro
sub RL_STATE_OVERWRITE { 0x02000; } # overwrite mode
sub RL_STATE_COMPLETING { 0x04000; } # doing completion
sub RL_STATE_SIGHANDLER { 0x08000; } # in readline sighandler
sub RL_STATE_UNDOING { 0x10000; } # doing an undo
sub RL_STATE_INPUTPENDING { 0x02_0000; } # rl_execute_next called
sub RL_STATE_TTYCSAVED { 0x04_0000; } # tty special chars saved [5.0]
sub RL_STATE_CALLBACK { 0x08_0000; } # using the callback interface [5.1]
sub RL_STATE_VIMOTION { 0x10_0000; } # reading vi motion arg [5.1]
sub RL_STATE_MULTIKEY { 0x20_0000; } # reading multiple-key command [5.1]
sub RL_STATE_VICMDONCE { 0x40_0000; } # entered vi command mode at least once [5.1]
sub RL_STATE_CHARSEARCH { 0x80_0000; } # vi mode char search [7.0]
sub RL_STATE_REDISPLAYING { # updating terminal display [6.1]
$readline_version < 0x0700 ? 0x80_0000 : 0x100_0000;
}
sub RL_STATE_DONE { # done; accepted line
$readline_version < 0x0501 ? 0x8_0000 :
($readline_version < 0x0601 ? 0x80_0000 :
($readline_version < 0x0700 ? 0x100_0000 : 0x200_0000));
}
sub RL_STATE_TIMEOUT { 0x400_0000; } # [8.2]
sub RL_STATE_EOF { 0x800_0000; } # [8.2]
#
# Methods Definition
#
=over 4
=item C<ReadLine>
returns the actual package that executes the commands. If
this package is being used, C<Term::ReadLine::Gnu> is returned.
=cut
sub ReadLine { 'Term::ReadLine::Gnu'; }
=item C<new(NAME,[IN,OUT])>
returns the handle for subsequent calls to following functions.
Argument is the name of the application. Optionally can be followed
by two arguments for C<IN> and C<OUT> file handles. These arguments
should be globs.
=cut
# The origin of this function is Term::ReadLine::Perl.pm by Ilya Zakharevich.
our $has_been_initialized = 0;
sub new {
my $this = shift; # Package
my $class = ref($this) || $this;
# Debian Bug Report #204362
croak "Wrong number of arguments" unless @_ == 1 or @_ == 3;
my $name = shift;
my $self = \%Attribs;
bless $self, $class;
if ($has_been_initialized) {
croak "Only one Term::ReadLine::Gnu instance is allowed."
}
$has_been_initialized = 1;
# set rl_readline_name before .inputrc is read in rl_initialize()
$Attribs{readline_name} = $name;
# on MSWin32 setting $ENV{TERM} does not affect on getenv() in XS
if ($^O eq 'MSWin32') {
$Attribs{terminal_name} = $ENV{TERM};
}
# some version of Perl cause segmentation fault, if XS module
# calls setenv() before the 1st assignment to $ENV{}.
$ENV{_TRL_DUMMY} = '';
# UTF-8 condition conpatible with Term:ReadLine
$Attribs{utf8_mode} ||= ${^UNICODE} & 1 || defined ${^ENCODING};
#printf "\${^UNICODE}: 0x%X, ", ${^UNICODE};
#print "\${^ENCODING}: ", defined ${^ENCODING} ? 'defined' : 'undef', "\n";
# set tty before calling rl_initialize() not to output some
# charactores to STDIO.
# https://rt.cpan.org/Ticket/Display.html?id=96569
if (!@_) {
my ($in, $out) = $self->findConsole();
open(my $IN,"<$in") || croak "Cannot open $in for read";
open(my $OUT,">$out") || croak "Cannot open $out for write";
if ($Attribs{utf8_mode}) {
binmode $IN, ':encoding(UTF-8)'; # not necessary
binmode $OUT, ':encoding(UTF-8)';
}
$self->newTTY($IN, $OUT);
} else {
# enable UTF-8 mode if input stream has the utf8 layer.
my @layers = PerlIO::get_layers($_[0]);
$Attribs{utf8_mode} ||= ($layers[$#layers] eq 'utf8');
$self->newTTY(@_);
}
# initialize the GNU Readline Library and termcap library
# This calls tgetent().
$self->initialize();
# enable ornaments to be compatible with perl5.004_05(?)
# This calls tgetstr().
$self->ornaments(1) unless ($ENV{PERL_RL} and $ENV{PERL_RL} =~ /\bo\w*=0/);
# keep rl_readline_version value for efficiency
$readline_version = $Attribs{readline_version};
# bind operate-and-get-next to \C-o by default for the compatibility
# with bash and Term::ReadLine::Perl
# GNU Readline 8.1 and later support operate-and-get-next natively.
Term::ReadLine::Gnu::XS::rl_add_defun('operate-and-get-next',
\&Term::ReadLine::Gnu::XS::operate_and_get_next, ord "\co")
if ($readline_version < 0x801);
$self;
}
sub DESTROY {}
=item C<readline(PROMPT[,PREPUT])>
gets an input line, with actual C<GNU Readline> support. Trailing
newline is removed. Returns C<undef> on C<EOF>. C<PREPUT> is an
optional argument meaning the initial value of input.
The optional argument C<PREPUT> is granted only if the value C<preput>
is in C<Features>.
C<PROMPT> may include some escape sequences. Use
C<RL_PROMPT_START_IGNORE> to begin a sequence of non-printing
characters, and C<RL_PROMPT_END_IGNORE> to end the sequence.
=cut
# to peacify -w
$Term::ReadLine::registered = $Term::ReadLine::registered;
sub readline { # should be ReadLine
my $self = shift;
my ($prompt, $preput) = @_;
# A contributed fix for Perl debugger
# make sure the outstream fd inside the readline library is
# in sync (see http://bugs.debian.org/236018)
# This is not a real fix but left for system where this fix works.
# Here is the real fix for perl5db.pl.
# https://rt.perl.org/Public/Bug/Display.html?id=121456
$Attribs{outstream} = $Attribs{outstream};
# ornament support (now prompt only)
$prompt = ${$Attribs{term_set}}[0] . $prompt . ${$Attribs{term_set}}[1];
# `completion_function' support for compatibility with
# Term:ReadLine::Perl. Prefer $completion_entry_function, since a
# program which uses $completion_entry_function should know
# Term::ReadLine::Gnu and have better completion function using
# the variable.
$Attribs{completion_entry_function} = $Attribs{_trp_completion_function}
if (!defined $Attribs{completion_entry_function}
&& defined $Attribs{completion_function});
# TkRunning support
if (not $Term::ReadLine::registered and $Term::ReadLine::toloop
and defined &Tk::DoOneEvent) {
$self->register_Tk;
$Attribs{getc_function} = $Attribs{Tk_getc};
}
# call readline()
my $line;
if (defined $preput) {
my $saved_startup_hook = $Attribs{startup_hook};
$Attribs{startup_hook} = sub {
$self->rl_insert_text($preput);
&$saved_startup_hook
if defined $saved_startup_hook;
};
$line = $self->rl_readline($prompt);
$Attribs{startup_hook} = $saved_startup_hook;
} else {
$line = $self->rl_readline($prompt);
}
return undef unless defined $line;
# history expansion
if ($Attribs{do_expand}) {
my $result;
($result, $line) = $self->history_expand($line);
my $outstream = $Attribs{outstream};
print $outstream "$line\n" if ($result);
# return without adding line into history
if ($result < 0 || $result == 2) {
return ''; # don't return `undef' which means EOF.
}
}
# add to history buffer
$self->add_history($line)
if (defined $self->{MinLength} && $self->{MinLength} > 0
&& length($line) >= $self->{MinLength});
return $line;
}
=item C<AddHistory(LINE1, LINE2, ...)>
adds the lines to the history of input, from where it can be used if
the actual C<readline> is present.
=cut
#use vars '*addhistory';
*addhistory = \&AddHistory; # for backward compatibility
sub AddHistory {
my $self = shift;
foreach (@_) {
$self->add_history($_);
}
}
=item C<IN>, C<OUT>
return the file handles for input and output or C<undef> if
C<readline> input and output cannot be used for Perl.
=cut
sub IN { $Attribs{instream}; }
sub OUT { $Attribs{outstream}; }
=item C<MinLine([MAX])>
If argument C<MAX> is specified, it is an advice on minimal size of
line to be included into history. C<undef> means do not include
anything into history. Returns the old value.
=cut
sub MinLine {
my $self = shift;
my $old_minlength = $self->{MinLength};
$self->{MinLength} = shift;
$old_minlength;
}
=item C<findConsole>
returns an array with two strings that give most appropriate names for
files for input and output using conventions C<"E<lt>$in">, C<"E<gt>$out">.
=cut
# findConsole is defined in ReadLine.pm.
=item C<Attribs>
returns a reference to a hash which describes internal configuration
(variables) of the package. Names of keys in this hash conform to
standard conventions with the leading C<rl_> stripped.
See section L</"C<Term::ReadLine::Gnu> Variables"> for supported variables.
=cut
sub Attribs { \%Attribs; }
=item C<Features>
Returns a reference to a hash with keys being features present in
current implementation. Several optional features are used in the
minimal interface: C<appname> should be present if the first argument
to C<new> is recognized, and C<minline> should be present if
C<MinLine> method is not dummy. C<autohistory> should be present if
lines are put into history automatically (maybe subject to
C<MinLine>), and C<addHistory> if C<AddHistory> method is not dummy.
C<preput> means the second argument to C<readline> method is processed.
C<getHistory> and C<setHistory> denote that the corresponding methods are
present. C<tkRunning> denotes that a Tk application may run while ReadLine
is getting input.
=cut
sub Features { \%Features; }
=item C<tkRunning>
makes Tk event loop run when waiting for user input (i.e., during
C<readline> method).
=cut
# tkRunning is defined in ReadLine.pm.
=item C<event_loop>
See the description of C<event_loop> on
L<Term::ReadLine|http://search.cpan.org/dist/Term-ReadLine/>.
=item C<ornaments>
makes the command line stand out by using termcap data. The argument
to C<ornaments> should be 0, 1, or a string of a form
C<"aa,bb,cc,dd">. Four components of this string should be names of
I<terminal capacities>, first two will be issued to make the prompt
standout, last two to make the input line standout.
=cut
sub ornaments {
my $self = shift;
return Term::ReadLine::Gnu::XS::ornaments(@_);
}
=item C<newTTY>
takes two arguments which are input filehandle and output filehandle.
Switches to use these filehandles.
=cut
# used by a program (ex. perldb5.pl) who changes input/output stream.
sub newTTY {
my ($self, $in, $out) = @_;
# borrowed from Term/ReadLine.pm
my $sel = select($out);
$| = 1; # for DB::OUT
select($sel);
$Attribs{instream} = $in;
$Attribs{outstream} = $out;
}
=item C<enableUTF8>
Enables UTF-8 support.
If STDIN is in UTF-8 by the C<-C> command-line switch or
C<PERL_UNICODE> environment variable, or C<IN> file handle has C<utf8>
IO layer, then UTF-8 support is also enabled. In other cases you need
this C<enableUTF8> method.
This is an original method of C<Term::ReadLine:Gnu>.
=cut
sub enableUTF8 {
my $self = shift;
$Attribs{utf8_mode} = 1;
binmode $self->IN, ':encoding(UTF-8)'; # not necessary
binmode $self->OUT, ':encoding(UTF-8)';
}
=back
=cut
# documented later
sub CallbackHandlerInstall {
my $self = shift;
my ($prompt, $lhandler) = @_;
$Attribs{_callback_handler} = $lhandler;
# ornament support (now prompt only)
$prompt = ${$Attribs{term_set}}[0] . $prompt . ${$Attribs{term_set}}[1];
$Attribs{completion_entry_function} = $Attribs{_trp_completion_function}
if (!defined $Attribs{completion_entry_function}
&& defined $Attribs{completion_function});
$self->rl_callback_handler_install($prompt,
\&Term::ReadLine::Gnu::XS::_ch_wrapper);
}
#
# Additional Supported Methods
#
# Documentation is after '__END__' for efficiency.
# for backward compatibility
#use vars qw(*AddDefun *BindKey *UnbindKey *ParseAndBind *StifleHistory);
*AddDefun = \&add_defun;
*BindKey = \&bind_key;
*UnbindKey = \&unbind_key;
*ParseAndBind = \&parse_and_bind;
*StifleHistory = \&stifle_history;
sub SetHistory {
my $self = shift;
$self->clear_history();
$self->AddHistory(@_);
}
sub GetHistory {
my $self = shift;
$self->history_list();
}
sub ReadHistory {
my $self = shift;
! $self->read_history_range(@_);
}
sub WriteHistory {
my $self = shift;
! $self->write_history(@_);
}
#
# Access Routines for GNU Readline/History Library Variables
#
package Term::ReadLine::Gnu::Var;
use Carp;
use strict;
use warnings;
our %_rl_vars;
%_rl_vars
= (
rl_line_buffer => ['S', 0],
rl_prompt => ['S', 1],
rl_library_version => ['S', 2],
rl_terminal_name => ['S', 3],
rl_readline_name => ['S', 4],
rl_basic_word_break_characters => ['S', 5],
rl_basic_quote_characters => ['S', 6],
rl_completer_word_break_characters => ['S', 7],
rl_completer_quote_characters => ['S', 8],
rl_filename_quote_characters => ['S', 9],
rl_special_prefixes => ['S', 10],
history_no_expand_chars => ['S', 11],
history_search_delimiter_chars => ['S', 12],
rl_executing_macro => ['S', 13], # GRL 4.2
history_word_delimiters => ['S', 14], # GRL 4.2
rl_display_prompt => ['S', 15], # GRL 6.0
rl_executing_keyseq => ['S', 16], # GRL 6.3
rl_point => ['I', 0],
rl_end => ['I', 1],
rl_mark => ['I', 2],
rl_done => ['I', 3],
rl_pending_input => ['I', 4],
rl_completion_query_items => ['I', 5],
rl_completion_append_character => ['C', 6],
rl_ignore_completion_duplicates => ['I', 7],
rl_filename_completion_desired => ['I', 8],
rl_filename_quoting_desired => ['I', 9],
rl_inhibit_completion => ['I', 10],
history_base => ['I', 11],
history_length => ['I', 12],
history_max_entries => ['I', 13],
max_input_history => ['I', 13], # before GRL 4.2
history_write_timestamps => ['I', 14], # GRL 5.0
history_expansion_char => ['C', 15],
history_subst_char => ['C', 16],
history_comment_char => ['C', 17],
history_quotes_inhibit_expansion => ['I', 18],
rl_erase_empty_line => ['I', 19], # GRL 4.0
rl_catch_signals => ['I', 20], # GRL 4.0
rl_catch_sigwinch => ['I', 21], # GRL 4.0
rl_already_prompted => ['I', 22], # GRL 4.1
rl_num_chars_to_read => ['I', 23], # GRL 4.1
rl_dispatching => ['I', 24], # GRL 4.2
rl_gnu_readline_p => ['I', 25], # GRL 4.1
rl_readline_state => ['I', 26], # GRL 4.2
rl_explicit_arg => ['I', 27], # GRL 4.2
rl_numeric_arg => ['I', 28], # GRL 4.2
rl_editing_mode => ['I', 29], # GRL 4.2
rl_attempted_completion_over => ['I', 30], # GRL 4.2
rl_completion_type => ['I', 31], # GRL 4.2
rl_readline_version => ['I', 32], # GRL 4.2a
rl_completion_suppress_append => ['I', 33], # GRL 4.3
rl_completion_quote_character => ['C', 34], # GRL 5.0
rl_completion_suppress_quote => ['I', 35], # GRL 5.0
rl_completion_found_quote => ['I', 36], # GRL 5.0
rl_completion_mark_symlink_dirs => ['I', 37], # GRL 4.3
rl_prefer_env_winsize => ['I', 38], # GRL 5.1
rl_sort_completion_matches => ['I', 39], # GRL 6.0
rl_completion_invoking_key => ['C', 40], # GRL 6.0
rl_executing_key => ['I', 41], # GRL 6.3
rl_key_sequence_length => ['I', 42], # GRL 6.3
rl_change_environment => ['I', 43], # GRL 6.3
rl_persistent_signal_handlers => ['I', 44], # GRL 7.0
history_quoting_state => ['I', 45], # GRL 8.0
utf8_mode => ['I', 46], # internal
rl_eof_found => ['I', 47], # GRL 8.2
rl_startup_hook => ['F', 0],
rl_event_hook => ['F', 1],
rl_getc_function => ['F', 2],
rl_redisplay_function => ['F', 3],
rl_completion_entry_function => ['F', 4],
rl_attempted_completion_function => ['F', 5],
rl_filename_quoting_function => ['F', 6],
rl_filename_dequoting_function => ['F', 7],
rl_char_is_quoted_p => ['F', 8],
rl_ignore_some_completions_function => ['F', 9],
rl_directory_completion_hook => ['F', 10],
history_inhibit_expansion_function => ['F', 11],
rl_pre_input_hook => ['F', 12], # GRL 4.0
rl_completion_display_matches_hook => ['F', 13], # GRL 4.0
rl_completion_word_break_hook => ['F', 14], # GRL 5.0
rl_prep_term_function => ['F', 15], # GRL 4.2
rl_deprep_term_function => ['F', 16], # GRL 4.2
rl_directory_rewrite_hook => ['F', 17], # GRL 4.2
rl_filename_rewrite_hook => ['F', 18], # GRL 6.1
rl_signal_event_hook => ['F', 19], # GRL 6.3
rl_input_available_hook => ['F', 20], # GRL 6.3
rl_filename_stat_hook => ['F', 21], # GRL 6.3
rl_timeout_event_hook => ['F', 22], # GRL 8.2
rl_instream => ['IO', 0],
rl_outstream => ['IO', 1],
rl_executing_keymap => ['K', 0],
rl_binding_keymap => ['K', 1],
rl_last_func => ['LF', 0],
);
my @stream;
sub TIESCALAR {
my $class = shift;
my $name = shift;
return bless \$name, $class;
}
sub FETCH {
my $self = shift;
confess "wrong type" unless ref $self;
my $name = $$self;
if (! defined $_rl_vars{$name}) {
confess "Term::ReadLine::Gnu::Var::FETCH: Unknown variable name `$name'\n";
return undef ;
}
my ($type, $id) = @{$_rl_vars{$name}};
if ($type eq 'S') {
return _rl_fetch_str($id);
} elsif ($type eq 'I') {
return _rl_fetch_int($id);
} elsif ($type eq 'C') {
return chr(_rl_fetch_int($id));
} elsif ($type eq 'F') {
return _rl_fetch_function($id);
} elsif ($type eq 'IO') {
# STORE was called in new() before coming here
return $stream[$id];
} elsif ($type eq 'K') {
return _rl_fetch_keymap($id);
} elsif ($type eq 'LF') {
return _rl_fetch_last_func();
} else {
carp "Term::ReadLine::Gnu::Var::FETCH: Illegal type `$type'\n";
return undef;
}
}
sub STORE {
my $self = shift;
confess "wrong type" unless ref $self;
my $name = $$self;
if (! defined $_rl_vars{$name}) {
confess "Term::ReadLine::Gnu::Var::STORE: Unknown variable name `$name'\n";
return undef ;
}
my $value = shift;
my ($type, $id) = @{$_rl_vars{$name}};
if ($type eq 'S') {
if ($name eq 'rl_line_buffer') {
return _rl_store_rl_line_buffer($value);
} else {
return _rl_store_str($value, $id);
}
} elsif ($type eq 'I') {
return _rl_store_int($value, $id);
} elsif ($type eq 'C') {
return chr(_rl_store_int(ord($value), $id));
} elsif ($type eq 'F') {
return _rl_store_function($value, $id);
} elsif ($type eq 'IO') {
_rl_store_iostream($value, $id);
# _rl_store_iostream() calls PerlIO_findFILE(). It pushes the
# 'stdio' layer on perl 5.10 and later. We must pop the stdio
# layer.
# https://rt.cpan.org/Ticket/Display.html?id=59832
# But we must pop the 'stdio' layer only when utf8 layer is
# included for remote debugging.
# https://rt.cpan.org/Ticket/Display.html?id=110121
if ($] >= 5.010) {
my @layers = PerlIO::get_layers($value);
if ((grep /^utf8$/, @layers) > 0 && $layers[$#layers] eq 'stdio') {
binmode($value, ":pop");
}
}
return $stream[$id] = $value;
} elsif ($type eq 'K' || $type eq 'LF') {
carp "Term::ReadLine::Gnu::Var::STORE: read only variable `$name'\n";
return undef;
} else {
carp "Term::ReadLine::Gnu::Var::STORE: Illegal type `$type'\n";
return undef;
}
}
package Term::ReadLine::Gnu;
use Carp;
use strict;
use warnings;
#
# set value of %Attribs
#
# Tie all Readline/History variables
foreach (keys %Term::ReadLine::Gnu::Var::_rl_vars) {
my $name;
($name = $_) =~ s/^rl_//; # strip leading `rl_'
tie $Attribs{$name}, 'Term::ReadLine::Gnu::Var', $_;
}
# add reference to some functions
{
my ($name, $fname);
no strict 'refs'; # allow symbolic reference
map {
($name = $_) =~ s/^rl_//; # strip leading `rl_'
$fname = 'Term::ReadLine::Gnu::XS::' . $_;
$Attribs{$name} = \&$fname; # symbolic reference
} qw(rl_getc
rl_redisplay
rl_callback_read_char
rl_display_match_list
rl_filename_completion_function
rl_username_completion_function
list_completion_function
_trp_completion_function);
# auto-splited subroutines cannot be processed in the map loop above
use strict 'refs';
$Attribs{shadow_redisplay} = \&Term::ReadLine::Gnu::XS::shadow_redisplay;
$Attribs{Tk_getc} = \&Term::ReadLine::Gnu::XS::Tk_getc;
$Attribs{list_completion_function} = \&Term::ReadLine::Gnu::XS::list_completion_function;
}
package Term::ReadLine::Gnu::AU;
use Carp;
no strict qw(refs vars);
use warnings;
sub AUTOLOAD {
{ $AUTOLOAD =~ s/.*:://; } # preserve match data
my $name;
if (exists $Term::ReadLine::Gnu::XS::{"rl_$AUTOLOAD"}) {
$name = "Term::ReadLine::Gnu::XS::rl_$AUTOLOAD";
} elsif (exists $Term::ReadLine::Gnu::XS::{"$AUTOLOAD"}) {
$name = "Term::ReadLine::Gnu::XS::$AUTOLOAD";
} else {
croak "Cannot do `$AUTOLOAD' in Term::ReadLine::Gnu";
}
no warnings 'redefine'; # Why is this line necessary ???
*$AUTOLOAD = sub { shift; &$name(@_); };
goto &$AUTOLOAD;
}
1;
__END__
=head2 C<Term::ReadLine::Gnu> Functions
All these GNU Readline/History Library functions supported are callable via
method interface and have names which conform to standard conventions
with the leading C<rl_> stripped. For example C<rl_foo()>
function is called as C<$term-E<gt>foo()>.
The titles of the following sections are same as the titles of the
corresponding sections in the "Programming with GNU Readline" section
in the L<GNU Readline Library
Manual|https://tiswww.cwru.edu/php/chet/readline/readline.html>.
Refer them for further details.
Although it is preferred to use method interface, most methods have
lower level functions in
C<Term::ReadLine::Gnu::XS> package. To use them a full qualified name
is required.
=head3 Basic Behavior
The function C<readline()> prints a prompt and then reads and returns
a single line of text from the user.
$_ = $term->readline('Enter a line: ');
You can change key-bindings using C<bind_key(KEY, FUNCTION [,MAP])>
function. The first argument, C<KEY>, is the character that you want
bind. The second argument, C<FUNCTION>, is the function to call when
C<KEY> is pressed. The C<FUNCTION> can be a reference to a Perl
function (see L</"Custom Functions">) or a "named function" named by
C<add_defun()> function or commands described in the "Bindable
Readline Commands" section in the L<GNU Readline Library
Manual|https://tiswww.cwru.edu/php/chet/readline/readline.html>.
$term->bind_key(ord "\ci, 'tab-insert');
The above example binds Control-I to the 'tab-insert' command.
=head3 Custom Functions
You can write new functions using Perl. The calling sequence for a
command foo looks like
sub foo ($count, $key) { ... }
where C<$count> is the numeric argument (or 1 if defaulted) and
C<$key> is the key that invoked this function.
Here is an example;
sub reverse_line { # reverse a whole line
my($count, $key) = @_; # ignored in this sample function
$t->modifying(0, $a->{end}); # save undo information
$a->{line_buffer} = reverse $a->{line_buffer};
}
See the "Writing a New Function" section in the L<GNU Readline Library
Manual|https://tiswww.cwru.edu/php/chet/readline/readline.html> for
further details.
=head3 Readline Convenience Functions
=head4 Naming a Function
=over 4
=item C<add_defun(NAME, FUNCTION [,KEY=-1])>
Add name to a Perl function C<FUNCTION>. If optional argument C<KEY>
is specified, bind it to the C<FUNCTION>. Returns reference to
C<FunctionPtr>.
Example:
# name `reverse-line' to a function reverse_line(),
# and bind it to "\C-t"
$term->add_defun('reverse-line', \&reverse_line, ord "\ct");
=back
=head4 Selecting a Keymap
=over 4
=item C<make_bare_keymap>
Keymap rl_make_bare_keymap()
=item C<copy_keymap(MAP)>
Keymap rl_copy_keymap(Keymap|str map)
=item C<make_keymap>
Keymap rl_make_keymap()
=item C<discard_keymap(MAP)>