diff --git a/changelog/fix_false_positive_style_redundant_string_escape.md b/changelog/fix_false_positive_style_redundant_string_escape.md new file mode 100644 index 00000000000..92232f93504 --- /dev/null +++ b/changelog/fix_false_positive_style_redundant_string_escape.md @@ -0,0 +1 @@ +* [#11346](https://github.com/rubocop/rubocop/issues/11346): Fix a false positive for `Style/RedundantStringEscape` when using escaped space in heredoc. ([@koic][]) diff --git a/lib/rubocop/cop/style/redundant_string_escape.rb b/lib/rubocop/cop/style/redundant_string_escape.rb index 4eedd1c815c..291c9cd14be 100644 --- a/lib/rubocop/cop/style/redundant_string_escape.rb +++ b/lib/rubocop/cop/style/redundant_string_escape.rb @@ -76,6 +76,7 @@ def begin_loc_present?(node) node.loc.to_hash.key?(:begin) && !node.loc.begin.nil? end + # rubocop:disable Metrics/CyclomaticComplexity def allowed_escape?(node, range) escaped = range.source[(1..-1)] @@ -88,13 +89,14 @@ def allowed_escape?(node, range) # with different versions of Ruby so that e.g. /\d/ != /d/ return true if /[\n\\[[:alnum:]]]/.match?(escaped[0]) - return true if escaped[0] == ' ' && percent_array_literal?(node) + return true if escaped[0] == ' ' && (percent_array_literal?(node) || node.heredoc?) return true if disabling_interpolation?(range) return true if delimiter?(node, escaped[0]) false end + # rubocop:enable Metrics/CyclomaticComplexity def interpolation_not_enabled?(node) single_quoted?(node) || diff --git a/spec/rubocop/cop/style/redundant_string_escape_spec.rb b/spec/rubocop/cop/style/redundant_string_escape_spec.rb index 0335b4d9cbf..a31fdce4f1f 100644 --- a/spec/rubocop/cop/style/redundant_string_escape_spec.rb +++ b/spec/rubocop/cop/style/redundant_string_escape_spec.rb @@ -417,6 +417,14 @@ def wrap(contents) MYHEREDOC RUBY end + + it 'does register an offense an escaped space' do + expect_no_offenses(<<~'RUBY') + <<~MYHEREDOC + \ text + MYHEREDOC + RUBY + end end context 'with an interpolation-disabled HEREDOC' do