summaryrefslogtreecommitdiff
path: root/support/latexindent/LatexIndent/Verbatim.pm
blob: 2d8fe0e2d8a66b8fe2302858117cdd14e47d24ee (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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package LatexIndent::Verbatim;
#	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 Data::Dumper;
use Exporter qw/import/;
use LatexIndent::Tokens qw/%tokens/;
use LatexIndent::GetYamlSettings qw/%masterSettings/;
use LatexIndent::Switches qw/$is_t_switch_active $is_tt_switch_active $is_m_switch_active/;
use LatexIndent::LogFile qw/$logger/;
our @EXPORT_OK = qw/put_verbatim_back_in find_verbatim_environments find_noindent_block find_verbatim_commands find_verbatim_special verbatim_common_tasks %verbatimStorage/;
our @ISA = "LatexIndent::Document"; # class inheritance, Programming Perl, pg 321
our $verbatimCounter;
our %verbatimStorage;

sub find_noindent_block{
    my $self = shift;

    # noindent block
    $logger->trace('*Searching for NOINDENTBLOCk (see noIndentBlock)') if $is_t_switch_active;
    $logger->trace(Dumper(\%{$masterSettings{noIndentBlock}})) if($is_tt_switch_active);
    while( my ($noIndentBlock,$yesno)= each %{$masterSettings{noIndentBlock}}){

        # integrity check on the field for noIndentBlock
        if ( ref($yesno) eq "HASH" ){
          if (not defined ${$yesno}{begin}){
            $logger->trace(" *not* looking for $noIndentBlock as $noIndentBlock:begin not specified") if $is_t_switch_active;
            next;
          } elsif (not defined ${$yesno}{end}) {
            $logger->trace(" *not* looking for $noIndentBlock as $noIndentBlock:end not specified") if $is_t_switch_active;
            next;
          } elsif (defined ${$yesno}{lookForThis} and !${$yesno}{lookForThis}){
            $logger->trace(" *not* looking for $noIndentBlock as lookForThis: 0") if $is_t_switch_active;
            next;
          }
        } elsif( ref($yesno) ne "HASH" and !$yesno ){
          $logger->trace(" *not* looking for $noIndentBlock as $noIndentBlock:$yesno") if $is_t_switch_active;
          next;
        }

        # if we've made it this far, then we're good to go
        my $noIndentRegExp;

        if (ref($yesno) eq "HASH"){
            # default value of body
            if (not defined ${$yesno}{body}){
                $logger->trace("looking for regex based $noIndentBlock, begin: ${$yesno}{begin}, end: ${$yesno}{end}") if $is_t_switch_active;
                $logger->trace("body not specified for $noIndentBlock, setting default .*?") if $is_t_switch_active;
                ${$yesno}{body} = qr/.*?/sx;
            } else {
                $logger->trace("looking for regex based $noIndentBlock") if $is_t_switch_active;
                $logger->trace("begin: ${$yesno}{begin}") if $is_t_switch_active;
                $logger->trace("body: ${$yesno}{body}") if $is_t_switch_active;
                $logger->trace("end: ${$yesno}{end}") if $is_t_switch_active;
            }

            $noIndentRegExp = qr/
                            (${$yesno}{begin})
                            (${$yesno}{body})                    
                            (${$yesno}{end})                    
                        /sx;
        } else {
            $logger->trace("looking for $noIndentBlock:$yesno noIndentBlock") if $is_t_switch_active;

            (my $noIndentBlockSpec = $noIndentBlock) =~ s/\*/\\*/sg;
            $noIndentRegExp = qr/
                            (
                                (?!<\\)
                                %
                                (?:\h|(?!<\\)%)*            # possible horizontal spaces
                                \\begin\{
                                        $noIndentBlockSpec  
                                       \}                   # % \begin{noindentblock} statement
                            )                               # begin captured into $1
                            (
                                .*?
                            )                               # non-greedy match (body) into $2
                            (
                                (?!<\\)
                                %                           # %
                                (?:\h|(?!<\\)%)*            # possible horizontal spaces
                                \\end\{$noIndentBlockSpec\} # \end{noindentblock}
                            )                               # % \end{<something>} statement into $3
                        /sx;
        } 
        while( ${$self}{body} =~ m/$noIndentRegExp/sx){

          # create a new Verbatim object
          my $noIndentBlockObj = LatexIndent::Verbatim->new( begin=>$1,
                                                body=>$2,
                                                end=>$3,
                                                name=>$noIndentBlock,
                                                type=>"noindentblock",
                                                modifyLineBreaksYamlName=>"verbatim",
                                                );
        
          # give unique id
          $noIndentBlockObj->create_unique_id;

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

          # log file output
          $logger->trace("NOINDENTBLOCK found: $noIndentBlock") if $is_t_switch_active;

          # remove the environment block, and replace with unique ID
          ${$self}{body} =~ s/$noIndentRegExp/${$noIndentBlockObj}{id}/sx;

          $logger->trace("replaced with ID: ${$noIndentBlockObj}{id}") if $is_t_switch_active;
          
          # possible decoration in log file 
          $logger->trace(${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace}) if ${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace};
        } 
    }
    return;
}

sub find_verbatim_environments{
    my $self = shift;

    # verbatim environments
    $logger->trace('*Searching for VERBATIM environments (see verbatimEnvironments)') if $is_t_switch_active;
    $logger->trace(Dumper(\%{$masterSettings{verbatimEnvironments}})) if($is_tt_switch_active);
    while( my ($verbEnv,$yesno)= each %{$masterSettings{verbatimEnvironments}}){
        if($yesno){
            $logger->trace("looking for $verbEnv:$yesno environments") if $is_t_switch_active;

            (my $verbEnvSpec = $verbEnv) =~ s/\*/\\*/sg;
            my $verbatimRegExp = qr/
                            (
                            \\begin\{
                                    $verbEnvSpec      # environment name captured into $1
                                   \}                 # \begin{<something>} statement
                            )
                            (
                                .*?
                            )                         # any character, but not \\begin
                            (
                                \\end\{$verbEnvSpec\} # \end{<something>} statement
                            )                    
                            (\h*)?                    # possibly followed by horizontal space
                            (\R)?                     # possibly followed by a line break 
                        /sx;

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

              # create a new Verbatim object
              my $verbatimBlock = LatexIndent::Verbatim->new( begin=>$1,
                                                    body=>$2,
                                                    end=>$3,
                                                    name=>$verbEnv,
                                                    type=>"environment",
                                                    modifyLineBreaksYamlName=>"verbatim",
                                                    linebreaksAtEnd=>{
                                                      end=>$5?1:0,
                                                    },
                                                    horizontalTrailingSpace=>$4?$4:q(),
                                                    aliases=>{
                                                      # begin statements
                                                      BeginStartsOnOwnLine=>"VerbatimBeginStartsOnOwnLine",
                                                      # after end statements
                                                      EndFinishesWithLineBreak=>"VerbatimEndFinishesWithLineBreak",
                                                    },
                                                    );

              # there are common tasks for each of the verbatim objects
              $verbatimBlock->verbatim_common_tasks;
              
              # verbatim children go in special hash
              $verbatimStorage{${$verbatimBlock}{id}}=$verbatimBlock;

              # log file output
              $logger->trace("*VERBATIM environment found: $verbEnv") if $is_t_switch_active;

              # remove the environment block, and replace with unique ID
              ${$self}{body} =~ s/$verbatimRegExp/${$verbatimBlock}{replacementText}/sx;

              $logger->trace("replaced with ID: ${$verbatimBlock}{id}") if $is_t_switch_active;
              
              # possible decoration in log file 
              $logger->trace(${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace}) if ${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace};
            } 
      } else {
            $logger->trace("*not* looking for $verbEnv as $verbEnv:$yesno") if $is_t_switch_active;
      }
    }
    return;
}

