]> git.donarmstrong.com Git - perltidy.git/commitdiff
improve indentation guess for file of only comments
authorSteve Hancock <perltidy@users.sourceforge.net>
Wed, 1 Jan 2025 16:40:20 +0000 (08:40 -0800)
committerSteve Hancock <perltidy@users.sourceforge.net>
Wed, 1 Jan 2025 16:40:20 +0000 (08:40 -0800)
CHANGES.md
lib/Perl/Tidy/Tokenizer.pm

index 88004a89aa7f330dd237f0f654e4ea6803bef1d3..f6945cbf9adbbddd9ac97502fb28213afb2209ca 100644 (file)
@@ -2,6 +2,12 @@
 
 ## 2024 09 03.09
 
+    - If a file consists only of comments, then the starting indentation will
+      be guessed from the indentation of the first comment. Previously it would
+      be guessed to be zero. Parameter --starting-indentation-level=n can be
+      used to specify an indentation and avoid a guess. This issue can
+      arise when formatting a block of comments from within an editor.
+
     - Added missing 'use File::Temp' for -html option. This was causing the
       message: "Undefined subroutine &File::Temp::tempfile called at ..."
       See git #176.
index 91410f13a94fa8e481dc17d53052c0850455419e..c245ab7c0f142395b185ee294e7c7ce0fda40911 100644 (file)
@@ -1755,6 +1755,7 @@ sub find_starting_indentation_level {
         # ( or, for now, an =pod line)
         my $msg = EMPTY_STRING;
         my $in_code_skipping;
+        my $line_for_guess;
         while ( defined( $line = $self->peek_ahead( $i++ ) ) ) {
 
             # if first line is #! then assume starting level is zero
@@ -1765,6 +1766,10 @@ sub find_starting_indentation_level {
 
             # ignore lines fenced off with code-skipping comments
             if ( $line =~ /^\s*#/ ) {
+
+                # use first comment for indentation guess in case of no code
+                if ( !defined($line_for_guess) ) { $line_for_guess = $line }
+
                 if ( !$in_code_skipping ) {
                     if (   $rOpts_code_skipping
                         && $line =~ /$code_skipping_pattern_begin/ )
@@ -1790,9 +1795,15 @@ sub find_starting_indentation_level {
 
             next if ( $line =~ /^\s*$/ );    # skip past blank lines
 
-            $starting_level = $self->guess_old_indentation_level($line);
+            # use first line of code for indentation guess
+            $line_for_guess = $line;
             last;
         } ## end while ( defined( $line = ...))
+
+        if ( defined($line_for_guess) ) {
+            $starting_level =
+              $self->guess_old_indentation_level($line_for_guess);
+        }
         $msg = "Line $i implies starting-indentation-level = $starting_level\n";
         $self->write_logfile_entry("$msg");
     }