summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/scripts/latexindent/LatexIndent/AlignmentAtAmpersand.pm
blob: 14f141b060cbd747f4fe11a17f596d0874d3fdc7 (plain)
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
package LatexIndent::AlignmentAtAmpersand;
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	See http://www.gnu.org/licenses/.
#
#	Chris Hughes, 2017
#
#	For all communication, please visit: https://github.com/cmhughes/latexindent.pl
use strict;
use warnings;
use utf8;
use Unicode::GCString;
use Data::Dumper;
use Exporter qw/import/;
use LatexIndent::TrailingComments qw/$trailingCommentRegExp/;
use LatexIndent::Switches qw/$is_t_switch_active $is_tt_switch_active/;
use LatexIndent::GetYamlSettings qw/%masterSettings/;
use LatexIndent::Tokens qw/%tokens/;
our @ISA = "LatexIndent::Document"; # class inheritance, Programming Perl, pg 321
our @EXPORT_OK = qw/align_at_ampersand find_aligned_block/;
our $alignmentBlockCounter;

sub find_aligned_block{
    my $self = shift;

    return unless (${$self}{body} =~ m/(?!<\\)%\*\h*\\begin\{/s);

    # aligned block
	#      %* \begin{tabular}
	#         1 & 2 & 3 & 4 \\
	#         5 &   & 6 &   \\
	#        %* \end{tabular}
    $self->logger('looking for ALIGNED blocks marked by comments','heading')if($is_t_switch_active);
    $self->logger(Dumper(\%{$masterSettings{lookForAlignDelims}})) if($is_t_switch_active);
    while( my ($alignmentBlock,$yesno)= each %{$masterSettings{lookForAlignDelims}}){
        if(ref $yesno eq "HASH"){
              $yesno = (defined ${$yesno}{delims} ) ? ${$yesno}{delims} : 1;
            }
        if($yesno){
            $self->logger("looking for $alignmentBlock:$yesno environments");

            my $noIndentRegExp = qr/
                            (
                                (?!<\\)
                                %
                                \*
                                \h*                     # possible horizontal spaces
                                \\begin\{
                                        $alignmentBlock  # environment name captured into $2
                                       \}               # %* \begin{alignmentBlock} statement
                            )
                            (
                                .*?
                            )
                            \R
                            \h*
                            (
                                (?!<\\)
                                %\*                     # %
                                \h*                     # possible horizontal spaces
                                \\end\{$alignmentBlock\} # \end{alignmentBlock}
                            )                           # %* \end{<something>} statement
                            #\R
                        /sx;

            while( ${$self}{body} =~ m/$noIndentRegExp/sx){

              ${$self}{body} =~ s/
                                    $noIndentRegExp
                                /
                                    # create a new Environment object
                                    my $alignmentBlock = LatexIndent::AlignmentAtAmpersand->new( begin=>$1,
                                                                          body=>$2,
                                                                          end=>$3,
                                                                          name=>$alignmentBlock,
                                                                          modifyLineBreaksYamlName=>"environments",
                                                                          linebreaksAtEnd=>{
                                                                            begin=>1,
                                                                            body=>1,
                                                                            end=>0,
                                                                          },
                                                                          );
            
                                    # the settings and storage of most objects has a lot in common
                                    $self->get_settings_and_store_new_object($alignmentBlock);
                                    ${@{${$self}{children}}[-1]}{replacementText};
                              /xseg;
            } 
      } else {
            $self->logger("*not* looking for $alignmentBlock as $alignmentBlock:$yesno");
      }
    }
    return;
}

sub modify_line_breaks_settings{
    return;
}

sub tasks_particular_to_each_object{
    return;
}

sub create_unique_id{
    my $self = shift;

    $alignmentBlockCounter++;
    ${$self}{id} = "$tokens{alignmentBlock}$alignmentBlockCounter";
    return;
}

sub align_at_ampersand{
    my $self = shift;
    return if(${$self}{bodyLineBreaks}==0);

    # calculate the maximum number of ampersands in a row in the body
    my $maximumNumberOfAmpersands = 0;
    foreach(split("\n",${$self}{body})){
        my $numberOfAmpersands = () = $_ =~ /(?<!\\)&/g;
        $maximumNumberOfAmpersands = $numberOfAmpersands if($numberOfAmpersands>$maximumNumberOfAmpersands);
    }

    # create an array of zeros
    my @maximumColumnWidth = (0) x ($maximumNumberOfAmpersands+1); 
    my @maximumColumnWidthMC = (0) x ($maximumNumberOfAmpersands+1); 

    # array for the new body
    my @formattedBody;

    # now loop back through the body, and store the maximum column size
    foreach(split("\n",${$self}{body})){
        # remove \\ and anything following it
        my $endPiece;
        if($_ =~ m/(\\\\.*)/){
            $_ =~ s/(\\\\.*)//;
            $endPiece = $1;
        }

        # remove any trailing comments
        my $trailingComments;
        if($_ =~ m/$trailingCommentRegExp/ ){
            $_ =~ s/($trailingCommentRegExp)//;
            $trailingComments = $1; 
        }

        # count the number of ampersands in the current row
        my $numberOfAmpersands = () = $_ =~ /(?<!\\)&/g;

        # switch for multiColumGrouping
        my $multiColumnGrouping = ($_ =~ m/\\multicolumn/ and ${$self}{multiColumnGrouping});
        my $alignRowsWithoutMaxDelims = ${$self}{alignRowsWithoutMaxDelims};

        # by default, the stripped row is simply the current row
        my $strippedRow = $_;

        # loop through the columns
        my $columnCount = 0;

        # format switch off by default
        my $formatRow = 0;

        # store the column sizes for measuring and comparison purposes
        my @columnSizes = ();

        # we will store the columns in each row
        my @columns;

        # need to have at least one ampersand, or contain a \multicolumn command
        if( ($_ =~ m/(?<!\\)&/ and ( ($numberOfAmpersands == $maximumNumberOfAmpersands)||$multiColumnGrouping||$alignRowsWithoutMaxDelims ) )
                                                or
                            ($multiColumnGrouping and $alignRowsWithoutMaxDelims) ){
            # remove space at the beginning of a row, surrounding &, and at the end of the row
            $_ =~ s/(?<!\\)\h*(?<!\\)&\h*/&/g;
            $_ =~ s/^\h*//g;
            $_ =~ s/\h*$//g;

            # if the line finishes with an &, then add an empty space,
            # otherwise the column count is off
            $_ .= ($_ =~ m/(?<!\\)&$/ ? " ":q());

            # store the columns, which are either split by & 
            # or otherwise simply the current line, if for example, the current line simply
            # contains \multicolumn{8}... \\  (see test-cases/texexchange/366841-zarko.tex, for example)
            @columns = ($_ =~ m/(?<!\\)&/ ? split(/(?<!\\)&/,$_) : $_);

            # empty the white-space-stripped row
            $strippedRow = '';
            foreach my $column (@columns){
                # if a column has finished with a \ then we need to add a trailing space, 
                # otherwise the \ can be put next to &. See test-cases/texexchange/112343-gonzalo for example
                $column .= ($column =~ m/\\$/ ? " ": q());

                # store the column size
                # reference: http://www.perl.com/pub/2012/05/perlunicook-unicode-column-width-for-printing.html
                my $gcs  = Unicode::GCString->new($column);
                my $columnWidth = $gcs->columns();

                # multicolumn cells need a bit of special care
                if($multiColumnGrouping and $column =~ m/\\multicolumn\{(\d+)\}/ and $1>1){
                    $maximumColumnWidthMC[$columnCount] = $columnWidth if( defined $maximumColumnWidthMC[$columnCount] and ($columnWidth > $maximumColumnWidthMC[$columnCount]) );
                    $columnWidth = 1 if($multiColumnGrouping and ($column =~ m/\\multicolumn\{(\d+)\}/));
                }

                # store the maximum column width
                $maximumColumnWidth[$columnCount] = $columnWidth if( defined $maximumColumnWidth[$columnCount] and ($columnWidth > $maximumColumnWidth[$columnCount]) );

                # put the row back together, using " " if the column is empty
                $strippedRow .= ($columnCount>0 ? "&" : q() ).($columnWidth > 0 ? $column: " ");

                # store the column width
                $columnSizes[$columnCount] = $columnWidth; 

                # move on to the next column
                if($multiColumnGrouping and ($column =~ m/\\multicolumn\{(\d+)\}/)){
                    # columns that are within the multiCol statement receive a width of -1
                    for my $i (($columnCount+1)..($columnCount+$1)){
                        $columnSizes[$i] = -1; 
                    }
                    # update the columnCount to account for the multiColSpan
                    $columnCount += $1; 
                } else {
                    $columnCount++;
                }
            }

            # toggle the formatting switch
            $formatRow = 1;
        } elsif($endPiece and ${$self}{alignDoubleBackSlash}){
            # otherwise a row could contain no ampersands, but would still desire
            # the \\ to be aligned, see test-cases/alignment/multicol-no-ampersands.tex
            @columns = $_;
            $formatRow = 1;
        }

        # store the information
        push(@formattedBody,{
                            row=>$strippedRow,
                            format=>$formatRow,
                            multiColumnGrouping=>$multiColumnGrouping,
                            columnSizes=>\@columnSizes,
                            columns=>\@columns,
                            endPiece=>($endPiece ? $endPiece :q() ),
                            trailingComment=>($trailingComments ? $trailingComments :q() )});
    }

    # output some of the info so far to the log file
    $self->logger("Maximum column sizes of horizontally stripped formatted block (${$self}{name}): @maximumColumnWidth") if $is_t_switch_active;
    $self->logger("align at ampersand: ${$self}{lookForAlignDelims}") if $is_t_switch_active;
    $self->logger("align at \\\\: ${$self}{alignDoubleBackSlash}") if $is_t_switch_active;
    $self->logger("spaces before \\\\: ${$self}{spacesBeforeDoubleBackSlash}") if $is_t_switch_active;
    $self->logger("multi column grouping: ${$self}{multiColumnGrouping}") if $is_t_switch_active;
    $self->logger("align rows without maximum delimeters: ${$self}{alignRowsWithoutMaxDelims}") if $is_t_switch_active;

    # acount for multicolumn grouping, if the appropriate switch is set
    if(${$self}{multiColumnGrouping}){
        foreach(@formattedBody){
            if(${$_}{format} and ${$_}{row} !~ m/^\h*$/){

                # set a columnCount, which will vary depending on multiColumnGrouping settings or not
                my $columnCount=0;

                # loop through the columns
                foreach my $column (@{${$_}{columns}}){
                    # calculate the width of the current column 
                    my $gcs  = Unicode::GCString->new($column);
                    my $columnWidth = $gcs->columns();

                    # check for multiColumnGrouping
                    if(${$_}{multiColumnGrouping} and $column =~ m/\\multicolumn\{(\d+)\}/ and $1>1){
                        my $multiColSpan = $1;

                        # for example, \multicolumn{3}{c}{<stuff>} spans 3 columns, so 
                        # the maximum column needs to account for this (subtract 1 because of 0 index in perl arrays)
                        my $columnMax = $columnCount+$multiColSpan-1;

                        # groupingWidth contains the total width of column sizes grouped 
                        # underneath the \multicolumn{} statement
                        my $groupingWidth = 0;
                        my $maxGroupingWidth = 0;
                        foreach (@formattedBody){
                           $groupingWidth = 0;

                            # loop through the columns covered by the multicolumn statement
                            foreach my $j ($columnCount..$columnMax){
                                if(  defined @{${$_}{columnSizes}}[$j] 
                                             and 
                                     @{${$_}{columnSizes}}[$j] >= 0
                                             and
                                         ${$_}{format} 
                                          ){
                                    $groupingWidth += (defined $maximumColumnWidth[$j] ? $maximumColumnWidth[$j] : 0); 
                                } else {
                                    $groupingWidth = 0;
                                }
                            }

                            # update the maximum grouping width
                            $maxGroupingWidth = $groupingWidth if($groupingWidth > $maxGroupingWidth);

                            # the cells that receive multicolumn grouping need extra padding; in particular
                            # the *last* cell of the multicol group receives the padding, hence the
                            # use of $columnMax below 
                            if(defined @{${$_}{columnSizes}}[$columnMax] and ($columnWidth > ($groupingWidth+3*($multiColSpan-1)) ) and @{${$_}{columnSizes}}[$columnMax] >= 0){
                                @{${$_}{multiColPadding}}[$columnMax] = $columnWidth-$groupingWidth-3*($multiColSpan-1);

                                # also need to account for maximum column width *including* other multicolumn statements
                                if($maximumColumnWidthMC[$columnCount]>$columnWidth){
                                    @{${$_}{multiColPadding}}[$columnMax] += ($maximumColumnWidthMC[$columnCount]-$columnWidth); 
                                }
                            }
                        }
                        # update it to account for the ampersands and 1 space either side of ampersands (total of 3)
                        $maxGroupingWidth += ($multiColSpan-1)*3;

                        # store the maxGroupingWidth for use in the next loop
                        @{${$_}{maxGroupingWidth}}[$columnCount] = $maxGroupingWidth; 

                        # update the columnCount to account for the multiColSpan
                        $columnCount += $multiColSpan - 1;
                    } 

                    # increase the column count
                    $columnCount++;
                }
            } 
        }
    }

    # the maximum row width will be used in aligning (or not) the \\
    my $maximumRowWidth = 0;

    # now that the multicolumn widths have been accounted for, loop through the body
    foreach(@formattedBody){
        if(${$_}{format} and ${$_}{row} !~ m/^\h*$/){

            # set a columnCount, which will vary depending on multiColumnGrouping settings or not
            my $columnCount=0;
            my $tmpRow = q();

            # loop through the columns
            foreach my $column (@{${$_}{columns}}){
                # calculate the width of the current column 
                my $gcs  = Unicode::GCString->new($column);
                my $columnWidth = $gcs->columns();

                # reset the column padding
                my $padding = q();

                # check for multiColumnGrouping
                if(${$_}{multiColumnGrouping} and $column =~ m/\\multicolumn\{(\d+)\}/ and $1>1){
                    my $multiColSpan = $1;

                    # groupingWidth contains the total width of column sizes grouped 
                    # underneath the \multicolumn{} statement
                    my $maxGroupingWidth = ${${$_}{maxGroupingWidth}}[$columnCount];

                    # set the padding; we need
                    #       maximum( $maxGroupingWidth, $maximumColumnWidthMC[$columnCount] )
                    # rather than load another module to give the 'max' function, I use the ternary operator
                    my $maxValueToUse = 0;
                    if(defined $maximumColumnWidthMC[$columnCount]){
                        $maxValueToUse = ($maxGroupingWidth>$maximumColumnWidthMC[$columnCount]?$maxGroupingWidth:$maximumColumnWidthMC[$columnCount]);
                    } else {
                        $maxValueToUse = $maxGroupingWidth;
                    }

                    # calculate the padding
                    $padding = " " x ( $maxValueToUse  >= $columnWidth ? $maxValueToUse  - $columnWidth : 0 );

                    # update the columnCount to account for the multiColSpan
                    $columnCount += $multiColSpan - 1;
                } else {
                    # compare the *current* column width with the *maximum* column width
                    $padding = " " x (defined $maximumColumnWidth[$columnCount] and $maximumColumnWidth[$columnCount] >= $columnWidth ? $maximumColumnWidth[$columnCount] - $columnWidth : 0);
                }

                # either way, the row is formed of "COLUMN + PADDING"
                $tmpRow .= $column.$padding.(defined @{${$_}{multiColPadding}}[$columnCount] ? " " x @{${$_}{multiColPadding}}[$columnCount]: q())." & ";
                $columnCount++;
            }

            # remove the final &
            $tmpRow =~ s/\h&\h*$/ /;
            $tmpRow =~ s/\h*$/ /;

            # replace the row with the formatted row
            ${$_}{row} = $tmpRow;

            # update the maximum row width
            my $gcs  = Unicode::GCString->new($tmpRow);
            ${$_}{rowWidth} = $gcs->columns();
            $maximumRowWidth = ${$_}{rowWidth} if(${$_}{rowWidth} >  $maximumRowWidth);
        } 
    }

    # final loop through to get \\ aligned
    foreach (@formattedBody){
        # reset the padding
        my $padding = q();

        # possibly adjust the padding
        if(${$_}{format} and ${$_}{row} !~ m/^\h*$/){
            # remove trailing horizontal space if ${$self}{alignDoubleBackSlash} is set to 0
            ${$_}{row} =~ s/\h*$// if (!${$self}{alignDoubleBackSlash});
            
            # format spacing infront of \\
            if(defined ${$self}{spacesBeforeDoubleBackSlash} and ${$self}{spacesBeforeDoubleBackSlash}<0 and !${$self}{alignDoubleBackSlash}){
                # zero spaces (possibly resulting in un-aligned \\)
                $padding = q();
            } elsif(defined ${$self}{spacesBeforeDoubleBackSlash} and ${$self}{spacesBeforeDoubleBackSlash}>=0 and !${$self}{alignDoubleBackSlash}){
                # specified number of spaces (possibly resulting in un-aligned \\)
                $padding = " " x (${$self}{spacesBeforeDoubleBackSlash});
            } else {
                # aligned \\
                $padding = " " x ($maximumRowWidth - ${$_}{rowWidth});
            }
        }

        # format the row, and put the trailing \\ and trailing comments back into the row
        ${$_}{row} .= $padding.(${$_}{endPiece} ? ${$_}{endPiece} :q() ).(${$_}{trailingComment}? ${$_}{trailingComment} : q() );
    }

    # to the log file
    if($is_tt_switch_active){    
        $self->logger(${$_}{row},'ttrace') for @formattedBody;
    }

    # delete the original body
    ${$self}{body} = q();

    # update the body
    ${$self}{body} .= ${$_}{row}."\n" for @formattedBody;

    # if the \end{} statement didn't originally have a line break before it, we need to remove the final 
    # line break added by the above
    ${$self}{body} =~ s/\h*\R$//s if !${$self}{linebreaksAtEnd}{body};
}

1;