sub find_verbatim_commands{
    my $self = shift;

    # verbatim commands need to be treated separately to verbatim environments;
    # note that, for example, we could quite reasonably have \lstinline!%!, which 
    # would need to be found *before* trailing comments have been removed. Similarly, 
    # verbatim commands need to be put back in *after* trailing comments have been put 
    # back in
    $logger->trace('*Searching for VERBATIM commands (see verbatimCommands)') if $is_t_switch_active;
    $logger->trace(Dumper(\%{$masterSettings{verbatimCommands}})) if($is_tt_switch_active);
    while( my ($verbCommand,$yesno)= each %{$masterSettings{verbatimCommands}}){
        if($yesno){
            $logger->trace("looking for $verbCommand:$yesno Commands") if $is_t_switch_active;

            my $verbatimRegExp = qr/
                            (
                                \\$verbCommand     
                                \h*                                             
                            )                                                   # name of command into $1
                            (
                                \[
                                    (?:
                                        (?!
                                            (?:(?<!\\)\[) 
                                        ).
                                    )*?     # not including [, but \[ ok
                                (?<!\\)     # not immediately pre-ceeded by \
                                \]          # [optional arguments]
                                \h*
                            )?              # opt arg into $2
                            (
                              .
                            )               # delimiter into $3
                            (
                              .*?
                            )               # body into $4
                            \3
                            (\h*)?          # possibly followed by horizontal space
                            (\R)?           # possibly followed by a line break 
                        /mx;

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

              # create a new Verbatim object
              my $verbatimCommand = LatexIndent::Verbatim->new( begin=>$1.($2?$2:q()).$3,
                                                    body=>$4,
                                                    end=>$3,
                                                    name=>$verbCommand,
                                                    type=>"command",
                                                    modifyLineBreaksYamlName=>"verbatim",
                                                    linebreaksAtEnd=>{
                                                      end=>$6?1:0,
                                                    },
                                                    horizontalTrailingSpace=>$5?$5:q(),
                                                    aliases=>{
                                                      # begin statements
                                                      BeginStartsOnOwnLine=>"VerbatimBeginStartsOnOwnLine",
                                                      # after end statements
                                                      EndFinishesWithLineBreak=>"VerbatimEndFinishesWithLineBreak",
                                                    },
                                                    optArg=>$2?$2:q(),
                                                    );
              # there are common tasks for each of the verbatim objects
              $verbatimCommand->verbatim_common_tasks;

              # output, if desired
              $logger->trace(Dumper($verbatimCommand),'ttrace') if($is_tt_switch_active);

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

              # log file output
              $logger->trace("*VERBATIM command found: $verbCommand") if $is_t_switch_active;

              # remove the environment block, and replace with unique ID
              ${$self}{body} =~ s/$verbatimRegExp/${$verbatimCommand}{replacementText}/sx;

              $logger->trace("replaced with ID: ${$verbatimCommand}{id}") if $is_t_switch_active;
              
              # possible decoration in log file 
              $logger->trace(${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace}) if ${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace};
            } 
      } else {
            $logger->trace("*not* looking for $verbCommand as $verbCommand:$yesno") if $is_t_switch_active;
      }
    }
    return;

}

