From 82ff8ea45a9c8143c4f73268ae36eaaa9668c804 Mon Sep 17 00:00:00 2001 From: Steve Hancock Date: Wed, 1 Jan 2025 08:40:20 -0800 Subject: [PATCH] improve indentation guess for file of only comments --- CHANGES.md | 6 ++++++ lib/Perl/Tidy/Tokenizer.pm | 13 ++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 88004a89..f6945cbf 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -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. diff --git a/lib/Perl/Tidy/Tokenizer.pm b/lib/Perl/Tidy/Tokenizer.pm index 91410f13..c245ab7c 100644 --- a/lib/Perl/Tidy/Tokenizer.pm +++ b/lib/Perl/Tidy/Tokenizer.pm @@ -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"); } -- 2.39.5