Text-Aligner-0.07/000755 000765 000024 00000000000 11443011277 014041 5ustar00annostaff000000 000000 Text-Aligner-0.07/.cvsignore000644 000765 000024 00000000031 07564477036 016055 0ustar00annostaff000000 000000 blib Makefile pm_to_blib Text-Aligner-0.07/Changes000644 000765 000024 00000001371 11443011112 015322 0ustar00annostaff000000 000000 Revision history for Perl extension Text::Aligner. 0.01 Mon Nov 11 20:38:07 2002 - original version; created by ExtUtils::ModuleMaker 0.204 - initial release to CPAN 03.12.02 0.02 Tue Dec 3 23:52:46 CET 2002 0.03 Tue May 4 23:06:37 CEST 2004 Corrected a slew of (spurious) warnings during tests See rt.cpan.org: Bug #6208 Warnings in make test 0.04 Mi 5 Mai 2010 02:55:34 CEST Tests fail with perl 5.130 (this righted itself, not released) 0.05 Sa 28 Aug 2010 21:23:16 CEST added color support to aligner 0.06 Sa 28 Aug 2010 23:21:28 CEST bug fix: auto alignment didn't recognize colorized numbers 0.07 So 12 Sep 2010 01:31:54 CEST One colorskip-dependent test moved into skip block as per rt. #61276 Text-Aligner-0.07/lib/000755 000765 000024 00000000000 11443011277 014607 5ustar00annostaff000000 000000 Text-Aligner-0.07/LICENSE000644 000765 000024 00000047370 07564477036 015103 0ustar00annostaff000000 000000 Terms of Perl itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" ---------------------------------------------------------------------------- The General Public License (GPL) Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ---------------------------------------------------------------------------- The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Text-Aligner-0.07/Makefile.PL000644 000765 000024 00000000700 11436271551 016015 0ustar00annostaff000000 000000 use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'Text::Aligner', VERSION_FROM => 'lib/Text/Aligner.pm', # finds $VERSION AUTHOR => 'Anno Siegel (siegel@zrz.tu-berlin.de)', ABSTRACT => 'Align text in columns', PREREQ_PM => { 'Test::More' => 0, 'Term::ANSIColor' => '2.01', }, ); Text-Aligner-0.07/MANIFEST000644 000765 000024 00000000302 10046004370 015157 0ustar00annostaff000000 000000 .cvsignore Changes LICENSE MANIFEST MANIFEST.SKIP Makefile.PL README lib/Text/Aligner.pm t/01_ini.t t/10_Aligner.t META.yml Module meta-data (added by MakeMaker) Text-Aligner-0.07/MANIFEST.SKIP000644 000765 000024 00000000221 07645775740 015757 0ustar00annostaff000000 000000 ^blib/ ^Makefile$ ^Makefile\.[a-z]+$ ^pm_to_blib$ CVS/.* ,v$ ^tmp/ \.old$ \.bak$ ~$ ^# \.shar$ \.tar$ \.tgz$ \.tar\.gz$ \.zip$ _uu$ ^ttt* ^dist/ Text-Aligner-0.07/META.yml000644 000765 000024 00000001101 11443011277 015303 0ustar00annostaff000000 000000 --- #YAML:1.0 name: Text-Aligner version: 0.07 abstract: Align text in columns author: - Anno Siegel (siegel@zrz.tu-berlin.de) license: unknown distribution_type: module configure_requires: ExtUtils::MakeMaker: 0 build_requires: ExtUtils::MakeMaker: 0 requires: Term::ANSIColor: 2.01 Test::More: 0 no_index: directory: - t - inc generated_by: ExtUtils::MakeMaker version 6.56 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 Text-Aligner-0.07/README000644 000765 000024 00000002222 07573052363 014731 0ustar00annostaff000000 000000 From the Text::Aligner documentation: NAME Text::Aligner SYNOPSIS use Text::Aligner qw( align); # Print the words "just a test!" right-justified each on a line: my @lines = align( 'right', qw( just a test!); print "$_\n" for @lines; DESCRIPTION Text::Aligner exports a single function, align(), which is used to justify strings to various alignment styles. The alignment specification is the first argument, followed by any number of scalars which are subject to alignment. The operation depends on context. In list context, a list of the justified scalars is returned. In scalar context, the justified arguments are joined into a single string with newlines appended. The original arguments remain unchanged. In void context, in-place justification is attempted. In this case, all arguments must be lvalues. Align() also does one level of scalar dereferencing. That is, whenever one of the arguments is a scalar reference, the scalar pointed to is aligned instead. Other references are simply stringified. An undefined argument is interpreted as an empty string without complaint. Text-Aligner-0.07/t/000755 000765 000024 00000000000 11443011277 014304 5ustar00annostaff000000 000000 Text-Aligner-0.07/t/01_ini.t000644 000765 000024 00000000335 07564477036 015573 0ustar00annostaff000000 000000 # t/01_ini.t; just to load Text::Aligner by using it $|++; print "1..1 "; my($test) = 1; # 1 load use Text::Aligner; my($loaded) = 1; $loaded ? print "ok $test " : print "not ok $test "; $test++; # end of t/01_ini.t Text-Aligner-0.07/t/10_Aligner.t000644 000765 000024 00000012722 11443010445 016352 0ustar00annostaff000000 000000 use Test::More; use strict; my $n_tests; use Text::Aligner; use Term::ANSIColor; use constant HAVE_COLORSTRIP => defined &Term::ANSIColor::colorstrip; # MaxKeeper BEGIN { $n_tests += 7 } my $mk = Text::Aligner::MaxKeeper->new; is( $mk->max, undef); $mk->remember( $_) for 0, 5, 3, -1, 5, 1; is( $mk->max, 5); $mk->forget( -1); is( $mk->max, 5); $mk->forget( 5); is( $mk->max, 5); $mk->forget( 5); is( $mk->max, 3); $mk->remember( 3); $mk->remember( 2); $mk->forget( 3); is( $mk->max, 3); $mk->forget( 3); is( $mk->max, 2); # _compile_alispec BEGIN { $n_tests += 6 } BEGIN { *_compile_alispec = \ &Text::Aligner::_compile_alispec } my @specs = qw( left center right num); is( ref( ( _compile_alispec( $_))[ 1]), 'CODE') for @specs, 0.5, 'num(,)', sub {}; # expected positions for combinations of string/specification BEGIN { $n_tests += 12*7 } # number of strings * number of specs no warnings 'qw'; my @strings = ( '', qw( x xy xyx xxxyxxxxxx 0 1 1. 12.13 .9 123 6,3)); my %ans = ( left => [ 0, qw( 0 0 0 0 0 0 0 0 0 0 0)], center => [ 0, qw( 0 1 1 5 0 0 1 2 1 1 1)], right => [ 0, qw( 1 2 3 10 1 1 2 5 2 3 3)], num => [ 0, qw( 1 2 3 10 1 1 1 2 0 3 3)], 'num(,)' => [ 0, qw( 1 2 3 10 1 1 2 5 2 3 1)], qr/x/ => [ 0, qw( 0 0 0 0 1 1 2 5 2 3 3)], qr/y/ => [ 0, qw( 1 1 1 3 1 1 2 5 2 3 3)], ); while ( my ( $spec, $ans) = each %ans ) { my @ans = @$ans; my $use_spec = $spec; $use_spec = qr/$use_spec/ if $use_spec =~ /\(\?/; # de-stringify Regex my $code = ( _compile_alispec( $use_spec))[ 1]; # the width is not tested for my $str ( @strings ) { my $wanted = shift @ans; my $got = $code->( $str); my $showstr = "'$str'"; is( "($spec, $showstr) -> $got", "($spec, $showstr) -> $wanted"); } } # Text::Aligner class BEGIN { $n_tests += 1 } # number recognition BEGIN { $n_tests += 2 } ok(Text::Aligner::_is_number(12.3)); ok(!Text::Aligner::_is_number('abc')); # moved to SKIP block # ok(Text::Aligner::_is_number(colored('123', 'red'))); my $ali = Text::Aligner->new; is( ref $ali, 'Text::Aligner'); # full sample # undef, '', ' ', qw( Z xxZ xxxxxxxxxZ 0 19 .1 9. 9.11 11119.1 1119.11111); # reduced sample for distribution use constant STRINGS => undef, qw( Z xxxxZ 0 9.11 1119.111111); use constant SPECS => qw( left center right num auto); BEGIN { my $nstr = @{ [ STRINGS ]}; my $nspec = @{ [ SPECS ]}; $n_tests += $nspec*( $nstr + 2*$nstr*$nstr); # according to program below } for my $spec ( SPECS ) { my $ali = Text::Aligner->new( $spec); for my $str ( STRINGS ) { my $res = $ali->justify( $str); my $diag = 'ok'; my $strout = defined $str ? $str : ''; $diag = "new $spec-aligner justifies '$strout' to '$res'" unless $strout eq $res; is( $diag, 'ok'); } for my $init ( STRINGS ) { $ali->alloc( $init); for my $str ( STRINGS ) { my $res = $ali->justify( $str); my $diag = ''; defined $init or $init = ''; if ( length( $res) != length( $init) ) { $diag = "$spec-aligner with '$init' justifies '$str' to '$res' (length)"; } is( $diag, ''); $diag = ''; defined $str or $str = ''; if ( $spec =~ /num/ and $str =~ /[9Z]/ and $init =~ /[9Z]/ ) { my $initloc = index( $init, '9'); $initloc = index( $init, 'Z') if $init =~ /Z/; my $resloc = index( $res, '9'); $resloc = index( $res, 'Z') if $res =~ /Z/; $diag = ( $initloc != $resloc); } $diag = "$spec-aligner with '$init' justifies '$str' to '$res' (pos)" if $diag; is( $diag, ''); } $ali->_forget( $init); } } # align() function BEGIN { $n_tests += 21 } use Text::Aligner qw( align); ok( defined &align); # Basic functionality my @col = qw( just a test!); my @save_col = @col; # copy for later my @res = align( '', @col); is( $res[ 0], 'just '); is( $res[ 1], 'a '); is( $res[ 2], 'test!'); # scalar context my $res = align( 'right', @col); is( $res, " just\n a\ntest!\n"); # original unchanged? is( join( '|', @col), join( '|', @save_col)); # in-place alignment align( '', @col); is( $col[ 0], 'just '); is( $col[ 1], 'a '); is( $col[ 2], 'test!'); # scalar deref (not sure i like this feature) @col = @save_col; my $scalar = 'now'; align( '', $col[ 0], \ $col[ 1], $col[ 2], \ $scalar); is( $col[ 0], 'just '); is( $col[ 1], 'a '); is( $col[ 2], 'test!'); is( $scalar, 'now '); # color support SKIP: { my $ver = $Term::ANSIColor::VERSION; skip( "Term::ANSIColor $ver doesn't support colorstrip", 6, ) unless HAVE_COLORSTRIP; *colorstrip = \ &Term::ANSIColor::colorstrip; my @col = ( 'Just', colored('a', 'green'), colored('test!', 'bold'), colored(123.456, 'red'), colored( 12, 'red'), ); my @res = align( 'auto', @col); my @ref = align( 'auto', map colorstrip($_), @col); my @check = map colorstrip($_), @res; is($check[$_], $ref[$_], "color support $_") for 0 .. $#col; ok(Text::Aligner::_is_number(colored('123', 'red'))); } # fail as expected? eval { align( '', 'wirdnix') }; like( $@, qr/^Modification of a read-only value/ ); BEGIN { plan tests => $n_tests } Text-Aligner-0.07/lib/Text/000755 000765 000024 00000000000 11443011277 015533 5ustar00annostaff000000 000000 Text-Aligner-0.07/lib/Text/Aligner.pm000644 000765 000000 00000033356 11443011144 017450 0ustar00annowheel000000 000000 # Text::Aligner - Align text in columns package Text::Aligner; use strict; use warnings; BEGIN { use Exporter (); use vars qw ($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = '0.07'; @ISA = qw (Exporter); @EXPORT = qw (); @EXPORT_OK = qw ( align); %EXPORT_TAGS = (); } # this is a non-method, and currently the only user interface sub align ($@) { my $ali = Text::Aligner->new( shift); $ali->alloc( map ref eq 'SCALAR' ? $$_ : $_, @_); if ( defined wantarray ) { my @just = map $ali->justify( ref eq 'SCALAR' ? $$_ : $_), @_; return @just if wantarray; return join "\n", @just, ''; } else { for ( @_ ) { $_ = $ali->justify( $_) for ref eq 'SCALAR' ? $$_ : $_; # one-shot } } } ### class Text::Aligner sub _new { # internal creator my $class = shift; my ( $width, $pos) = @_; # both method-or-coderef (this is very general) bless { width => $width, pos => $pos, left => Text::Aligner::MaxKeeper->new, right => Text::Aligner::MaxKeeper->new, }, $class; } # create an aligner sub new { my ( $class, $spec) = @_; $spec ||= 0; # left alignment is default my $al; if ( !ref( $spec) and $spec =~ s/^auto/num/ ) { $al = Text::Aligner::Auto->_new( $spec); } else { $al = $class->_new( _compile_alispec( $spec)); } $al; } # return left and right field widths for an object sub _measure0 { my $al = shift; my $obj = shift; $obj = '' unless defined $obj; my ( $w, $p); if ( ref $obj ) { ( $w, $p) = ( $obj->$al->{ width}->(), $obj->$al->{ pos}->() ); } else { ( $w, $p) = ( $al->{ width}->( $obj), $al->{ pos}->( $obj) ); } $_ ||= 0 for $w, $p; ( $p, $w - $p); } use Term::ANSIColor; *colorstrip = \ &Term::ANSIColor::colorstrip; # early versions of Term::ANSIColor don't have colorstrip defined &colorstrip or *colorstrip = sub { shift }; # return left and right field widths for an object sub _measure { my $al = shift; my $obj = shift; $obj = '' unless defined $obj; my ( $wmeth, $pmeth) = @{ $al}{ qw( width pos)}; # support colorized strings $obj = colorstrip($obj) unless ref $obj; my $w = ref $wmeth ? $wmeth->( $obj) : $obj->$wmeth; my $p = ref $pmeth ? $pmeth->( $obj) : $obj->$pmeth; $_ ||= 0 for $w, $p; ( $p, $w - $p); } # return left and rigth maxima, or nothing if the aligner is empty sub _status { my @lr = ( $_[ 0]->{ left}->max, $_[ 0]->{ right}->max); # $l and $r should be both defined or undefined, unless the # MaxKeeper memory is corrupted by forgetting unremembered things. return unless defined( $lr[ 0]) and defined( $lr[ 1]); @lr; } # remember alignment requirements sub alloc { my $al = shift; for ( @_ ) { # $_ ||= ''; print "allocing '$_'\n"; my ( $l, $r) = $al->_measure( $_); $al->{ left}->remember( $l); # space needed left of pos $al->{ right}->remember( $r); # ...and right of pos } $al; } # release alignment requirement. it disturbs an aligner deeply to forget # things it hasn't remembered. the effects may be delayed. sub _forget { my $al = shift; for ( map defined() ? $_ : '', @_ ) { # print "forgetting '$_'\n"; my ( $l, $r) = $al->_measure( $_); $al->{ left}->forget( $l); $al->{ right}->forget( $r); } $al; } # justify a string. a string is aligned within the aligner's field, and # filled with blanks or cut to size, as appropriate. a string that has # been allocated will never be trimmed (that is the point of allocation). # if the aligner is empty it returns the string unaltered. sub justify { my $al = shift; my $str = shift; # print "justifying '$str'\n"; $str .= ''; # stringify (objects, numbers, undef) my ( $l_pad, $r_pad) = $al->_padding( $str); substr( $str, 0, -$l_pad) = '' if $l_pad < 0; # trim if negative substr( $str, $r_pad) = '' if $r_pad < 0; # ... both ends join $str, ' ' x $l_pad, ' ' x $r_pad; # pad if positive } # return two numbers that indicate how many blanks are needed on each side # of a string to justify it. Negative values mean trim that many characters. # an empty aligner returns ( 0, 0), so doesn't change anything. sub _padding { my $al = shift; my $str = shift; my ( $this_l, $this_r) = $al->_measure( $str); my ( $l_pad, $r_pad) = ( 0, 0); if ( $al->_status ) { ( $l_pad, $r_pad) = $al->_status; $l_pad -= $this_l; $r_pad -= $this_r; } ( $l_pad, $r_pad); } # _compile_alispec() returns positioners according to specification. In # effect, it is is the interpreter for alignment specifications. sub _compile_alispec { # it's a dirty job... my $width = sub { length shift }; # this is always so for string aligners my $pos; # the positioner we actually compile local $_ = shift || ''; # alignment specification if ( ref() eq 'Regexp' ) { my $regex = $_; # lexical copy! $pos = sub { local $_ = shift; return m/$regex/ ? $-[ 0] : length; # assume match after string }; } else { s/^left/0/; s/^center/0.5/; s/^right/1/; if ( _is_number( $_) ) { my $proportion = $_; # use lexical copy $pos = sub { int( $proportion*length shift) }; } elsif ( $_ =~ /^(?:num|point)(?:\((.*))?/ ) { my $point = defined $1 ? $1 : ''; $point =~ s/\)$//; # ignore trailing paren, if present length $point or $point = '.'; $pos = sub { index( shift() . $point, $point) } } else { $pos = sub { 0 }; } } ( $width, $pos); } # decide if a string is a number. (see perlfaq4). sub _is_number { my ($x) = @_; return 0 unless defined $x; return 0 if $x !~ /\d/; return 1 if $x =~ /^-?\d+\.?\d*$/; $x = colorstrip($x); $x =~ /^-?\d+\.?\d*$/ } package Text::Aligner::Auto; # Combined numeric and left alignment. Numbers are aligned numerically, # other strings are left-aligned. The resulting columns are interleaved # flush left and filled on the right if necessary. sub _new { # only called by Text::Aligner->new() my $class = shift; my $numspec = shift; # currently ignored bless { num => Text::Aligner->new( 'num'), # align numbers among themselves other => Text::Aligner->new, # left-align anything else }, $class; } sub alloc { my $aa = shift; my @num = grep _is_number( $_), @_; my @other = grep !_is_number( $_), @_; $aa->{ num}->alloc( @num); $aa->{ other}->alloc( @other); $aa; } sub _forget { my $aa = shift; $aa->{ num}->_forget( grep _is_number( $_), @_); $aa->{ other}->_forget( grep !_is_number( $_), @_); $aa; } # justify as required sub justify { my ( $aa, $str) = @_; # align according to type $str = $aa->{ _is_number( $str) ? 'num' : 'other'}->justify( $str); my $combi = Text::Aligner->new; # left-justify pre-aligned string # initialise to size of partial aligners. (don't initialise from # empty aligner) $combi->alloc( $aa->{ num}->justify( '')) if $aa->{ num}->_status; $combi->alloc( $aa->{ other}->justify( '')) if $aa->{ other}->_status; $combi->justify( $str); } # for convenience BEGIN { # import _is_number() *_is_number = \ &Text::Aligner::_is_number; } package Text::Aligner::MaxKeeper; # Keep the maximum of a dynamic set of numbers. Optimized for the case of # a relatively small range of numbers that may occur repeatedly. sub new { bless { max => undef, seen => {}, }, shift; } sub max { $_[ 0]->{ max} } sub remember { my ( $mk, $val) = @_; _to_max( $mk->{ max}, $val); $mk->{ seen}->{ $val}++; $mk; } sub forget { my ( $mk, $val) = @_; if ( exists $mk->{ seen}->{ $val} ) { my $seen = $mk->{ seen}; unless ( --$seen->{ $val} ) { delete $seen->{ $val}; if ( $mk->{ max} == $val ) { # lost the maximum, recalculate undef $mk->{ max}; _to_max( $mk->{ max}, keys %$seen); } } } $mk; } sub _to_max { my $var = \ shift; defined $_ and ( not defined $$var or $$var < $_) and $$var = $_ for @_; $$var; } ########################################### main pod documentation begin ## =head1 NAME Text::Aligner =head1 SYNOPSIS use Text::Aligner qw( align); # Print the words "just a test!" right-justified each on a line: my @lines = align( 'right', qw( just a test!); print "$_\n" for @lines; =head1 DESCRIPTION Text::Aligner exports a single function, align(), which is used to justify strings to various alignment styles. The alignment specification is the first argument, followed by any number of scalars which are subject to alignment. The operation depends on context. In list context, a list of the justified scalars is returned. In scalar context, the justified arguments are joined into a single string with newlines appended. The original arguments remain unchanged. In void context, in-place justification is attempted. In this case, all arguments must be lvalues. Align() also does one level of scalar dereferencing. That is, whenever one of the arguments is a scalar reference, the scalar pointed to is aligned instead. Other references are simply stringified. An undefined argument is interpreted as an empty string without complaint. Alignment respects colorizing escape sequences a la Term::ANSICOLOR, which means it knows that thses sequences don't take up space on the screen. =head1 ALIGNMENT The first argument of the align() function is an alignment style, a single scalar. It can be one of the strings "left", "right", "center", "num", "point", or "auto", or a regular expression (qr/.../), or a coderef. A default style of "left" is assumed for every other value, including "" and undef. "left", "right" and "center" have the obvious meanings. These can also be given as numbers 0, 1, and 0.5 respectively. (Other numbers are also possible, but probably not very useful). "num", and its synonym "point", specify that the decimal points be aligned (assumed on the right, unless present). Arbitrary (non-numeric) strings are also aligned in this manner, so they end up one column left of the (possibly assumed) decimal point, flush right with any integers. For the occasional string like "inf", or "-" for missing values, this may be the right place. A string-only column ends up right-aligned (unless there are points present). The "auto" style separates numeric strings (that are composed of "-", ".", and digits in the usual manner) and aligns them numerically. Other strings are left aligned with the number that sticks out farthest to the left. This gives left alignment for string-only columns and numeric alignment for columns of numbers. In mixed columns, strings are reasonably placed to serve as column headings or intermediate titles. With "num" (and "point") it is possible to specify another character for the decimal point in the form "num(,)". In fact, you can specify any string after a leading "(", and the closing ")" is optional. "point(=>)" could be used to align certain pieces of Perl code. This option is currently not available with "auto" alignment (because recognition of numbers is Anglo-centric). If a regular expression is specified, the points are aligned where the first match of the regex starts. A match is assumed immediately after the string if it doesn't match. A regular expression is a powerful way of alignment specification. It can replace most others easily, except center alignment and, of course, the double action of "auto". =head1 POSITIONERS For entirely self-defined forms of alignment, a coderef, also known as a positioner, can be given instead of an alignment style. This code will be called once or more times with the string to be aligned as its argument. It must return two numbers, a width and a position, that describe how to align a string with other strings. The width should normally be the length of the string. The position defines a point relative to the beginning of the string, which is aligned with the positions given for other strings. A zero position for all strings results in left alignment, positioning to the end of the string results in right alignment, and returning half the length gives center alignment. "num" alignment is realized by marking the position of the decimal point. Note that the position you return is a relative measure. Adding a constant value to all positions results in no change in alignment. It doesn't have to point inside the string (as in right alignment, where it points one character past the end of the string). The first return value of a positioner should almost always be the length of the given string. It may be useful to ly about the string length if the string contains escape sequences that occupy no place on screen. =head1 USAGE use Text::Aligner qw( align); align( $style, $str, ...); $style must be given and must be an alignment specification. Any number of scalars can follow. An argument that contains a scalar reference is dereferenced before it is used. In scalar and list context, the aligned strings are returned. In void context, the values are aligned in place and must be lvalues. =head1 BUGS None known as of realease, but... =head1 AUTHOR Anno Siegel CPAN ID: ANNO =head1 COPYRIGHT Copyright (c) 2002 Anno Siegel. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of the license can be found in the LICENSE file included with this module. =head1 SEE ALSO perl(1) Text::Table =cut 1; #this line is important and will help the module return a true value __END__