summaryrefslogtreecommitdiff
path: root/support/latexindent/LatexIndent/Lines.pm
blob: d1ee631b0840eac4319b3c2170c9056fc682adc6 (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
package LatexIndent::Lines;
#	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 Exporter qw/import/;
use LatexIndent::LogFile qw/$logger/;
use LatexIndent::Switches qw/%switches/;
use LatexIndent::Verbatim qw/%verbatimStorage/;
our @ISA = "LatexIndent::Document"; # class inheritance, Programming Perl, pg 321
our @EXPORT_OK = qw/lines_body_selected_lines lines_verbatim_create_line_block/;

sub lines_body_selected_lines {
    my $self = shift;
    my @lines = @{$_[0]};

    # strip all space from lines switch
    $switches{lines} =~ s/\h//sg;

    # convert multiple - into single
    $switches{lines} =~ s/-+/-/sg;

    $logger->info("*-n,--lines switch is active, operating on lines $switches{lines}"); 
    $logger->info("number of lines in file: ".($#lines+1));
    $logger->info("*interpretting $switches{lines}"); 
    
    my @lineRanges = split(/,/,$switches{lines});
    my @indentLineRange;
    my @NOTindentLineRange;

    my %minMaxStorage;
    my %negationMinMaxStorage;

    # loop through line ranges, which are separated by commas
    #
    #       --lines 3-15,17-19
    #
    foreach(@lineRanges){
      my $minLine = 0;
      my $maxLine = 0;
      my $negationMode = 0;

      #
      #  --lines !3-15
      #
      if($_ =~ m/!/s){
        $negationMode = 1;
        $_ =~ s/!//s;
        $logger->info("negation mode active as $_");
      }

      #  --lines min-max
      if($_ =~ m/-/s){
          ($minLine,$maxLine) = split(/-/,$_);
      } else {
          $minLine = $_;
          $maxLine = $_;
      }

      # both minLine and maxLine need to be INTEGERS
      if ($minLine !~ m/^\d+$/ or $maxLine !~ m/^\d+$/){
        $logger->warn("*$_ not a valid line specification; I'm ignoring this entry");
        next;
      }

      # swap minLine and maxLine if necessary
      if($minLine > $maxLine){
          ($minLine,$maxLine) = ($maxLine, $minLine);
      }
      
      # minline > number of lines needs addressing
      if ($minLine-1 > $#lines){
           $logger->warn("*--lines specified with min line $minLine which is *greater than* the number of lines in file: ".($#lines+1));
           $logger->warn("adjusting this value to be ".($#lines+1));
           $minLine = $#lines+1;
      }

      # maxline > number of lines needs addressing
      if ($maxLine-1 > $#lines){
           $logger->warn("*--lines specified with max line $maxLine which is *greater than* the number of lines in file: ".($#lines+1));
           $logger->warn("adjusting this value to be ".($#lines+1));
           $maxLine = $#lines+1;
      }

      # either store the negation, or not
      if($negationMode){
        $negationMinMaxStorage{$minLine} = $maxLine;
      } else {
        $minMaxStorage{$minLine} = $maxLine;
      }
      $logger->info("min line: $minLine, max line: $maxLine");
    } 
    
    # only proceed if we have a valid line range
    if ( (keys %minMaxStorage) < 1 and (keys %negationMinMaxStorage) < 1){
      $logger->warn("*--lines not specified with valid range: $switches{lines}");
      $logger->warn("entire body will be indented, and ignoring $switches{lines}");
      $switches{lines} = 0;
      ${$self}{body} = join("",@lines);
      return;
    } 
    
    # we need to perform the token check here
    ${$self}{body} = join("",@lines);
    $self->token_check;
    ${$self}{body} = q();

    # negated line ranges
    if (keys %negationMinMaxStorage >= 1){
        @NOTindentLineRange = &lines_sort_and_combine_line_range(\%negationMinMaxStorage);

        $logger->info("*negation line range summary: ");
        $logger->info("the number of NEGATION line ranges: ".(($#NOTindentLineRange+1)/2));
        $logger->info("the *sorted* NEGATION line ranges are in the form MIN-MAX: ");
        for (my $index=0; $index<(($#NOTindentLineRange+1)/2); $index++){
            $logger->info(join("-",@NOTindentLineRange[2*$index..2*$index+1]));

            if($index==0 and $NOTindentLineRange[2*$index]>1){
                $minMaxStorage{1} = $NOTindentLineRange[2*$index]-1;
            } elsif($index>0){
                $minMaxStorage{$NOTindentLineRange[2*$index-1]+1} = $NOTindentLineRange[2*$index]-1;
            }
        }

        # final range
        if($NOTindentLineRange[-1]<$#lines){
          $minMaxStorage{$NOTindentLineRange[-1]+1} = $#lines+1;
        }
    }

    @indentLineRange = &lines_sort_and_combine_line_range(\%minMaxStorage) if (keys %minMaxStorage >= 1) ;

    $logger->info("*line range summary: ");
    $logger->info("the number of indent line ranges: ".(($#indentLineRange+1)/2));
    $logger->info("the *sorted* line ranges are in the form MIN-MAX: ");
    for (my $index=0; $index<(($#indentLineRange+1)/2); $index++){
        $logger->info(join("-",@indentLineRange[2*$index..2*$index+1]));
    }

    my $startLine = 0;

    # now that we have the line range, we can sort arrange the body 
    while ($#indentLineRange>0){
        my $minLine = shift(@indentLineRange);
        my $maxLine = shift(@indentLineRange);

        # perl arrays start at 0
        $minLine--;
        $maxLine--;

        $self->lines_verbatim_create_line_block(\@lines,$startLine,$minLine-1) unless ($minLine == 0);

        ${$self}{body} .= join("",@lines[$minLine..$maxLine]);

        $startLine = $maxLine+1;
    }

    # final line range
    $self->lines_verbatim_create_line_block(\@lines,$startLine,$#lines) if($startLine<=$#lines);
    return;
}

sub lines_sort_and_combine_line_range{

    my %minMaxStorage = %{$_[0]};
    #
    #     --lines 8-10,4-5,1-2
    #
    # needs to be interpretted as 
    #
    #     --lines 1-2,4-5,8-10, 
    #
    # sort the line ranges by the *minimum* value, the associated 
    # maximum values will be arranged after this
    my @indentLineRange = sort { $a <=> $b } keys(%minMaxStorage);

    my @justMinimumValues = @indentLineRange; 
    for (my $index=0;$index<=$#justMinimumValues;$index++){
        splice(@indentLineRange,2*$index+1,0,$minMaxStorage{$justMinimumValues[$index]});
    }

    for (my $index=1;$index<(($#indentLineRange+1)/2);$index++){
        my $currentMin  = $indentLineRange[2*$index];
        my $currentMax  = $indentLineRange[2*$index+1];
        my $previousMax = $indentLineRange[2*$index-1];
        my $previousMin = $indentLineRange[2*$index-2];

        if ( ($currentMin - 1) <= $previousMax and ( $currentMax > $previousMax ) ){
            # overlapping line ranges, for example
            #
            #     --lines 3-5,4-10 
            #
            # needs to be interpretted as 
            #
            #     --lines 3-10 
            #
            $logger->info("overlapping line range found");
            $logger->info("line ranges (before): ".join(", ",@indentLineRange));
            splice(@indentLineRange,2*$index-1,2);
            $logger->info("line ranges (after): ".join(", ",@indentLineRange));

            # reset index so that loop starts again
            $index = 0;
        } elsif ( ($currentMin - 1) <= $previousMax and ( $currentMax <= $previousMax ) ){
            # overlapping line ranges, for example
            #
            #     --lines 3-7,4-6
            #
            # needs to be interpretted as 
            #
            #     --lines 3-7
            #
            $logger->info("overlapping line range found");
            $logger->info("line ranges (before): ".join(", ",@indentLineRange));
            splice(@indentLineRange,2*$index,2);
            $logger->info("line ranges (after): ".join(", ",@indentLineRange));

            # reset index so that loop starts again
            $index = 0;
        }
    }

    return @indentLineRange;
}

sub lines_verbatim_create_line_block{
    my $self = shift;
    my @lines = @{$_[0]};
    my $startLine = $_[1];
    my $finishLine = $_[2];

    my $verbBody = join("",@lines[$startLine..$finishLine]);
    $verbBody =~ s/\R?$//s;

    # create a new Verbatim object
    my $noIndentBlockObj = LatexIndent::Verbatim->new( begin=>q(),
                                          body=>$verbBody,
                                          end=>q(),
                                          name=>"line-switch-verbatim-protection",
                                          type=>"linesprotect", 
                                          modifyLineBreaksYamlName=>"lines-not-to-be-indented",
                                          );
    
    # give unique id
    $noIndentBlockObj->create_unique_id;

    # verbatim children go in special hash
    $verbatimStorage{${$noIndentBlockObj}{id}}=$noIndentBlockObj;

    # remove the environment block, and replace with unique ID
    ${$self}{body} .= ${$noIndentBlockObj}{id}."\n";

    return;
}

1;