Module: Cecil::Indentation

Defined in:
lib/cecil/indentation.rb

Defined Under Namespace

Modules: Ambiguity

Class Method Summary collapse

Class Method Details

.reindent(src, depth, indent_chars, handle_ambiguity: Ambiguity.raise_error) ⇒ Object

Reindent src string to the level specified by depth. indent_chars is used only the current level of indentation as well as add more indentation.

Reindents the given source code string to the specified depth.

Parameters:



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/cecil/indentation.rb', line 107

def reindent(src, depth, indent_chars, handle_ambiguity: Ambiguity.raise_error)
  # Turn
  # "\n" +
  # "  line 1\n" +
  # "    line 2\n"
  # into
  # "  line 1\n" +
  # "    line 2\n"
  src = src.sub(/\A\R/m, "")

  new_indentation = indent_chars * depth
  reindent_line_re = /^[ \t]{0,#{level(src, handle_ambiguity:)}}/

  lines = src.lines.map do |line|
    if line =~ /\S/
      line.sub(reindent_line_re, new_indentation)
    else
      line.sub(/^[ \t]*/, "")
    end
  end

  lines.join
end