5 Sepia - Simple Emacs-Perl Interface
11 M-x load-library RET sepia RET
14 At the prompt in the C<*sepia-repl*> buffer:
18 For more information, please see F<Sepia.html> or F<sepia.info>, which
19 come with the distribution.
23 Sepia is a set of features to make Emacs a better tool for Perl
24 development. This package contains the Perl side of the
25 implementation, including all user-serviceable parts (for the
26 cross-referencing facility see L<Sepia::Xref>). This document is
27 aimed as Sepia developers; for user documentation, see
28 L<Sepia.html> or L<sepia.info>.
30 Though not intended to be used independent of the Emacs interface, the
31 Sepia module's functionality can be used through a rough procedural
36 $VERSION = '0.991_03';
38 # a less annoying version of strict and warnings
39 if (!eval 'use common::sense;1') {
42 no warnings
'deprecated'; # undo some of the 5.12 suck.
43 # Not as useful as I had hoped...
47 (my $child = $_[1]) =~ s!/!::!g;
49 push @
{$REQUIRED_BY{$child}}, $parent;
50 push @
{$REQUIRES{$parent}}, $child;
52 BEGIN { sub TRACK_REQUIRES
() { $ENV{TRACK_REQUIRES
}||0 } };
53 unshift @INC, \
&Sepia
::track_requires
if TRACK_REQUIRES
;
56 use Sepia
::Debug
; # THIS TURNS ON DEBUGGING INFORMATION!
58 use Scalar
::Util
'looks_like_number';
61 use Storable
qw(store retrieve);
63 use vars
qw($PS1 %REPL %RK %REPL_DOC %REPL_SHORT %PRINTER
64 @res $REPL_LEVEL $REPL_QUIT $PACKAGE $SIGGED
65 $WANTARRAY $PRINTER $STRICT $COLUMNATE $ISEVAL $STRINGIFY
66 $LAST_INPUT $READLINE @PRE_EVAL @POST_EVAL @PRE_PROMPT
67 %REQUIRED_BY %REQUIRES);
70 eval q{ use List::Util 'max' };
75 $ret = $_ if $_ > $ret;
84 Like Emacs, Sepia's behavior can be modified by placing functions on
85 various hooks (arrays). Hooks can be manipulated by the following
90 =item C<add_hook(@hook, @functions)> -- Add C<@functions> to C<@hook>.
92 =item C<remove_hook(@hook, @functions)> -- Remove named C<@functions> from C<@hook>.
94 =item C<run_hook(@hook)> -- Run the functions on the named hook.
96 Each function is called with no arguments in an eval {} block, and
97 its return value is ignored.
101 Sepia currently defines the following hooks:
105 =item C<@PRE_PROMPT> -- Called immediately before the prompt is printed.
107 =item C<@PRE_EVAL> -- Called immediately before evaluating user input.
109 =item C<@POST_EVAL> -- Called immediately after evaluating user input.
128 push @
$hook, $h unless grep $h eq $_, @
$hook;
135 @
$hook = grep { my $x = $_; !grep $_ eq $x, @
$hook } @
$hook;
140 Sepia tries hard to come up with a list of completions.
144 =item C<$re = _apropos_re($pat)>
146 Create a completion expression from user input.
152 # Do that crazy multi-word identifier completion thing:
154 my $hat = shift() ?
'' : '^';
155 return qr/.*/ if $re eq '';
158 s/(?:^|(?<=[A-Za-z\d]))(([^A-Za-z\d])\2*)/[A-Za-z\\d]*$2+/g;
160 } split /:+/, $re, -1;
162 if ($re !~ /[^\w\d_^:]/) {
163 $re =~ s/(?<=[A-Za-z\d])(([^A-Za-z\d])\2*)/[A-Za-z\\d]*$2+/g;
171 %sigil = qw(ARRAY @ SCALAR $ HASH %);
174 =item C<$val = filter_untyped>
176 Return true if C<$_> is the name of a sub, file handle, or package.
178 =item C<$val = filter_typed $type>
180 Return true if C<$_> is the name of something of C<$type>, which
181 should be either a glob slot name (e.g. SCALAR) or the special value
182 "VARIABLE", meaning an array, hash, or scalar.
190 local $_ = /^::/ ?
$_ : "::$_";
191 defined *{$_}{CODE
} || defined *{$_}{IO
} || (/::$/ && %$_);
194 ## XXX: Careful about autovivification here! Specifically:
195 ## defined *FOO{HASH} # => ''
196 ## defined %FOO # => ''
197 ## defined *FOO{HASH} # => 1
202 local $_ = /^::/ ?
$_ : "::$_";
203 if ($type eq 'SCALAR') {
205 } elsif ($type eq 'VARIABLE') {
206 defined $$_ || defined *{$_}{HASH
} || defined *{$_}{ARRAY
};
212 =item C<$re_out = maybe_icase $re_in>
214 Make C<$re_in> case-insensitive if it looks like it should be.
221 return '' if $ch eq '';
222 $ch =~ /[A-Z]/ ?
$ch : '['.uc($ch).$ch.']';
225 =item C<@res = all_abbrev_completions $pattern>
227 Find all "abbreviated completions" for $pattern.
231 sub all_abbrev_completions
233 use vars
'&_completions';
234 local *_completions
= sub {
236 my ($stash, @e) = @_;
237 my $ch = '[A-Za-z0-9]*';
238 my $re1 = "^".maybe_icase
($e[0]).$ch.join('', map {
239 '_'.maybe_icase
($_).$ch
242 my $re2 = maybe_icase
$e[0];
243 $re2 = qr/^$re2.*::$/;
244 my @ret = grep !/::$/ && /$re1/, keys %{$stash};
245 my @pkgs = grep /$re2/, keys %{$stash};
246 (map("$stash$_", @ret),
247 @e > 1 ?
map { _completions
"$stash$_", @e[1..$#e] } @pkgs :
248 map { "$stash$_" } @pkgs)
250 map { s/^:://; $_ } _completions
('::', split //, shift);
255 my ($icase, $re) = @_;
257 $icase ?
qr/^$re.*$/i : qr/^$re.*$/;
262 my $icase = $_[0] !~ /[A-Z]/;
263 my @parts = split /:+/, shift, -1;
264 my $re = apropos_re
$icase, pop @parts;
265 use vars
'&_completions';
266 local *_completions
= sub {
270 map { "$stash$_" } grep /$re/, keys %{$stash};
272 my $re2 = $icase ?
qr/^$_[0].*::$/i : qr/^$_[0].*::$/;
273 my @pkgs = grep /$re2/, keys %{$stash};
274 map { _completions
"$stash$_", @_[1..$#_] } @pkgs
277 map { s/^:://; $_ } _completions
('::', @parts);
280 =item C<@res = filter_exact_prefix @names>
282 Filter exact matches so that e.g. "A::x" completes to "A::xx" when
283 both "Ay::xx" and "A::xx" exist.
287 sub filter_exact_prefix
289 my @parts = split /:+/, shift, -1;
292 my $pre = shift @parts;
293 while (@parts && (@tmp = grep /^\Q$pre\E(?:::|$)/, @res)) {
295 $pre .= '::'.shift @parts;
300 =item C<@res = lexical_completions $type, $str, $sub>
302 Find lexicals of C<$sub> (or a parent lexical environment) of type
303 C<$type> matching C<$str>.
307 sub lexical_completions
309 eval q{ require PadWalker; import PadWalker 'peek_sub' };
310 # "internal" function, so don't warn on failure
312 *lexical_completions
= sub {
313 my ($type, $str, $sub) = @_;
314 $sub = "$PACKAGE\::$sub" unless $sub =~ /::/;
315 # warn "Completing $str of type $type in $sub\n";
317 return unless defined *{$sub}{CODE
};
318 my $pad = peek_sub
(\
&$sub);
320 map { s/^[\$\@&\%]//;$_ } grep /^\Q$type$str\E/, keys %$pad;
322 map { s/^[\$\@&\%]//;$_ } grep /^.\Q$str\E/, keys %$pad;
325 goto &lexical_completions
;
328 =item C<@compls = completions($string [, $type])>
330 Find a list of completions for C<$string> with glob type C<$type>,
331 which may be "SCALAR", "HASH", "ARRAY", "CODE", "IO", or the special
332 value "VARIABLE", which means either scalar, hash, or array.
333 Completion operates on word subparts separated by [:_], so
334 e.g. "S:m_w" completes to "Sepia::my_walksymtable".
336 =item C<@compls = method_completions($expr, $string [,$eval])>
338 Complete among methods on the object returned by C<$expr>. The
339 C<$eval> argument, if present, is a function used to do the
340 evaluation; the default is C<eval>, but for example the Sepia REPL
341 uses C<Sepia::repl_eval>. B<Warning>: Since it has to evaluate
342 C<$expr>, method completion can be extremely problematic. Use with
349 my ($type, $str, $sub) = @_;
351 my %h = qw(@ ARRAY % HASH & CODE * IO $ SCALAR);
353 @rh{values %h} = keys %h;
355 $t = $type ?
$rh{$type} : '';
357 if ($sub && $type ne '') {
358 @ret = lexical_completions
$t, $str, $sub;
362 $type ? filter_typed
$type : filter_untyped
363 } all_completions
$str;
365 if (!@ret && $str !~ /:/) {
367 $type ? filter_typed
$type : filter_untyped
368 } all_abbrev_completions
$str;
370 @ret = map { s/^:://; "$t$_" } filter_exact_prefix
$str, @ret;
371 # ## XXX: Control characters, $", and $1, etc. confuse Emacs, so
374 length $_ > 0 && !/^\d+$/ && !/^[^\w\d_]$/ && !/^_</ && !/^[[:cntrl:]]/
378 sub method_completions
380 my ($x, $fn, $eval) = @_;
383 $eval ||= 'CORE::eval';
385 return unless ($x =~ /^\$/ && ($x = $eval->("ref($x)")))
386 || $eval->('%'.$x.'::');
388 my $re = _apropos_re
$fn;
389 ## Filter out overload methods "(..."
390 return sort { $a cmp $b } map { s/.*:://; $_ }
391 grep { defined *{$_}{CODE
} && /::$re/ && !/\(/ }
396 =item C<@matches = apropos($name [, $is_regex])>
398 Search for function C<$name>, either in all packages or, if C<$name>
399 is qualified, only in one package. If C<$is_regex> is true, the
400 non-package part of C<$name> is a regular expression.
404 sub my_walksymtable
(&*)
410 &$f for keys %$stash;
411 _walk
("$stash$_") for grep /(?<!main)::$/, keys %$stash;
418 my ($it, $re, @types) = @_;
421 $stashp = grep /STASH/, @types;
422 @types = grep !/STASH/, @types;
427 if ($it =~ /^(.*::)([^:]+)$/) {
428 my ($stash, $name) = ($1, $2);
433 my $name = qr/^$name/;
438 my $stashnm = "$stash$_";
442 defined($_ eq 'SCALAR' ?
$$stashnm : *{$stashnm}{$_})
446 defined &$it ?
$it : ();
450 my $findre = $re ?
qr/$it/ : qr/^\Q$it\E$/;
452 push @ret, "$stash$_" if /$findre/;
454 map { s/^:*(?:main:+)*//;$_ } @ret;
460 =head2 Module information
464 =item C<@names = mod_subs($pack)>
466 Find subs in package C<$pack>.
474 my $stash = \
%{"$p\::"};
476 grep { defined &{"$p\::$_"} } keys %$stash;
480 =item C<@decls = mod_decls($pack)>
482 Generate a list of declarations for all subroutines in package
493 my $proto = prototype(\
&{"$pack\::$sn"});
494 $proto = defined($proto) ?
"($proto)" : '';
497 return wantarray ?
@ret : join '', @ret;
500 =item C<$info = module_info($module, $type)>
502 Emacs-called function to get module information.
508 eval q{ require Module::Info; import Module::Info };
517 $info = Module
::Info
->new_from_file($m);
519 (my $file = $m) =~ s
|::|/|g
;
521 if (exists $INC{$file}) {
522 $info = Module
::Info
->new_from_loaded($m);
524 $info = Module
::Info
->new_from_module($m);
535 =item C<$file = mod_file($mod)>
537 Find the likely file owner for module C<$mod>.
545 while ($m && !exists $INC{"$m.pm"}) {
546 $m =~ s
#(?:^|/)[^/]+$##;
548 $m ?
$INC{"$m.pm"} : undef;
551 =item C<@mods = package_list>
553 Gather a list of all distributions on the system.
561 eval 'require ExtUtils::Installed';
562 $INST = new ExtUtils
::Installed
;
569 sort { $a cmp $b } inst
()->modules;
572 =item C<@mods = module_list>
574 Gather a list of all packages (.pm files, really) installed on the
575 system, grouped by distribution. XXX UNUSED
581 join '|', map quotemeta, sort { length $b <=> length $a } @INC;
586 @_ = package_list
unless @_;
588 $incre = qr
|(?
:$incre)/|;
592 s/$incre\///; s|/|::|g
;$_
593 } grep /\.pm$/, $inst->files($_)]
597 =item C<@paths = file_list $module>
599 List the absolute paths of all files (except man pages) installed by
606 my @ret = eval { grep /\.p(l|m|od)$/, inst
->files(shift) };
610 =item C<@mods = doc_list>
612 Gather a list of all documented packages (.?pm files, really)
613 installed on the system, grouped by distribution. XXX UNUSED
621 @_ = package_list
unless @_;
625 s/.*man.\///; s|/|::|g
;s/\..?pm//; $_
626 } grep /\..pm$/, $inst->files($_)]
630 =head2 Miscellaneous functions
634 =item C<$v = core_version($module)>
640 eval q{ require Module::CoreList };
644 *core_version
= sub { Module
::CoreList
->first_release(@_) };
649 =item C<[$file, $line, $name] = location($name)>
651 Return a [file, line, name] triple for function C<$name>.
659 if (my ($pfx, $name) = /^([\%\$\@]?)(.+)/) {
661 warn "Sorry -- can't lookup variables.";
663 # XXX: svref_2object only seems to work with a package
664 # tacked on, but that should probably be done elsewhere...
665 $name = 'main::'.$name unless $name =~ /::/;
666 my $cv = B
::svref_2object
(\
&{$name});
667 if ($cv && defined($cv = $cv->START) && !$cv->isa('B::NULL')) {
668 my ($file, $line) = ($cv->file, $cv->line);
669 if ($file !~ /^\//) {
671 if (!ref $_ && -f
"$_/$file") {
677 my ($shortname) = $name =~ /^(?:.*::)([^:]+)$/;
678 return [Cwd
::abs_path
($file), $line, $shortname || $name]
686 =item C<lexicals($subname)>
688 Return a list of C<$subname>'s lexical variables. Note that this
689 includes all nested scopes -- I don't know if or how Perl
690 distinguishes inner blocks.
696 my $cv = B
::svref_2object
(\
&{+shift});
697 return unless $cv && ($cv = $cv->PADLIST);
698 my ($names, $vals) = $cv->ARRAY;
700 my $name = $_->PV; $name =~ s/\0.*$//; $name
701 } grep B
::class($_) ne 'SPECIAL', $names->ARRAY;
704 =item C<$lisp = tolisp($perl)>
706 Convert a Perl scalar to some ELisp equivalent.
712 my $thing = @_ == 1 ?
shift : \
@_;
715 if (!defined $thing) {
717 } elsif (looks_like_number
$thing) {
720 ## XXX Elisp and perl have slightly different
721 ## escaping conventions, so we do this crap instead.
722 $thing =~ s/["\\]/\\$1/g;
725 } elsif ($t eq 'GLOB') {
726 (my $name = $$thing) =~ s/\*main:://;
728 } elsif ($t eq 'ARRAY') {
729 '(' . join(' ', map { tolisp
($_) } @
$thing).')'
730 } elsif ($t eq 'HASH') {
731 '(' . join(' ', map {
732 '(' . tolisp
($_) . " . " . tolisp
($thing->{$_}) . ')'
734 } elsif ($t eq 'Regexp') {
735 "'(regexp . \"" . quotemeta($thing) . '")';
736 # } elsif ($t eq 'IO') {
742 =item C<printer(\@res)>
744 Print C<@res> appropriately on the current filehandle. If C<$ISEVAL>
745 is true, use terse format. Otherwise, use human-readable format,
746 which can use either L<Data::Dumper>, L<YAML>, or L<Data::Dump>.
752 eval q{ require Data::Dumper };
753 local $Data::Dumper
::Deparse
= 1;
754 local $Data::Dumper
::Indent
= 0;
756 my $thing = @res > 1 ? \
@res : $res[0];
758 $_ = Data
::Dumper
::Dumper
($thing);
760 if (length $_ > ($ENV{COLUMNS
} || 80)) {
761 $Data::Dumper
::Indent
= 1;
763 $_ = Data
::Dumper
::Dumper
($thing);
774 if (eval q{require 'dumpvar.pl';1}) {
775 dumpvar
::veryCompact
(1);
776 $PRINTER{dumpvar
} = sub { dumpValue
(\
@res) };
777 goto &{$PRINTER{dumpvar
}};
781 eval q{ require YAML };
783 $PRINTER{dumper
}->();
789 eval q{ require Data::Dump };
791 $PRINTER{dumper
}->();
793 Data
::Dump
::dump(\
@res);
802 $PRINTER{dumper
}->();
804 my $ret = new IO
::Scalar
;
805 my $out = select $ret;
806 Devel
::Peek
::Dump
(@res == 1 ?
$res[0] : \
@res);
827 $_ = @res == 1 ?
$res[0] : @res == 0 ?
undef : [@res];
831 } elsif (@res == 1 && !$ISEVAL && $STRINGIFY
832 && UNIVERSAL
::can
($res[0], '()')) {
835 } elsif (!$ISEVAL && $COLUMNATE && @res > 1 && !grep ref, @res) {
836 $res = columnate
(@res);
840 $res = $PRINTER{$PRINTER}->();
843 print ';;;', length $res, "\n$res\n";
858 =item C<prompt()> -- Print the REPL prompt.
864 run_hook
@PRE_PROMPT;
865 "$PACKAGE $WANTARRAY$PS1"
871 Data
::Dumper
->Dump([$_[0]], [$_[1]]);
875 =item C<$flowed = flow($width, $text)> -- Flow C<$text> to at most C<$width> columns.
882 my $n1 = int(2*$n/3);
884 s/(.{$n1,$n}) /$1\n/g;
894 =item C<load \@keyvals> -- Load persisted data in C<@keyvals>.
896 =item C<$ok = saveable $name> -- Return whether C<$name> is saveable.
898 Saving certain magic variables leads to badness, so we avoid them.
900 =item C<\@kvs = save $re> -- Return a list of name/value pairs to save.
911 *{$_->[0]} = $_->[1];
916 undef @BADVARS{qw(%INC @INC %SIG @ISA %ENV @ARGV)};
922 return !/^.[^c-zA-Z]$/ # single-letter stuff (match vars, $_, etc.)
923 && !/^.[\0-\060]/ # magic weirdness.
924 && !/^._</ # debugger info
925 && !exists $BADVARS{$_}; # others.
932 $re = qr/(?:^|::)$re/;
933 no strict; # no kidding...
936 || $stash =~ /^(?:::)?(?:warnings|Config|strict|B)\b/;
938 my $name = "$stash$_";
939 if (defined ${$name} and saveable '$'.$_) {
940 push @save, [$name, \$$name];
942 if (defined *{$name}{HASH} and saveable '%'.$_) {
943 push @save, [$name, \%{$name}];
945 if (defined *{$name}{ARRAY} and saveable '@'.$_) {
946 push @save, [$name, \@{$name}];
950 print STDERR "$_->[0] " for @save;
955 =head2 REPL shortcuts
957 The function implementing built-in REPL shortcut ",X" is named C<repl_X>.
961 =item C<define_shortcut $name, $sub [, $doc [, $shortdoc]]>
963 Define $name as a shortcut for function $sub.
969 my ($name, $doc, $short, $fn);
975 ($name, $fn, $doc) = @_;
978 ($name, $fn, $short, $doc) = @_;
981 $REPL_DOC{$name} = $doc;
982 $REPL_SHORT{$name} = $short;
983 abbrev \%RK, keys %REPL;
986 =item C<define_shortcuts()>
988 Define the default REPL shortcuts.
994 define_shortcut 'help', \&Sepia::repl_help,
996 'Display help on all commands, or just CMD.';
997 define_shortcut 'cd', \&Sepia::repl_chdir,
998 'cd DIR', 'Change directory to DIR';
999 define_shortcut 'pwd', \&Sepia::repl_pwd,
1000 'Show current working directory';
1001 define_shortcut 'methods', \&Sepia::repl_methods,
1003 'List methods for reference or package X, matching optional pattern RE';
1004 define_shortcut 'package', \&Sepia::repl_package,
1005 'package PKG', 'Set evaluation package to PKG';
1006 define_shortcut 'who', \&Sepia::repl_who,
1008 'List variables and subs in PKG matching optional pattern RE.';
1009 define_shortcut 'wantarray', \&Sepia::repl_wantarray,
1010 'wantarray [0|1]', 'Set or toggle evaluation context';
1011 define_shortcut 'format', \&Sepia::repl_format,
1012 'format [TYPE]', "Set output formatter to TYPE (one of 'dumper', 'dump', 'yaml', 'plain'; default: 'dumper'), or show current type.";
1013 define_shortcut 'strict', \&Sepia::repl_strict,
1014 'strict [0|1]', 'Turn \'use strict\' mode on or off';
1015 define_shortcut 'quit', \&Sepia::repl_quit,
1017 define_shortcut 'restart', \&Sepia::repl_restart,
1018 'Reload Sepia.pm and relaunch the REPL.';
1019 define_shortcut 'shell', \&Sepia::repl_shell,
1020 'shell CMD ...', 'Run CMD in the shell';
1021 define_shortcut 'eval', \&Sepia::repl_eval,
1022 'eval EXP', '(internal)';
1023 define_shortcut 'size', \&Sepia::repl_size,
1025 'List total sizes of objects in PKG matching optional pattern RE.';
1026 define_shortcut define => \&Sepia::repl_define,
1027 'define NAME [\'DOC\'] BODY',
1028 'Define NAME as a shortcut executing BODY';
1029 define_shortcut undef => \&Sepia::repl_undef,
1030 'undef NAME', 'Undefine shortcut NAME';
1031 define_shortcut test => \&Sepia::repl_test,
1032 'test FILE...', 'Run tests interactively.';
1033 define_shortcut load => \&Sepia::repl_load,
1034 'load [FILE]', 'Load state from FILE.';
1035 define_shortcut save => \&Sepia::repl_save,
1036 'save [PATTERN [FILE]]', 'Save variables matching PATTERN to FILE.';
1037 define_shortcut reload => \&Sepia::repl_reload,
1038 'reload [MODULE | /RE/]', 'Reload MODULE, or all modules matching RE.';
1039 define_shortcut freload => \&Sepia::repl_full_reload,
1040 'freload MODULE', 'Reload MODULE and all its dependencies.';
1041 define_shortcut time => \&Sepia::repl_time,
1042 'time [0|1]', 'Print timing information for each command.';
1043 define_shortcut lsmod => \&Sepia::repl_lsmod,
1044 'lsmod [PATTERN]', 'List loaded modules matching PATTERN.';
1047 =item C<repl_strict([$value])>
1049 Toggle strict mode. Requires L<Lexical::Persistence>.
1055 eval q{ require Lexical::Persistence; import Lexical::Persistence };
1057 print "Strict mode requires Lexical::Persistence.\n";
1059 # L::P has the stupid behavior of not persisting variables
1060 # starting with '_', and dividing them into "contexts" based
1061 # on whatever comes before the first underscore. Get rid of
1063 *Lexical
::Persistence
::parse_variable
= sub {
1064 my ($self, $var) = @_;
1067 my ($sigil, $member) = (
1068 $var =~ /^([\$\@\%])(\S+)/
1073 if (defined $context) {
1074 if (exists $self->{context
}{$context}) {
1075 return $sigil, $context, $member if $context eq "arg";
1076 return $sigil, $context, "$sigil$member";
1078 return $sigil, "_", "$sigil$context\_$member";
1081 return $sigil, "_", "$sigil$member";
1084 *repl_strict
= sub {
1085 my $x = as_boolean
(shift, $STRICT);
1086 if ($x && !$STRICT) {
1087 $STRICT = new Lexical
::Persistence
;
1098 eval q{ require Devel::Size };
1100 print "Size requires Devel::Size.\n";
1102 *Sepia
::repl_size
= sub {
1104 ## XXX: C&P from repl_who:
1105 my ($pkg, $re) = split ' ', shift || '';
1106 if ($pkg =~ /^\/(.*)\
/?$/) {
1112 } elsif (!$re && !%{$pkg.'::'}) {
1116 my @who = who
($pkg, $re);
1117 my $len = max
(3, map { length } @who) + 4;
1118 my $fmt = '%-'.$len."s%10d\n";
1119 # print "$pkg\::/$re/\n";
1120 print 'Var', ' ' x
($len + 2), "Bytes\n";
1121 print '-' x
($len-4), ' ' x
9, '-' x
5, "\n";
1124 next unless /^[\$\@\%\&]/; # skip subs.
1125 next if $_ eq '%SIG';
1126 $res{$_} = eval "no strict; package $pkg; Devel::Size::total_size \\$_;";
1128 for (sort { $res{$b} <=> $res{$a} } keys %res) {
1129 printf $fmt, $_, $res{$_};
1136 =item C<repl_time([$value])>
1138 Toggle command timing.
1142 my ($time_res, $TIME);
1143 sub time_pre_prompt_bsd
1145 printf "(%.2gr, %.2gu, %.2gs) ", @
{$time_res} if defined $time_res;
1148 sub time_pre_prompt_plain
1150 printf "(%.2gs) ", $time_res if defined $time_res;
1155 $TIME = as_boolean
(shift, $TIME);
1157 print STDERR
"Removing time hook.\n";
1158 remove_hook
@PRE_PROMPT, 'Sepia::time_pre_prompt';
1159 remove_hook
@PRE_EVAL, 'Sepia::time_pre_eval';
1160 remove_hook
@POST_EVAL, 'Sepia::time_post_eval';
1163 print STDERR
"Adding time hook.\n";
1164 add_hook
@PRE_PROMPT, 'Sepia::time_pre_prompt';
1165 add_hook
@PRE_EVAL, 'Sepia::time_pre_eval';
1166 add_hook
@POST_EVAL, 'Sepia::time_post_eval';
1167 my $has_bsd = eval q{ use BSD::Resource 'getrusage';1 };
1168 my $has_hires = eval q{ use Time::HiRes qw(gettimeofday tv_interval);1 };
1170 if ($has_bsd) { # sweet! getrusage!
1171 my ($user, $sys, $real);
1172 *time_pre_eval
= sub {
1174 ($user, $sys) = getrusage
();
1175 $real = $has_hires ?
[gettimeofday
()] : $user+$sys;
1177 *time_post_eval
= sub {
1178 my ($u2, $s2) = getrusage
();
1179 $time_res = [$has_hires ? tv_interval
($real, [gettimeofday
()])
1180 : $s2 + $u2 - $real,
1181 ($u2 - $user), ($s2 - $sys)];
1183 *time_pre_prompt
= *time_pre_prompt_bsd
;
1184 } elsif ($has_hires) { # at least we have msec...
1185 *time_pre_eval
= sub {
1187 $t0 = [gettimeofday
()];
1189 *time_post_eval
= sub {
1190 $time_res = tv_interval
($t0, [gettimeofday
()]);
1192 *time_pre_prompt
= *time_pre_prompt_plain
;
1194 *time_pre_eval
= sub {
1198 *time_post_eval
= sub {
1199 $time_res = (time - $t0);
1201 *time_pre_prompt
= *time_pre_prompt_plain
;
1207 my $width = $ENV{COLUMNS
} || 80;
1209 if ($args =~ /\S/) {
1212 my $full = $RK{$args};
1214 my $short = $REPL_SHORT{$full};
1215 my $flow = flow
($width - length $short - 4, $REPL_DOC{$full});
1216 $flow =~ s/(.)\n/"$1\n".(' 'x (4 + length $short))/eg;
1217 print "$short $flow\n";
1219 print "$args: no such command\n";
1222 my $left = 1 + max
map length, values %REPL_SHORT;
1223 print "REPL commands (prefixed with ','):\n";
1225 for (sort keys %REPL) {
1226 my $flow = flow
($width - $left, $REPL_DOC{$_});
1227 $flow =~ s/(.)\n/"$1\n".(' ' x $left)/eg;
1228 printf "%-${left}s%s\n", $REPL_SHORT{$_}, $flow;
1236 my ($name, $doc, $body);
1237 if (/^\s*(\S+)\s+'((?:[^'\\]|\\.)*)'\s+(.+)/) {
1238 ($name, $doc, $body) = ($1, $2, $3);
1239 } elsif (/^\s*(\S+)\s+(\S.*)/) {
1240 ($name, $doc, $body) = ($1, $2, $2);
1242 print "usage: define NAME ['doc'] BODY...\n";
1245 my $sub = eval "sub { do { $body } }";
1247 print "usage: define NAME ['doc'] BODY...\n\t$@\n";
1250 define_shortcut
$name, $sub, $doc;
1251 # %RK = abbrev keys %REPL;
1259 my $full = $RK{$name};
1261 delete $REPL{$full};
1262 delete $REPL_SHORT{$full};
1263 delete $REPL_DOC{$full};
1264 abbrev \
%RK, keys %REPL;
1266 print "$name: no such shortcut.\n";
1275 print "printer = $PRINTER, columnate = @{[$COLUMNATE ? 1 : 0]}\n";
1277 my %formats = abbrev
keys %PRINTER;
1278 if (exists $formats{$t}) {
1279 $PRINTER = $formats{$t};
1281 warn "No such format '$t' (dumper, dump, yaml, plain).\n";
1288 chomp(my $dir = shift);
1289 $dir =~ s/^~\//$ENV{HOME
}\
//;
1290 $dir =~ s/\$HOME/$ENV{HOME}/;
1293 my $ecmd = '(cd "'.Cwd
::getcwd
().'")';
1294 print ";;;###".length($ecmd)."\n$ecmd\n";
1296 warn "Can't chdir\n";
1302 print Cwd
::getcwd
(), "\n";
1305 =item C<who($package [, $re])>
1307 List variables and functions in C<$package> matching C<$re>, or all
1308 variables if C<$re> is absent.
1314 my ($pack, $re_str) = @_;
1316 my $re = qr/$re_str/;
1318 if ($re_str =~ /^[\$\@\%\&]/) {
1319 ## sigil given -- match it
1320 sort grep /$re/, map {
1321 my $name = $pack.'::'.$_;
1322 (defined *{$name}{HASH
} ?
'%'.$_ : (),
1323 defined *{$name}{ARRAY
} ?
'@'.$_ : (),
1324 defined *{$name}{CODE
} ?
$_ : (),
1325 defined ${$name} ?
'$'.$_ : (), # ?
1327 } grep !/::$/ && !/^(?:_<|[^\w])/ && /$re/, keys %{$pack.'::'};
1329 ## no sigil -- don't match it
1331 my $name = $pack.'::'.$_;
1332 (defined *{$name}{HASH
} ?
'%'.$_ : (),
1333 defined *{$name}{ARRAY
} ?
'@'.$_ : (),
1334 defined *{$name}{CODE
} ?
$_ : (),
1335 defined ${$name} ?
'$'.$_ : (), # ?
1337 } grep !/::$/ && !/^(?:_<|[^\w])/ && /$re/, keys %{$pack.'::'};
1341 =item C<$text = columnate(@items)>
1343 Format C<@items> in columns such that they fit within C<$ENV{COLUMNS}>
1351 my $width = $ENV{COLUMNS
} || 80;
1353 $len = length if $len < length;
1355 my $nc = int($width / ($len+1)) || 1;
1356 my $nr = int(@_ / $nc) + (@_ % $nc ?
1 : 0);
1357 my $fmt = ('%-'.($len+1).'s') x
($nc-1) . "%s\n";
1358 my @incs = map { $_ * $nr } 0..$nc-1;
1360 for my $r (0..$nr-1) {
1361 $str .= sprintf $fmt, map { defined($_) ?
$_ : '' }
1362 @_[map { $r + $_ } @incs];
1370 my ($pkg, $re) = split ' ', shift;
1372 if ($pkg && $pkg =~ /^\/(.*)\
/?$/) {
1375 } elsif (!$re && !%{$pkg.'::'}) {
1379 print columnate who
($pkg || $PACKAGE, $re);
1382 =item C<@m = methods($package [, $qualified])>
1384 List method names in C<$package> and its parents. If C<$qualified>,
1385 return full "CLASS::NAME" rather than just "NAME."
1391 my ($pack, $qualified) = @_;
1393 my @own = $qualified ?
grep {
1395 } map { "$pack\::$_" } keys %{$pack.'::'}
1397 defined &{"$pack\::$_"}
1398 } keys %{$pack.'::'};
1399 if (exists ${$pack.'::'}{ISA
} && *{$pack.'::ISA'}{ARRAY
}) {
1401 undef @m{@own, map methods
($_, $qualified), @
{$pack.'::ISA'}};
1409 my ($x, $re) = split ' ', shift;
1413 $x = $REPL{eval}->("ref $x");
1418 print columnate
sort { $a cmp $b } grep /$re/, methods
$x;
1423 my ($val, $cur) = @_;
1425 length($val) ?
$val : !$cur;
1430 $WANTARRAY = shift || $WANTARRAY;
1431 $WANTARRAY = '' unless $WANTARRAY eq '@' || $WANTARRAY eq '$';
1436 chomp(my $p = shift);
1448 do $INC{'Sepia.pm'};
1450 print "Restart failed:\n$@\n";
1452 $REPL_LEVEL = 0; # ok?
1467 # local $PACKAGE = $pkg || $PACKAGE;
1469 if ($WANTARRAY eq '$') {
1470 $buf = 'scalar($buf)';
1471 } elsif ($WANTARRAY ne '@') {
1474 my $ctx = join(',', keys %{$STRICT->get_context('_')});
1475 $ctx = $ctx ?
"my ($ctx);" : '';
1476 $buf = eval "sub { package $PACKAGE; use strict; $ctx $buf }";
1478 print "ERROR\n$@\n";
1481 $STRICT->call($buf);
1483 $buf = "do { package $PACKAGE; no strict; $buf }";
1484 if ($WANTARRAY eq '@') {
1486 } elsif ($WANTARRAY eq '$') {
1503 } elsif (-f
"t/$buf") {
1507 find
({ no_chdir
=> 1,
1509 push @files, $_ if /\.t$/;
1510 }}, Cwd
::getcwd
() =~ /t\/?
$/ ? '.' : './t
');
1513 # XXX: this is cribbed from an EU::MM-generated Makefile.
1514 system $^X, qw(-MExtUtils::Command::MM -e),
1515 "test_harness(0, 'blib/lib', 'blib/arch')", @files;
1517 print "No test files for '$buf' in ", Cwd
::getcwd
, "\n";
1523 my ($file) = split ' ', shift;
1524 $file ||= "$ENV{HOME}/.sepia-save";
1525 load
(retrieve
$file);
1530 my ($re, $file) = split ' ', shift;
1532 $file ||= "$ENV{HOME}/.sepia-save";
1533 store save
($re), $file;
1536 sub modules_matching
1539 if ($pat =~ /^\/(.*)\
/?$/) {
1543 grep /$pat/, keys %INC;
1547 exists $INC{"$pat.pm"} ?
"$pat.pm" : ();
1553 my %save_inc = %INC;
1555 for my $name (modules_matching
$_[0]) {
1556 print STDERR
"full reload $name\n";
1559 my @ret = keys %INC;
1560 while (my ($k, $v) = each %save_inc) {
1566 sub repl_full_reload
1568 chomp (my $pat = shift);
1569 my @x = full_reload
$pat;
1570 print "Reloaded: @x\n";
1575 chomp (my $pat = shift);
1576 # for my $name (modules_matching $pat) {
1577 # delete $INC{$PAT};
1578 # eval "require $name";
1580 # (my $mod = $name) =~ s/
1581 if ($pat =~ /^\/(.*)\
/?$/) {
1599 if (exists $INC{$pat}) {
1601 eval 'require $mod';
1602 import
$mod unless $@
;
1603 print "Reloaded $mod.\n"
1605 print "$mod not loaded.\n"
1612 chomp (my $pat = shift);
1616 my $fmt = "%-20s%8s %s\n";
1617 for (sort keys %INC) {
1621 next if /^::/ || !/$pat/;
1623 printf $fmt, qw(Module Version File);
1624 printf $fmt, qw(------ ------- ----);
1627 printf $fmt, $_, (UNIVERSAL
::VERSION
($_)||'???'), $INC{$file};
1630 print "No modules found.\n";
1634 =item C<sig_warn($warning)>
1636 Collect C<$warning> for later printing.
1638 =item C<print_warnings()>
1640 Print and clear accumulated warnings.
1656 print ';;;'.length($tmp)."\n$tmp\n";
1660 print "warning: $_\n";
1669 I need user feedback! Please send questions or comments to seano\@cpan.org.
1670 Sepia version $Sepia::VERSION.
1671 Type ",h" for help, or ",q" to quit.
1677 Execute a command interpreter on standard input and standard output.
1678 If you want to use different descriptors, localize them before
1679 calling C<repl()>. The prompt has a few bells and whistles, including:
1683 =item Obviously-incomplete lines are treated as multiline input (press
1684 'return' twice or 'C-c' to discard).
1686 =item C<die> is overridden to enter a debugging repl at the point
1691 Behavior is controlled in part through the following package-globals:
1695 =item C<$PACKAGE> -- evaluation package
1697 =item C<$PRINTER> -- result printer (default: dumper)
1699 =item C<$PS1> -- the default prompt
1701 =item C<$STRICT> -- whether 'use strict' is applied to input
1703 =item C<$WANTARRAY> -- evaluation context
1705 =item C<$COLUMNATE> -- format some output nicely (default = 1)
1707 Format some values nicely, independent of $PRINTER. Currently, this
1708 displays arrays of scalars as columns.
1710 =item C<$REPL_LEVEL> -- level of recursive repl() calls
1712 If zero, then initialization takes place.
1714 =item C<%REPL> -- maps shortcut names to handlers
1716 =item C<%REPL_DOC> -- maps shortcut names to documentation
1718 =item C<%REPL_SHORT> -- maps shortcut names to brief usage
1729 if ($REPL_LEVEL == 0) {
1731 -f
"$ENV{HOME}/.sepiarc" and eval qq#package $Sepia::PACKAGE; do "$ENV{HOME}/.sepiarc"#;
1732 warn ".sepiarc: $@\n" if $@
;
1734 Sepia
::Debug
::add_repl_commands
;
1735 repl_banner
if $REPL_LEVEL == 0;
1738 $READLINE = sub { print prompt
(); <STDIN
> };
1743 local $REPL_LEVEL = $REPL_LEVEL + 1;
1749 my $nextrepl = sub { $SIGGED++; };
1752 local *CORE
::GLOBAL
::die = \
&Sepia
::Debug
::die;
1753 local *CORE
::GLOBAL
::warn = \
&Sepia
::Debug
::warn;
1754 my @sigs = qw(INT TERM PIPE ALRM);
1756 $SIG{$_} = $nextrepl for @sigs;
1757 repl
: while (defined(my $in = $READLINE->())) {
1767 if ($buf =~ /^<<(\d+)\n(.*)/) {
1772 while ($len && defined($tmp = read STDIN
, $buf, $len, length $buf)) {
1776 ## Only install a magic handler if no one else is playing.
1777 local $SIG{__WARN__
} = $SIG{__WARN__
};
1779 unless ($SIG{__WARN__
}) {
1780 $SIG{__WARN__
} = 'Sepia::sig_warn';
1784 # repeat last interactive command
1790 if ($buf =~ /^,(\S+)\s*(.*)/s) {
1791 ## Inspector shortcuts
1793 if (exists $Sepia::RK
{$short}) {
1797 $Sepia::REPL
{$Sepia::RK
{$short}}->($arg, wantarray);
1799 if (grep /^$short/, keys %Sepia::REPL
) {
1800 print "Ambiguous shortcut '$short': ",
1801 join(', ', sort grep /^$short/, keys %Sepia::REPL
),
1804 print "Unrecognized shortcut '$short'\n";
1812 @res = $REPL{eval}->($buf);
1813 run_hook
@POST_EVAL;
1816 ## Always return results for an eval request
1817 Sepia
::printer \
@res, wantarray;
1818 Sepia
::printer
[$@
], wantarray;
1819 # print_warnings $ISEVAL;
1821 } elsif ($@
=~ /(?:at|before) EOF(?:$| at)/m) {
1822 ## Possibly-incomplete line
1824 print "Error:\n$@\n*** cancel ***\n";
1831 # $@ =~ s/(.*) at eval .*/$1/;
1832 # don't complain if we're abandoning execution
1833 # from the debugger.
1834 unless (ref $@
eq 'Sepia::Debug') {
1836 print "\n" unless $@
=~ /\n\z/;
1843 if ($buf !~ /;\s*$/ && $buf !~ /^,/) {
1844 ## Be quiet if it ends with a semicolon, or if we
1845 ## executed a shortcut.
1846 Sepia
::printer \
@res, wantarray;
1852 wantarray ?
@res : $res[0]
1857 tolisp
($REPL{eval}->(shift));
1860 =head2 Module browsing
1864 =item C<$status = html_module_list([$file [, $prefix]])>
1866 Generate an HTML list of installed modules, looking inside of
1867 packages. If C<$prefix> is missing, uses "about://perldoc/". If
1868 $file is given, write the result to $file; otherwise, return it as a
1871 =item C<$status = html_package_list([$file [, $prefix]])>
1873 Generate an HTML list of installed top-level modules, without looking
1874 inside of packages. If C<$prefix> is missing, uses
1875 "about://perldoc/". $file is the same as for C<html_module_list>.
1881 sub html_module_list
1883 my ($file, $base) = @_;
1884 $base ||= 'about://perldoc/';
1886 return unless $inst;
1888 open OUT
, ">", $file || \
$out or return;
1889 print OUT
"<html><body>";
1892 for (package_list
) {
1893 push @
{$ns{$1}}, $_ if /^([^:]+)/;
1895 # Handle core modules.
1897 undef $fs{$_} for map {
1898 s/.*man.\///; s|/|::|g
; s/\.\d(?:pm)?$//; $_
1900 /\.\d(?:pm)?$/ && !/man1/ && !/usr\/bin
/ # && !/^(?
:\
/|perl)/
1901 } $inst->files('Perl');
1902 my @fs = sort keys %fs;
1903 print OUT
qq{<h2
>Core Modules
</h2
><ul
>};
1905 print OUT
qq{<li
><a href
="$base$_">$_</a
>};
1907 print OUT
'</ul><h2>Installed Modules</h2><ul>';
1910 for (sort keys %ns) {
1911 next if $_ eq 'Perl'; # skip Perl core.
1912 print OUT
qq{<li
><b
>$_</b
><ul
>} if @
{$ns{$_}} > 1;
1913 for (sort @
{$ns{$_}}) {
1915 undef $fs{$_} for map {
1916 s/.*man.\///; s|/|::|g
; s/\.\d(?:pm)?$//; $_
1918 /\.\d(?:pm)?$/ && !/man1/
1920 my @fs = sort keys %fs;
1921 next unless @fs > 0;
1923 print OUT
qq{<li
><a href
="$base$fs[0]">$fs[0]</a
>};
1925 print OUT
qq{<li
>$_<ul
>};
1927 print OUT
qq{<li
><a href
="$base$_">$_</a
>};
1932 print OUT
qq{</ul
>} if @
{$ns{$_}} > 1;
1935 print OUT
"</ul></body></html>\n";
1940 sub html_package_list
1942 my ($file, $base) = @_;
1943 return unless inst
();
1945 for (package_list
) {
1946 push @
{$ns{$1}}, $_ if /^([^:]+)/;
1948 $base ||= 'about://perldoc/';
1950 open OUT
, ">", $file || \
$out or return;
1951 print OUT
"<html><body><ul>";
1953 for (sort keys %ns) {
1954 if (@
{$ns{$_}} == 1) {
1956 qq{<li
><a href
="$base$ns{$_}[0]">$ns{$_}[0]</a
>};
1958 print OUT
qq{<li
><b
>$_</b
><ul
>};
1959 print OUT
qq{<li
><a href
="$base$_">$_</a
>}
1960 for sort @
{$ns{$_}};
1961 print OUT
qq{</ul
>};
1964 print OUT
"</ul></body></html>\n";
1971 my $re = _apropos_re
$_[0], 1;
1975 for ($inst->files('Perl', 'prog'), package_list
) {
1976 if (/\.\d?(?:pm)?$/ && !/man1/ && !/usr\/bin
/ && /$re/) {
1981 s/\.\d?(?:p[lm])?$//;
1991 my @q = $REQUIRES{$mod};
1996 push @q, @
{$REQUIRES{$m}};
2004 @
{$REQUIRED_BY{$mod}}
2012 See the README file included with the distribution.
2016 Sepia's public GIT repository is located at L<http://repo.or.cz/w/sepia.git>.
2018 There are several modules for Perl development in Emacs on CPAN,
2019 including L<Devel::PerlySense> and L<PDE>. For a complete list, see
2020 L<http://emacswiki.org/cgi-bin/wiki/PerlLanguage>.
2024 Sean O'Rourke, E<lt>seano@cpan.orgE<gt>
2026 Bug reports welcome, patches even more welcome.
2030 Copyright (C) 2005-2010 Sean O'Rourke. All rights reserved, some
2031 wrongs reversed. This module is distributed under the same terms as