sub find_verbatim_special{
    my $self = shift;

    # loop through specialBeginEnd
    while( my ($specialName,$BeginEnd)= each %{$masterSettings{specialBeginEnd}}){

      # only classify special Verbatim if lookForThis is 'verbatim'
      if( (ref($BeginEnd) eq "HASH") and ${$BeginEnd}{lookForThis}=~m/v/s and ${$BeginEnd}{lookForThis} eq 'verbatim'){
            $logger->trace('*Searching for VERBATIM special (see specialBeginEnd)') if $is_t_switch_active;

            my $verbatimRegExp = qr/
                            (
                                ${$BeginEnd}{begin}
                            )
                            (
                                .*?
                            )                    
                            (
                                ${$BeginEnd}{end}
                            )                    
                            (\h*)?                    # possibly followed by horizontal space
                            (\R)?                     # possibly followed by a line break 
                        /sx;

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

              # create a new Verbatim object
              my $verbatimBlock = LatexIndent::Verbatim->new( begin=>$1,
                                                    body=>$2,
                                                    end=>$3,
                                                    name=>$specialName,
                                                    modifyLineBreaksYamlName=>"specialBeginEnd",
                                                    linebreaksAtEnd=>{
                                                      end=>$5?1:0,
                                                    },
                                                    horizontalTrailingSpace=>$4?$4:q(),
                                                    type=>"special",
                                                    aliases=>{
                                                      # begin statements
                                                      BeginStartsOnOwnLine=>"SpecialBeginStartsOnOwnLine",
                                                      # after end statements
                                                      EndFinishesWithLineBreak=>"SpecialEndFinishesWithLineBreak",
                                                    },
                                                    );
              # there are common tasks for each of the verbatim objects
              $verbatimBlock->verbatim_common_tasks;

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

              # log file output
              $logger->trace("*VERBATIM special found: $specialName") if $is_t_switch_active;

              # remove the special block, and replace with unique ID
              ${$self}{body} =~ s/$verbatimRegExp/${$verbatimBlock}{replacementText}/sx;

              $logger->trace("replaced with ID: ${$verbatimBlock}{id}") if $is_t_switch_active;
              
              # possible decoration in log file 
              $logger->trace(${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace}) if ${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace};
            } 
    }
  }
}

