Debian Codegraph @

eg/perlsh

raw
1 #!/usr/bin/env perl
2 #
3 #
4 # Copyright (c) 1996 Hiroo Hayashi. All Rights Reserved.
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the same terms as Perl itself.
8
9 =head1 NAME
10
11 perlsh - one-line perl evaluator with line editing function and
12 variable name completion function
13
14 =head1 SYNOPSIS
15
16 perlsh
17
18 =head1 DESCRIPTION
19
20 This program reads input a line, and evaluates it by perl interpreter,
21 and prints the result. If the result is a list value then each value
22 of the list is printed line by line. This program can be used as a
23 very strong calculator which has whole perl functions.
24
25 This is a sample program Term::ReadLine::Gnu module. When you input a
26 line, the line editing function of GNU Readline Library is available.
27 Perl symbol name completion function is also available.
28
29 =cut
30
31 package PerlSh;
32
33 use strict;
34 use warnings;
35 use Term::ReadLine;
36 use POSIX; # for sigaction below
37
38 use vars qw($PS1 $PS2 $HISTFILE $HISTSIZE $INPUTRC $STRICT
39 $HOSTNAME $LOGNAME $CWP);
40
41 #$PS1 = '$ ';
42 $PS1='\w[\!]$ ';
43 $PS2 = '> ';
44 $HISTFILE = ($ENV{HOME} || ((getpwuid($<))[7])) . "/.perlsh_history";
45 $HISTSIZE = 256;
46 $INPUTRC = ($ENV{HOME} || ((getpwuid($<))[7])) . "/.perlshrc";
47 $STRICT = 0;
48
49 $HOSTNAME = $ENV{HOSTNAME};
50 $LOGNAME = $ENV{LOGNAME};
51 $CWP = 'main'; # current working package
52
53 package main;
54 if (-f $PerlSh::INPUTRC) {
55 do $PerlSh::INPUTRC;
56 }
57
58 package PerlSh;
59
60 use vars qw($term $attribs); # to access as `$PerlSh::term' from prompt
61 $term = new Term::ReadLine 'PerlSh';
62 $attribs = $term->Attribs;
63
64 $term->bind_key(ord "^", 'history-expand-line', 'emacs-meta');
65 $term->bind_key(ord "\cv", 'display-readline-version', 'emacs-ctlx');
66 $term->bind_key(ord "\cc", 'abort'); # not works yet FIXME!!!
67
68 if (defined &main::afterinit) {
69 package main;
70 &afterinit;
71 package PerlSh;
72 }
73
74 &toplevel; # never returns
75
76 ########################################################################
77 sub toplevel {
78 # disable implicit add_history() call
79 $term->MinLine(undef);
80
81 $term->stifle_history($HISTSIZE);
82 if (-f $HISTFILE) {
83 $term->ReadHistory($HISTFILE)
84 or warn "perlsh: cannot read history file: $!\n";
85 }
86 $attribs->{attempted_completion_function} = \&attempt_perl_completion;
87 $attribs->{special_prefixes} = '$@%&';
88 $attribs->{completion_display_matches_hook}
89 = \&perl_symbol_display_match_list;
90
91 # See http://perldoc.perl.org/perlipc.html#Deferred-Signals-%28Safe-Signals%29
92 # was '$SIG{INT} = sub { ...'
93 sigaction SIGINT, new POSIX::SigAction sub {
94 $term->modifying;
95 $term->delete_text;
96 $attribs->{point} = $attribs->{end} = 0;
97 $term->redisplay;
98 } or die "Error setting SIGINT handler: $!\n";
99
100 my ($strict, $command, @result);
101 $strict = $STRICT ? '' : 'no strict;';
102 while (defined($command = &reader)) {
103 @result = eval ("$strict package $CWP; $command");
104 use strict;
105 if ($@) { print "Error: $@\n"; next; }
106 printer (@result);
107 $CWP = $1 if ($command =~ /^\s*package\s+([\w:]+)/);
108 }
109 &quit;
110 }
111
112 sub sigint {
113 $term->modifying;
114 $term->delete_text;
115 $attribs->{point} = $attribs->{end} = 0;
116 $term->redisplay;
117 }
118
119 sub quit {
120 $term->WriteHistory($HISTFILE)
121 or warn "perlsh: cannot write history file: $!\n";
122 exit (0);
123 }
124
125 sub reader {
126 my ($line, $command);
127 $command = '';
128 while (1) {
129 $line = $term->readline($command ? $PS2 : prompt($PS1));
130 return undef unless (defined $line);
131
132 if ($line =~ /\\$/) {
133 chop $line;
134 $command = $command ? $command . " $line" : $line;
135 } else {
136 $command = $command ? $command . " $line" : $line;
137 $term->addhistory($command) if (length($command) > 0);
138 return $command;
139 }
140 }
141 }
142
143 sub printer {
144 my (@res) = @_;
145 my ($i);
146 foreach $i (@res) { print "$i\n"; }
147 }
148
149 sub prompt {
150 local($_) = @_;
151 # if reference to a subroutine return the return value of it
152 return &$_ if (ref($_) eq 'CODE');
153
154 # \h: hostname, \u: username, \w: package name, \!: history number
155 s/\\h/$HOSTNAME/g;
156 s/\\u/$LOGNAME/g;
157 s/\\w/$CWP/g;
158 s/\\!/$attribs->{history_base} + $attribs->{history_length}/eg;
159 $_;
160 }
161
162 #
163 # custom completion for Perl
164 #
165
166 sub perl_symbol_display_match_list ($$$) {
167 my($matches, $num_matches, $max_length) = @_;
168 map { $_ =~ s/^((\$#|[\@\$%&])?).*::(.+)/$3/; }(@{$matches});
169 $term->display_match_list($matches);
170 $term->forced_update_display;
171 }
172
173 sub attempt_perl_completion ($$$$) {
174 my ($text, $line, $start, $end) = @_;
175
176 no strict qw(refs);
177 if (substr($line, 0, $start) =~ m/\$([\w:]+)\s*(->)?\s*{\s*['"]?$/) {
178 # $foo{key, $foo->{key
179 $attribs->{completion_append_character} = '}';
180 return $term->completion_matches($text,
181 \&perl_hash_key_completion_function);
182 } elsif (substr($line, 0, $start) =~ m/\$([\w:]+)\s*->\s*['"]?$/) {
183 # $foo->method
184 $attribs->{completion_append_character} = ' ';
185 return $term->completion_matches($text,
186 \&perl_method_completion_function);
187 } else { # Perl symbol completion
188 $attribs->{completion_append_character} = '';
189 return $term->completion_matches($text,
190 \&perl_symbol_completion_function);
191 }
192 }
193
194 # static global variables for completion functions
195 use vars qw($i @matches);
196
197 sub perl_hash_key_completion_function ($$) {
198 my($text, $state) = @_;
199
200 if ($state) {
201 $i++;
202 } else {
203 # the first call
204 $i = 0; # clear index
205 my ($var,$arrow) = (substr($attribs->{line_buffer},
206 0, $attribs->{point} - length($text))
207 =~ m/\$([\w:]+)\s*(->)?\s*{\s*['"]?$/); # });
208 no strict qw(refs);
209 $var = "${CWP}::$var" unless ($var =~ m/::/);
210 if ($arrow) {
211 my $hashref = eval "\$$var";
212 @matches = keys %$hashref;
213 } else {
214 @matches = keys %$var;
215 }
216
217 }
218 for (; $i <= $#matches; $i++) {
219 return $matches[$i] if ($matches[$i] =~ /^\Q$text/);
220 }
221 return undef;
222 }
223
224 sub _search_ISA ($) {
225 my ($mypkg) = @_;
226 no strict 'refs';
227 no warnings 'prototype';
228 my $isa = "${mypkg}::ISA";
229 return $mypkg, map _search_ISA($_), @$isa;
230 }
231
232 sub perl_method_completion_function ($$) {
233 my($text, $state) = @_;
234
235 if ($state) {
236 $i++;
237 } else {
238 # the first call
239 my ($var, $pkg, $sym, $pk);
240 $i = 0; # clear index
241 $var = (substr($attribs->{line_buffer},
242 0, $attribs->{point} - length($text))
243 =~ m/\$([\w:]+)\s*->\s*$/)[0];
244 $pkg = ref eval (($var =~ m/::/) ? "\$$var" : "\$${CWP}::$var");
245 no strict qw(refs);
246 @matches = map { $pk = $_ . '::';
247 grep (/^\w+$/
248 && ($sym = "${pk}$_", defined *$sym{CODE}),
249 keys %$pk);
250 } _search_ISA($pkg);
251 }
252 for (; $i <= $#matches; $i++) {
253 return $matches[$i] if ($matches[$i] =~ /^\Q$text/);
254 }
255 return undef;
256 }
257
258 #
259 # Perl symbol name completion
260 #
261 {
262 my ($prefix, %type, @keyword);
263
264 sub perl_symbol_completion_function ($$) {
265 my($text, $state) = @_;
266
267 if ($state) {
268 $i++;
269 } else {
270 # the first call
271 my ($pre, $pkg, $sym);
272 $i = 0; # clear index
273
274 no strict qw(refs);
275 ($prefix, $pre, $pkg) = ($text =~ m/^((\$#|[\@\$%&])?(.*::)?)/);
276 @matches = grep /::$/, $pkg ? keys %$pkg : keys %::;
277 $pkg = ($CWP eq 'main' ? '::' : $CWP . '::') unless $pkg;
278
279 if ($pre) { # $foo, @foo, $#foo, %foo, &foo
280 @matches = (@matches,
281 grep (/^\w+$/
282 && ($sym = $pkg . $_,
283 defined *$sym{$type{$pre}}),
284 keys %$pkg));
285 } else { # foo
286 @matches = (@matches,
287 !$prefix && @keyword,
288 grep (/^\w+$/
289 && ($sym = $pkg . $_,
290 defined *$sym{CODE} || defined *$sym{IO}
291 ),
292 keys %$pkg));
293 }
294 }
295 my $entry;
296 for (; $i <= $#matches; $i++) {
297 $entry = $prefix . $matches[$i];
298 return $entry if ($entry =~ /^\Q$text/);
299 }
300 return undef;
301 }
302
303 BEGIN {
304 %type = ('$' => 'SCALAR', '*' => 'SCALAR',
305 '@' => 'ARRAY', '$#' => 'ARRAY',
306 '%' => 'HASH',
307 '&' => 'CODE'); # '
308
309 # from perl5.004_02 perlfunc
310 @keyword = qw(
311 chomp chop chr crypt hex index lc lcfirst
312 length oct ord pack q qq
313 reverse rindex sprintf substr tr uc ucfirst
314 y
315
316 m pos quotemeta s split study qr
317
318 abs atan2 cos exp hex int log oct rand sin
319 sqrt srand
320
321 pop push shift splice unshift
322
323 grep join map qw reverse sort unpack
324
325 delete each exists keys values
326
327 binmode close closedir dbmclose dbmopen die
328 eof fileno flock format getc print printf
329 read readdir rewinddir seek seekdir select
330 syscall sysread sysseek syswrite tell telldir
331 truncate warn write
332
333 pack read syscall sysread syswrite unpack vec
334
335 chdir chmod chown chroot fcntl glob ioctl
336 link lstat mkdir open opendir readlink rename
337 rmdir stat symlink umask unlink utime
338
339 caller continue die do dump eval exit goto
340 last next redo return sub wantarray
341
342 caller import local my package use
343
344 defined dump eval formline local my reset
345 scalar undef wantarray
346
347 alarm exec fork getpgrp getppid getpriority
348 kill pipe qx setpgrp setpriority sleep
349 system times wait waitpid
350
351 do import no package require use
352
353 bless dbmclose dbmopen package ref tie tied
354 untie use
355
356 accept bind connect getpeername getsockname
357 getsockopt listen recv send setsockopt shutdown
358 socket socketpair
359
360 msgctl msgget msgrcv msgsnd semctl semget
361 semop shmctl shmget shmread shmwrite
362
363 endgrent endhostent endnetent endpwent getgrent
364 getgrgid getgrnam getlogin getpwent getpwnam
365 getpwuid setgrent setpwent
366
367 endprotoent endservent gethostbyaddr
368 gethostbyname gethostent getnetbyaddr
369 getnetbyname getnetent getprotobyname
370 getprotobynumber getprotoent getservbyname
371 getservbyport getservent sethostent setnetent
372 setprotoent setservent
373
374 gmtime localtime time times
375
376 abs bless chomp chr exists formline glob
377 import lc lcfirst map my no prototype qx qw
378 readline readpipe ref sub sysopen tie tied
379 uc ucfirst untie use
380
381 dbmclose dbmopen
382 );
383 }
384 }
385
386 __END__
387
388 =pod
389
390 Before invoking, this program reads F<~/.perlshrc> and evaluates the
391 content of the file.
392
393 When this program is terminated, the content of the history buffer is
394 saved in a file F<~/.perlsh_history>, and it is read at next
395 invoking.
396
397 =head1 VARIABLES
398
399 You can customize the behavior of C<perlsh> by setting following
400 variables in F<~/.perlshrc>;
401
402 =over 4
403
404 =item C<$PerlSh::PS1>
405
406 The primary prompt string. The following backslash-escaped special
407 characters can be used.
408
409 \h: host name
410 \u: user name
411 \w: package name
412 \!: history number
413
414 The default value is `C<\w[\!]$ >'.
415
416 =item C<$PerlSh::PS2>
417
418 The secondary prompt string. The default value is `C<E<gt> >'.
419
420 =item C<$PerlSh::HISTFILE>
421
422 The name of the file to which the command history is saved. The
423 default value is C<~/.perlsh_history>.
424
425 =item C<$PerlSh::HISTSIZE>
426
427 If not C<undef>, this is the maximum number of commands to remember in
428 the history. The default value is 256.
429
430 =item C<$PerlSh::STRICT>
431
432 If true, restrict unsafe constructs. See C<use strict> in perl man
433 page. The default value is 0;
434
435 =back
436
437 =head1 FILES
438
439 =over 4
440
441 =item F<~/.perlshrc>
442
443 This file is eval-ed at initialization. If a subroutine C<afterinit>
444 is defined in this file, it will be eval-ed after initialization.
445 Here is a sample.
446
447 # -*- mode: perl -*-
448 # decimal to hexa
449 sub h { map { sprintf("0x%x", $_ ) } @_;}
450
451 sub tk {
452 $t->tkRunning(1);
453 use Tk;
454 $mw = MainWindow->new();
455 }
456
457 # for debugging Term::ReadLine::Gnu
458 sub afterinit {
459 *t = \$PerlSh::term;
460 *a = \$PerlSh::attribs;
461 }
462
463 =item F<~/.perlsh_history>
464
465 =item F<~/.inputrc>
466
467 A initialization file for the GNU Readline Library. Refer its manual
468 for details.
469
470 =back
471
472 =head1 SEE ALSO
473
474 L<Term::ReadLine::Gnu|http://search.cpan.org/dist/Term-ReadLine-Gnu/>
475
476 L<GNU Readline Library|https://tiswww.cwru.edu/php/chet/readline/rltop.html>
477
478 =head1 AUTHOR
479
480 Hiroo Hayashi <[email protected]>
481
482 =cut