Class: RuboCop::Cop::Layout::LineLength
| Relationships & Source Files | |
| Super Chains via Extension / Inclusion / Inheritance | |
|
Class Chain:
self,
::RuboCop::Cop::AutoCorrector,
::RuboCop::Cop::Base,
::RuboCop::ExcludeLimit,
NodePattern::Macros,
RuboCop::AST::Sexp
|
|
|
Instance Chain:
self,
::RuboCop::Cop::EndlessMethodRewriter,
::RuboCop::Cop::LineLengthHelp,
::RuboCop::Cop::Alignment,
::RuboCop::Cop::RangeHelp,
::RuboCop::Cop::AllowedPattern,
::RuboCop::Cop::CheckLineBreakable,
::RuboCop::Cop::Base,
::RuboCop::Cop::AutocorrectLogic,
::RuboCop::Cop::IgnoredNode,
::RuboCop::Util,
RuboCop::AST::Sexp
|
|
| Inherits: |
RuboCop::Cop::Base
|
| Defined in: | lib/rubocop/cop/layout/line_length.rb |
Overview
Checks the length of lines in the source code.
The maximum length is configurable.
The tab size is configured in the IndentationWidth
of the Layout/IndentationStyle cop.
It also ignores a shebang line by default.
This cop has some autocorrection capabilities. It can programmatically shorten certain long lines by inserting line breaks into expressions that can be safely split across lines. These include arrays, hashes, and method calls with argument lists.
If autocorrection is enabled, the following cops are recommended to further format the broken lines. (Many of these are enabled by default.)
-
Layout/ArgumentAlignment -
Layout/ArrayAlignment -
Layout/BlockAlignment -
Layout/BlockEndNewline -
Layout/ClosingParenthesisIndentation -
Layout/FirstArgumentIndentation -
Layout/FirstArrayElementIndentation -
Layout/FirstHashElementIndentation -
Layout/FirstParameterIndentation -
Layout/HashAlignment -
Layout/IndentationWidth -
Layout/MultilineArrayLineBreaks -
Layout/MultilineBlockLayout -
Layout/MultilineHashBraceLayout -
Layout/MultilineHashKeyLineBreaks -
Layout/MultilineMethodArgumentLineBreaks -
Layout/MultilineMethodParameterLineBreaks -
Layout/ParameterAlignment -
Style/BlockDelimiters
Together, these cops will pretty print hashes, arrays, method calls, etc. For example, let’s say the max columns is 25:
Constant Summary
-
ESCAPE_SEQUENCE_TAIL =
# File 'lib/rubocop/cop/layout/line_length.rb', line 79
A trailing backslash, or a trailing unicode, hex, octal, meta or control escape whose payload may be incomplete. An even run of backslashes is complete on its own. Meta and control prefixes chain (
\M-\C-x,\c\M-x), so a whole chain is one escape, and a braced unicode escape may hold several space-separated codepoints./ (?<!\\)(?:\\\\)* ( \\(?:(?:[MC]-|c)\\)* (?:u\{[\da-f\x20]*|u[\da-f]{0,4}|x[\da-f]{0,2}|[0-7]{0,3}|[MC]-?|c)? )\z /xi.freeze
-
MSG =
# File 'lib/rubocop/cop/layout/line_length.rb', line 73'Line is too long. [%<length>d/%<max>d]'
::RuboCop::Cop::Base - Inherited
DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND
::RuboCop::Cop::RangeHelp - Included
::RuboCop::Cop::Alignment - Included
Class Attribute Summary
::RuboCop::Cop::AutoCorrector - Extended
::RuboCop::Cop::Base - Inherited
| .gem_requirements, .lint?, | |
| .support_autocorrect? | Returns if class supports autocorrect. |
| .support_multiple_source? | Override if your cop should be called repeatedly for multiple investigations Between calls to #on_new_investigation and #on_investigation_end, the result of |
Class Method Summary
::RuboCop::Cop::Base - Inherited
| .autocorrect_incompatible_with | List of cops that should not try to autocorrect at the same time as this cop. |
| .badge | Naming. |
| .callbacks_needed, .cop_name, .department, | |
| .documentation_url | Returns a url to view this cops documentation online. |
| .exclude_from_registry | Call for abstract Cop classes. |
| .inherited, | |
| .joining_forces | Override and return the Force class(es) you need to join. |
| .match? | Returns true if the cop name or the cop namespace matches any of the given names. |
| .new, | |
| .requires_gem | Register a version requirement for the given gem name. |
| .restrict_on_send | Reserved for Commissioner. |
::RuboCop::ExcludeLimit - Extended
| exclude_limit | Sets up a configuration option to have an exclude limit tracked. |
| transform | |
Instance Attribute Summary
- #allow_string_split? ⇒ Boolean readonly private
- #breakable_range rw private
- #compact_array_brackets_enforced? ⇒ Boolean readonly private
- #require_endless_methods? ⇒ Boolean readonly private
::RuboCop::Cop::LineLengthHelp - Included
::RuboCop::Cop::Alignment - Included
::RuboCop::Cop::Base - Inherited
| #active_support_extensions_enabled?, #always_autocorrect?, #config, #config_to_allow_offenses, #config_to_allow_offenses=, #contextual_autocorrect?, #disabled_autocorrect?, | |
| #preview? | Whether the user opted in to unstable behavior, with |
| #processed_source, #project_index, #string_literals_frozen_by_default?, #target_satisfies_all_gem_version_requirements? | |
::RuboCop::Cop::AutocorrectLogic - Included
| #autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?, | |
| #skipped_unsafe_correction_with_disable_uncorrectable? | Whether a correction exists but is skipped because it is unsafe in a safe autocorrect run, while |
| #contextual_autocorrect_held_back? | When LSP is enabled or the |
Instance Method Summary
-
#on_array(node)
Alias for #on_potential_breakable_node.
- #on_block(node) (also: #on_numblock, #on_itblock)
-
#on_csend(node)
Alias for #on_potential_breakable_node.
- #on_def(node) (also: #on_defs)
-
#on_defs(node)
Alias for #on_def.
- #on_dstr(node)
-
#on_hash(node)
Alias for #on_potential_breakable_node.
- #on_investigation_end
-
#on_itblock(node)
Alias for #on_block.
- #on_new_investigation
-
#on_numblock(node)
Alias for #on_block.
- #on_potential_breakable_node(node) (also: #on_array, #on_hash, #on_send, #on_csend)
-
#on_send(node)
Alias for #on_potential_breakable_node.
- #on_str(node)
- #after_heredoc_opener?(range) ⇒ Boolean private
- #allowed_combination?(line, uri_range, qualified_name_range) ⇒ Boolean private
- #allowed_heredoc private
- #allowed_line?(line, line_index) ⇒ Boolean private
- #blank_between?(begin_pos, end_pos) ⇒ Boolean private
- #blank_left_part?(node, content_begin_pos, pos) ⇒ Boolean private
- #blank_rest?(node, break_pos) ⇒ Boolean private
- #block_opening_with_do(block_node) private
- #break_ranges(line_index) private
- #breakable_block_range(block_node) private
- #breakable_dstr?(node) ⇒ Boolean private
- #breakable_dstr_begin_position(node) private
- #breakable_range_after_semicolon(semicolon_token) private
- #breakable_range_by_line_index private
- #breakable_space_position(node, substr) private
- #breakable_string?(node) ⇒ Boolean private
- #breakable_string_delimiters private
- #breakable_string_position(node) private
-
#breakable_string_range(node)
private
Locate where to break a string that is too long, ensuring that escape characters are not bisected.
- #breakable_string_range_at_limit(source_range) private
- #breakable_strings private
- #check_directive_line(line, line_index) private
- #check_for_breakable_block(block_node) private
- #check_for_breakable_dstr(node) private
- #check_for_breakable_node(node) private
- #check_for_breakable_semicolons(processed_source) private
-
#check_for_breakable_str(node)
private
rubocop:disable-next Metrics/AbcSize.
-
#check_line(line, line_index)
private
rubocop:disable-next Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity.
- #check_line_for_exemptions(line, line_index) private
- #compact_nested_array_break?(node, breakable_node) ⇒ Boolean private
- #correct_endless_method_block_to_multiline(corrector, node) private
- #correctable_endless_method_block?(node) ⇒ Boolean private
- #endless_methods_by_line private
- #escape_sequence_start(text) private
- #excess_range(uri_range, line, line_index) private
- #extract_heredocs(ast) private
- #handle_endless_method_line(line, line_index) private
-
#heredoc_body_after_method?(node) ⇒ Boolean
private
The correction puts the body and
endon lines of their own, which separates an opener before the body, or on the last line, from its heredoc body. - #heredoc_openers private
- #heredocs private
- #highlight_start(line) private
-
#largest_possible_string(node)
private
Find the largest possible substring of a string node to retain before a break.
- #leaves_two_parts?(node, content_begin_pos, pos) ⇒ Boolean private
- #line_in_permitted_heredoc?(line_number) ⇒ Boolean private
- #max (also: #max_line_length) private
-
#max_line_length
private
Alias for #max.
- #next_string_break_position(node, pos, delimiter) private
- #opens_string?(begin_node) ⇒ Boolean private
- #range_if_applicable(line, type) private
- #receiver_contains_heredoc?(node) ⇒ Boolean private
- #register_endless_method_offense(line, line_index) private
- #register_offense(loc, line, line_index, length: line_length(line)) private
- #register_required_endless_method_offense(line, line_index) private
- #shebang?(line, line_index) ⇒ Boolean private
- #size_before_whitespace_run(text, size) private
- #space_before_word(node, max_pos) private
- #starts_after_quote?(node) ⇒ Boolean private
- #string_break_ranges(node, delimiter) private
- #string_content_length(node) private
- #string_delimiter(node) private
- #track_endless_method(node) private
::RuboCop::Cop::EndlessMethodRewriter - Included
::RuboCop::Cop::LineLengthHelp - Included
::RuboCop::Cop::Alignment - Included
| #check_alignment, #configured_indentation_width, #display_column, #each_bad_alignment, #end_of_line_comment, #indentation, #offset, #register_offense, #within? |
::RuboCop::Cop::RangeHelp - Included
| #add_range, | |
| #arguments_range | A range containing the first to the last argument of a method call or method definition. |
| #column_offset_between, | |
| #contents_range | A range containing only the contents of a literal with delimiters (e.g. |
| #directions, | |
| #effective_column | Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value. |
| #final_pos | rubocop:disable-next Metrics/ParameterLists. |
| #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, | |
| #range_for_statement_removal | Returns the range to remove a statement: its whole lines, including a trailing comment and the final newline, when no other code shares them, and otherwise the range itself with the spaces after it. |
| #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range | |
::RuboCop::Cop::AllowedPattern - Included
| #allowed_line?, #allowed_pattern_regexps, #allowed_patterns, #cop_config_deprecated_methods_values, #cop_config_patterns_values, #ignored_line?, #matches_allowed_pattern?, #matches_ignored_pattern? |
::RuboCop::Cop::CheckLineBreakable - Included
| #extract_breakable_node, #all_on_same_line?, #already_on_multiple_lines?, #breakable_collection?, #chained_to_heredoc?, | |
| #children_could_be_broken_up? | The result depends only on the given node, but the check may traverse all children of a large collection and is repeated for each contained element, so memoize it per node. |
| #compute_children_could_be_broken_up?, #contained_by_breakable_collection_on_same_line?, #contained_by_multiline_collection_that_could_be_broken_up?, #extract_breakable_node_from_elements, #extract_first_element_over_column_limit, | |
| #first_element_movable? | If a method call or definition is not parenthesized, the first element cannot be moved, because it can result in changed behavior or a syntax error. |
| #heredoc_begin_position, #process_args, #safe_to_ignore?, | |
| #shift_elements_for_heredoc_arg | If a |
| #within_column_limit? | |
::RuboCop::Cop::Base - Inherited
| #add_global_offense | Adds an offense that has no particular location. |
| #add_offense | Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense. |
| #begin_investigation | Called before any investigation. |
| #callbacks_needed | — grouped under the Commissioner heading above. |
| #cop_config | Configuration Helpers. |
| #cop_name, #excluded_file?, | |
| #external_dependency_checksum | This method should be overridden when a cop’s behavior depends on state that lives outside of these locations: |
| #file_independent_relevance | Whether |
| #inspect, | |
| #message | Gets called if no message is specified when calling |
| #name | Alias for Base#cop_name. |
| #offenses, | |
| #on_investigation_end | Called after all on_… |
| #on_new_investigation | Called before all on_… |
| #on_other_file | Called instead of all on_… |
| #parse | There should be very limited reasons for a Cop to do it’s own parsing The source is parsed the way the file under investigation was. |
| #parser_engine, | |
| #ready | Called between investigations. |
| #relevant_file?, | |
| #target_gem_version | Returns the version of a gem in the target, by default its locked version (i.e. from Gemfile.lock or gems.locked). |
| #target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction, | |
| #callback_argument | Reserved for Cop::Cop. |
| #complete_investigation | Called to complete an investigation. |
| #correct, #covering_disabled_range, #current_corrector, | |
| #current_offense_locations | Reserved for Commissioner: |
| #current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, | |
| #enabled_lines? | A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code. |
| #file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #new_offense, #range_for_original, #range_from_node_or_range, | |
| #reset_investigation | Actually private methods. |
| #suppression_reason | The |
| #use_corrector | |
::RuboCop::Cop::AutocorrectLogic - Included
::RuboCop::Cop::IgnoredNode - Included
Constructor Details
This class inherits a constructor from RuboCop::Cop::Base
Class Method Details
.autocorrect_incompatible_with
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 87
def self.autocorrect_incompatible_with [Style::MethodCallWithArgsParentheses, Style::MethodDefParentheses] end
Instance Attribute Details
#allow_string_split? ⇒ Boolean (readonly, private)
[ GitHub ]
# File 'lib/rubocop/cop/layout/line_length.rb', line 597
def allow_string_split? cop_config['SplitStrings'] end
#breakable_range (rw, private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 143
attr_accessor :breakable_range
#compact_array_brackets_enforced? ⇒ Boolean (readonly, private)
[ GitHub ]
#require_endless_methods? ⇒ Boolean (readonly, private)
[ GitHub ]
Instance Method Details
#after_heredoc_opener?(range) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 246
def after_heredoc_opener?(range) heredoc_openers.any? do |opener| opener.line == range.line && opener.begin_pos < range.begin_pos end end
#allowed_combination?(line, uri_range, qualified_name_range) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 660
def allowed_combination?(line, uri_range, qualified_name_range) if uri_range && qualified_name_range allowed_position?(line, uri_range) && allowed_position?(line, qualified_name_range) elsif uri_range allowed_position?(line, uri_range) elsif qualified_name_range allowed_position?(line, qualified_name_range) else false end end
#allowed_heredoc (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 593
def allowed_heredoc cop_config['AllowHeredoc'] end
#allowed_line?(line, line_index) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 521
def allowed_line?(line, line_index) matches_allowed_pattern?(line) || shebang?(line, line_index) || (heredocs && line_in_permitted_heredoc?(line_index.succ)) end
#blank_between?(begin_pos, end_pos) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 387
def blank_between?(begin_pos, end_pos) range_between(begin_pos, end_pos).source.strip.empty? end
#blank_left_part?(node, content_begin_pos, pos) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 373
def blank_left_part?(node, content_begin_pos, pos) return false unless pos.end_pos > content_begin_pos return false unless starts_after_quote?(node) blank_between?(content_begin_pos, pos.end_pos) end
#blank_rest?(node, break_pos) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 445
def blank_rest?(node, break_pos) offset = break_pos - node.source_range.begin_pos node.source[offset...string_content_length(node)].strip.empty? end
#block_opening_with_do(block_node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 221
def block_opening_with_do(block_node) if block_node.send_node.lambda_literal? opening = block_node.source_range.with(end_pos: block_node.loc.begin.begin_pos) return "#{opening.source.rstrip} do" end block_arguments = block_node.arguments? ? " #{block_node.arguments.source}" : '' "#{block_node.send_node.source} do#{block_arguments}" end
#break_ranges(line_index) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 551
def break_ranges(line_index) return [] if breakable_range.nil? return [breakable_range] unless (node = breakable_strings[line_index])&.loc?(:end) string_break_ranges(node, breakable_string_delimiters[line_index]) end
#breakable_block_range(block_node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 336
def breakable_block_range(block_node) if block_node.arguments? && !block_node.lambda? block_node.arguments.loc.end else block_node.braces? ? block_node.loc.begin : block_node.loc.begin.adjust(begin_pos: 1) end end
#breakable_dstr?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 672
def breakable_dstr?(node) # If the `dstr` only contains one child, it cannot be broken breakable_string?(node) && !node.child_nodes.one? end
#breakable_dstr_begin_position(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 457
def breakable_dstr_begin_position(node) source_range = node.source_range return unless source_range.column < max && source_range.last_column >= max return if opens_string?(node) source_range.begin_pos end
#breakable_range_after_semicolon(semicolon_token) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 344
def breakable_range_after_semicolon(semicolon_token) range = semicolon_token.pos end_pos = range.end_pos next_range = range_between(end_pos, end_pos + 1) return nil unless same_line?(next_range, range) next_char = next_range.source return nil if /[\r\n]/.match?(next_char) return nil if next_char == ';' next_range end
#breakable_range_by_line_index (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 473
def breakable_range_by_line_index @breakable_range_by_line_index ||= {} end
#breakable_space_position(node, substr) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 410
def breakable_space_position(node, substr) limit = string_content_length(node) - 1 space_pos = space_before_word(node, substr.length - 1) space_pos = space_before_word(node, limit - 1) if space_pos && space_pos + 1 > limit space_pos end
#breakable_string?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 326
def breakable_string?(node) allow_string_split? && node.single_line? && !node.heredoc? && # TODO: strings inside hashes, kwargs and arrays are currently ignored, # but could be considered in the future !node.parent&.type?(:pair, :kwoptarg, :array) && !after_heredoc_opener?(node.source_range) end
#breakable_string_delimiters (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 481
def breakable_string_delimiters @breakable_string_delimiters ||= {} end
#breakable_string_position(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 357
def breakable_string_position(node) source_range = node.source_range return if source_range.last_column < max return unless (pos = breakable_string_range(node)) content_begin_pos = node.loc?(:begin) ? node.loc.begin.end_pos : source_range.begin_pos if blank_left_part?(node, content_begin_pos, pos) pos = breakable_string_range_at_limit(source_range) end pos.end_pos if pos && leaves_two_parts?(node, content_begin_pos, pos) end
#breakable_string_range(node) (private)
Locate where to break a string that is too long, ensuring that escape characters are not bisected. If the string contains spaces, use them to determine a place for a clean break; otherwise, the string will be broken at the line length limit.
# File 'lib/rubocop/cop/layout/line_length.rb', line 395
def breakable_string_range(node) source_range = node.source_range relevant_substr = largest_possible_string(node) if (space_pos = breakable_space_position(node, relevant_substr)) # A space can separate codepoints inside a braced unicode escape. escape_pos = escape_sequence_start(relevant_substr[0..space_pos]) source_range.resize(escape_pos || (space_pos + 1)) elsif (escape_pos = escape_sequence_start(relevant_substr)) source_range.resize(escape_pos) else breakable_string_range_at_limit(source_range) end end
#breakable_string_range_at_limit(source_range) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 427
def breakable_string_range_at_limit(source_range) adjustment = max - source_range.last_column - 3 return if adjustment.abs > source_range.size cut = source_range.adjust(end_pos: adjustment) cut = cut.resize(size_before_whitespace_run(source_range.source, cut.size)) escape_pos = escape_sequence_start(cut.source) escape_pos ? source_range.resize(escape_pos) : cut end
#breakable_strings (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 485
def breakable_strings @breakable_strings ||= {} end
#check_directive_line(line, line_index) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 627
def check_directive_line(line, line_index) length_without_directive = line_length_without_directive(line) return if length_without_directive <= max range = max..(length_without_directive - 1) register_offense( source_range( processed_source.buffer, line_index + 1, range ), line, line_index, length: length_without_directive ) end
#check_for_breakable_block(block_node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 283
def check_for_breakable_block(block_node) return unless block_node.single_line? line_index = block_node.loc.line - 1 return if breakable_string_delimiters[line_index] range = breakable_block_range(block_node) pos = range.begin_pos + 1 range = range_between(pos, pos + 1) return if after_heredoc_opener?(range) breakable_range_by_line_index[line_index] = range end
#check_for_breakable_dstr(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 311
def check_for_breakable_dstr(node) # rubocop:disable Metrics/AbcSize line_index = node.loc.line - 1 return if breakable_range_by_line_index[line_index] return unless breakable_dstr?(node) return unless (delimiter = string_delimiter(node)) node.each_child_node(:begin).detect do |begin_node| next unless (pos = breakable_dstr_begin_position(begin_node)) breakable_range_by_line_index[line_index] = range_between(pos, pos + 1) breakable_string_delimiters[line_index] = delimiter end end
#check_for_breakable_node(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 232
def check_for_breakable_node(node) breakable_node = extract_breakable_node(node, max) return if breakable_node.nil? return if compact_nested_array_break?(node, breakable_node) line_index = breakable_node.first_line - 1 range = breakable_node.source_range existing = breakable_range_by_line_index[line_index] return if existing || after_heredoc_opener?(range) breakable_range_by_line_index[line_index] = range end
#check_for_breakable_semicolons(processed_source) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 273
def check_for_breakable_semicolons(processed_source) tokens = processed_source.tokens.select { |t| t.type == :tSEMI } tokens.reverse_each do |token| range = breakable_range_after_semicolon(token) next if range.nil? || after_heredoc_opener?(range) breakable_range_by_line_index[range.line - 1] = range end end
#check_for_breakable_str(node) (private)
rubocop:disable-next Metrics/AbcSize
# File 'lib/rubocop/cop/layout/line_length.rb', line 298
def check_for_breakable_str(node) line_index = node.loc.line - 1 return if breakable_range_by_line_index[line_index] return unless breakable_string?(node) return unless (delimiter = string_delimiter(node)) return unless (pos = breakable_string_position(node)) breakable_range_by_line_index[line_index] = range_between(pos, pos + 1) breakable_string_delimiters[line_index] = delimiter breakable_strings[line_index] = node end
#check_line(line, line_index) (private)
rubocop:disable-next Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# File 'lib/rubocop/cop/layout/line_length.rb', line 501
def check_line(line, line_index) return if line_length(line) <= max return if allowed_line?(line, line_index) if endless_methods_by_line.key?(line_index) return handle_endless_method_line(line, line_index) end if allow_rbs_inline_annotation? && rbs_inline_annotation_on_source_line?(line_index) return end if allow_cop_directives? && directive_on_source_line?(line_index) return check_directive_line(line, line_index) end return check_line_for_exemptions(line, line_index) if allow_uri? || allow_qualified_name? register_offense(excess_range(nil, line, line_index), line, line_index) end
#check_line_for_exemptions(line, line_index) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 644
def check_line_for_exemptions(line, line_index) uri_range = range_if_applicable(line, :uri) qualified_name_range = range_if_applicable(line, :qualified_name) return if allowed_combination?(line, uri_range, qualified_name_range) range = uri_range || qualified_name_range register_offense(excess_range(range, line, line_index), line, line_index) end
#compact_nested_array_break?(node, breakable_node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 259
def compact_nested_array_break?(node, breakable_node) return false if !node.array_type? || !node.square_brackets? return false unless breakable_node.equal?(node.children.first) return false unless breakable_node.source.start_with?('[') compact_array_brackets_enforced? end
#correct_endless_method_block_to_multiline(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 210
def correct_endless_method_block_to_multiline(corrector, node) block_node = node.body replacement = [ block_opening_with_do(block_node), "#{indent(node, offset: 2)}#{block_node.body.source}", "#{indent(node)}end" ].join("\n") corrector.replace(block_node, replacement) end
#correctable_endless_method_block?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 200
def correctable_endless_method_block?(node) block_node = node.body block_node&.type?(:any_block) && block_node.braces? && block_node.single_line? && block_node.body && !receiver_contains_heredoc?(block_node) end
#endless_methods_by_line (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 477
def endless_methods_by_line @endless_methods_by_line ||= {} end
#escape_sequence_start(text) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 423
def escape_sequence_start(text) text.match(ESCAPE_SEQUENCE_TAIL)&.begin(1) end
#excess_range(uri_range, line, line_index) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 577
def excess_range(uri_range, line, line_index) excessive_position = if uri_range && uri_range.begin < max uri_range.end else highlight_start(line) end source_range(processed_source.buffer, line_index + 1, excessive_position...(line_length(line))) end
#extract_heredocs(ast) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 601
def extract_heredocs(ast) return [] unless ast ast.each_node(:any_str).select(&:heredoc?).map do |node| body = node.location.heredoc_body delimiter = node.location.heredoc_end.source.strip [body.first_line...body.last_line, delimiter] end end
#handle_endless_method_line(line, line_index) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 150
def handle_endless_method_line(line, line_index) if require_endless_methods? return register_required_endless_method_offense(line, line_index) end register_endless_method_offense(line, line_index) end
#heredoc_body_after_method?(node) ⇒ Boolean (private)
The correction puts the body and end on lines of their own, which
separates an opener before the body, or on the last line, from its
heredoc body.
# File 'lib/rubocop/cop/layout/line_length.rb', line 178
def heredoc_body_after_method?(node) body_begin = node.body.source_range.begin_pos heredoc_openers.any? do |opener| (opener.line == node.first_line && opener.begin_pos < body_begin) || (opener.line == node.last_line && opener.begin_pos < node.source_range.end_pos) end end
#heredoc_openers (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 252
def heredoc_openers ast = processed_source.ast return [] if ast.nil? @heredoc_openers ||= ast.each_node(:any_str).select(&:heredoc?).map(&:source_range) end
#heredocs (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 489
def heredocs @heredocs ||= extract_heredocs(processed_source.ast) end
#highlight_start(line) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 493
def highlight_start(line) # TODO: The max with 0 is a quick fix to avoid crashes when a line # begins with many tabs, but getting a correct highlighting range # when tabs are used for indentation doesn't work currently. [max - indentation_difference(line), 0].max end
#largest_possible_string(node) (private)
Find the largest possible substring of a string node to retain before a break
# File 'lib/rubocop/cop/layout/line_length.rb', line 688
def largest_possible_string(node) # The maximum allowed length of a string value is: # `Max` - end delimiter (quote) - continuation characters (space and slash) max_length = max - 3 # Offset by the string's starting column so the broken line actually fits # within `Max`, whatever precedes the string on its line. max_length -= node.loc.column node.source[0, [max_length, 0].max] end
#leaves_two_parts?(node, content_begin_pos, pos) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 369
def leaves_two_parts?(node, content_begin_pos, pos) pos.end_pos > content_begin_pos && !blank_rest?(node, pos.end_pos) end
#line_in_permitted_heredoc?(line_number) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 611
def line_in_permitted_heredoc?(line_number) return false unless allowed_heredoc heredocs.any? do |range, delimiter| range.cover?(line_number) && (allowed_heredoc == true || allowed_heredoc.include?(delimiter)) end end
#max (private) Also known as: #max_line_length
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 588
def max cop_config['Max'] end
#max_line_length (private)
Alias for #max.
# File 'lib/rubocop/cop/layout/line_length.rb', line 591
alias max_line_length max
#next_string_break_position(node, pos, delimiter) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 569
def next_string_break_position(node, pos, delimiter) rest = parse("#{delimiter}#{node.source_range.with(begin_pos: pos).source}").ast return unless rest&.str_type? return unless (rest_pos = breakable_string_position(rest)) pos + rest_pos - delimiter.length end
#on_array(node)
Alias for #on_potential_breakable_node.
# File 'lib/rubocop/cop/layout/line_length.rb', line 108
alias on_array on_potential_breakable_node
#on_block(node) Also known as: #on_numblock, #on_itblock
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 91
def on_block(node) check_for_breakable_block(node) end
#on_csend(node)
Alias for #on_potential_breakable_node.
# File 'lib/rubocop/cop/layout/line_length.rb', line 111
alias on_csend on_potential_breakable_node
#on_def(node) Also known as: #on_defs
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 113
def on_def(node) if node.endless? track_endless_method(node) else check_for_breakable_node(node) end end
#on_defs(node)
Alias for #on_def.
# File 'lib/rubocop/cop/layout/line_length.rb', line 120
alias on_defs on_def
#on_dstr(node)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 101
def on_dstr(node) check_for_breakable_dstr(node) end
#on_hash(node)
Alias for #on_potential_breakable_node.
# File 'lib/rubocop/cop/layout/line_length.rb', line 109
alias on_hash on_potential_breakable_node
#on_investigation_end
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 135
def on_investigation_end processed_source.lines.each_with_index do |line, line_index| check_line(line, line_index) end end
#on_itblock(node)
Alias for #on_block.
# File 'lib/rubocop/cop/layout/line_length.rb', line 95
alias on_itblock on_block
#on_new_investigation
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 122
def on_new_investigation @breakable_range_by_line_index = {} @breakable_string_delimiters = {} @breakable_strings = {} @endless_methods_by_line = {} @heredocs = nil @heredoc_openers = nil return unless processed_source.raw_source.include?(';') check_for_breakable_semicolons(processed_source) end
#on_numblock(node)
Alias for #on_block.
# File 'lib/rubocop/cop/layout/line_length.rb', line 94
alias on_numblock on_block
#on_potential_breakable_node(node) Also known as: #on_array, #on_hash, #on_send, #on_csend
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 105
def on_potential_breakable_node(node) check_for_breakable_node(node) end
#on_send(node)
Alias for #on_potential_breakable_node.
# File 'lib/rubocop/cop/layout/line_length.rb', line 110
alias on_send on_potential_breakable_node
#on_str(node)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 97
def on_str(node) check_for_breakable_str(node) end
#opens_string?(begin_node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 465
def opens_string?(begin_node) quote = begin_node.parent.loc.begin return false unless quote blank_between?(quote.end_pos, begin_node.source_range.begin_pos) end
#range_if_applicable(line, type) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 654
def range_if_applicable(line, type) return unless type == :uri ? allow_uri? : allow_qualified_name? find_excessive_range(line, type) end
#receiver_contains_heredoc?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 620
def receiver_contains_heredoc?(node) return false unless (receiver = node.receiver) return true if receiver.any_str_type? && receiver.heredoc? receiver.each_descendant(:any_str).any?(&:heredoc?) end
#register_endless_method_offense(line, line_index) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 163
def register_endless_method_offense(line, line_index) = format(MSG, length: line_length(line), max: max) loc = excess_range(nil, line, line_index) node = endless_methods_by_line[line_index] add_offense(loc, message: ) do |corrector| self.max = line_length(line) correct_to_multiline(corrector, node) unless heredoc_body_after_method?(node) end end
#register_offense(loc, line, line_index, length: line_length(line)) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 531
def register_offense(loc, line, line_index, length: line_length(line)) = format(MSG, length: length, max: max) self.breakable_range = breakable_range_by_line_index[line_index] add_offense(loc, message: ) do |corrector| self.max = line_length(line) insertion = if (delimiter = breakable_string_delimiters[line_index]) [delimiter, " \\\n", delimiter].join else "\n" end break_ranges(line_index).each do |range| corrector.insert_before(range, insertion) end end end
#register_required_endless_method_offense(line, line_index) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 187
def register_required_endless_method_offense(line, line_index) node = endless_methods_by_line[line_index] loc = excess_range(nil, line, line_index) add_offense(loc, message: format(MSG, length: line_length(line), max: max)) do |corrector| self.max = line_length(line) if correctable_endless_method_block?(node) correct_endless_method_block_to_multiline(corrector, node) end end end
#shebang?(line, line_index) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 527
def shebang?(line, line_index) line_index.zero? && line.start_with?('#!') end
#size_before_whitespace_run(text, size) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 438
def size_before_whitespace_run(text, size) return size if size.zero? return size unless text[size]&.match?(/\s/) text.rindex(/\S/, size - 1) || size end
#space_before_word(node, max_pos) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 417
def space_before_word(node, max_pos) return if max_pos.negative? node.source.rindex(/\s(?=\S)/, max_pos) end
#starts_after_quote?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/layout/line_length.rb', line 380
def starts_after_quote?(node) return true if node.loc?(:begin) quote = node.parent&.loc&.begin if node.parent&.dstr_type? quote ? quote.end_pos == node.source_range.begin_pos : false end
#string_break_ranges(node, delimiter) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 558
def string_break_ranges(node, delimiter) ranges = [breakable_range] pos = breakable_range.begin_pos while (pos = next_string_break_position(node, pos, delimiter)) ranges << range_between(pos, pos + 1) end ranges end
#string_content_length(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 451
def string_content_length(node) content_end = node.loc?(:end) ? node.loc.end.begin_pos : node.source_range.end_pos content_end - node.source_range.begin_pos end
#string_delimiter(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 677
def string_delimiter(node) delimiter = if node.loc?(:begin) node.loc.begin elsif node.parent&.dstr_type? && node.parent.loc?(:begin) node.parent.loc.begin end&.source delimiter if %w[' "].include?(delimiter) end
#track_endless_method(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/layout/line_length.rb', line 145
def track_endless_method(node) line_index = node.first_line - processed_source.buffer.first_line endless_methods_by_line[line_index] = node end