sub  put_verbatim_back_in {
    my $self = shift;
    my %input = @_;

    my $verbatimCount=0;
    my $toMatch = q();
    if($input{match} eq "everything-except-commands"){
        $toMatch = "noindentblockenvironmentspecial";
    } else {
        $toMatch = "command";
    }

    # count the number of non-command verbatim objects
    while( my ($key,$child)= each %verbatimStorage){
        ${$child}{type} = "environment" if !(defined ${$child}{type});
        $verbatimCount++ if($toMatch =~ m/${$child}{type}/);
    }

    return unless($verbatimCount>0);
    
    # search for environments/commands
    $logger->trace('*Putting verbatim back in') if $is_t_switch_active;
    $logger->trace('pre-processed body:') if $is_tt_switch_active;
    $logger->trace(${$self}{body}) if($is_tt_switch_active);

    # loop through document children hash
    my $verbatimFound=0;
    while($verbatimFound < $verbatimCount){
        while( my ($verbatimID,$child)= each %verbatimStorage){
          if($toMatch =~ m/${$child}{type}/){
            if(${$self}{body} =~ m/$verbatimID/mx){
                # possibly remove trailing line break
                if(defined ${$child}{EndFinishesWithLineBreak} 
                    and ${$child}{EndFinishesWithLineBreak}==-1
                    and ${$self}{body} =~ m/$verbatimID\h*\R/s){
                    $logger->trace("m-switch active, removing trailing line breaks from ${$child}{name}") if $is_t_switch_active;
                    ${$self}{body} =~ s/$verbatimID(\h*)?(\R|\h)*/$verbatimID /s;
                }
                # replace ids with body
                ${$self}{body} =~ s/$verbatimID/${$child}{begin}${$child}{body}${$child}{end}/s;

                # log file info
                $logger->trace('Body now looks like:') if $is_tt_switch_active;
                $logger->trace(${$self}{body},'ttrace') if($is_tt_switch_active);

                # delete the child so it won't be operated upon again
                delete $verbatimStorage{$verbatimID};
                $verbatimFound++;
              } elsif ($is_m_switch_active 
                  and ${$masterSettings{modifyLineBreaks}{textWrapOptions}}{columns}>1 
                  and ${$masterSettings{modifyLineBreaks}{textWrapOptions}}{huge} ne "overflow" 
                  and ${$self}{body} !~ m/${$child}{id}/){
                $logger->trace("$verbatimID not found in body using /m matching, it may have been split across line (see modifyLineBreaks: textWrapOptions)") if($is_t_switch_active);

                # search for a version of the verbatim ID that may have line breaks 
                my $verbatimIDwithLineBreaks = join("\\R?",split(//,$verbatimID));
                my $verbatimIDwithLineBreaksRegExp = qr/$verbatimIDwithLineBreaks/s;  

                # replace the line-broken verbatim ID with a non-broken verbatim ID
                ${$self}{body} =~ s/$verbatimIDwithLineBreaksRegExp/${$child}{id}/s;

                # note: we do *not* label this as found, as we need to go back through
                #       and search for the newly modified ID
              }
            }

            # logfile info
            $logger->trace('*Post-processed body:') if $is_tt_switch_active;
            $logger->trace(${$self}{body}) if($is_tt_switch_active);
          }
    }
    return;
}

sub verbatim_common_tasks{

    my $self = shift;

    # get yaml settings
    $self->yaml_modify_line_breaks_settings if $is_m_switch_active;

    # give unique id
    $self->create_unique_id;

    # the replacement text can be just the ID, but the ID might have a line break at the end of it
    $self->get_replacement_text;

    # the above regexp, when used below, will remove the trailing linebreak in ${$self}{linebreaksAtEnd}{end}
    # so we compensate for it here
    $self->adjust_replacement_text_line_breaks_at_end;
    
    # modify line breaks end statements
    $self->modify_line_breaks_end if ($is_m_switch_active and defined ${$self}{EndStartsOnOwnLine} and ${$self}{EndStartsOnOwnLine}!=0);
    $self->modify_line_breaks_end_after if ($is_m_switch_active and defined ${$self}{EndFinishesWithLineBreak} and ${$self}{EndFinishesWithLineBreak}!=0);
}

sub create_unique_id{
    my $self = shift;

    $verbatimCounter++;
    ${$self}{id} = "$tokens{verbatim}$verbatimCounter$tokens{endOfToken}";
    return;
}

sub yaml_get_textwrap_removeparagraphline_breaks{
    my $self = shift;
    $logger->trace("No text wrap or remove paragraph line breaks for verbatim code blocks, ${$self}{name}") if ${$masterSettings{logFilePreferences}}{showDecorationFinishCodeBlockTrace};
}

1;