BeautifyRuby icon indicating copy to clipboard operation
BeautifyRuby copied to clipboard

Beautify selection only?

Open findchris opened this issue 11 years ago • 3 comments

The command beautifies the whole file. Any way to beautify just the selected text? Thanks.

findchris avatar Apr 10 '14 15:04 findchris

+1

brian-vogogo avatar Jan 28 '15 00:01 brian-vogogo

+1

andersennl avatar Jun 09 '15 12:06 andersennl

+1.

As a temporary workaround, open up beautify_ruby.py and replace the beautify_buffer function with this:

  def beautify_buffer(self, edit):
    sel = self.view.sel()
    if all(selection.empty() for selection in sel): # if there is no selection, 
      sel = [sublime.Region(0, self.view.size())]   # beautify the entire file
    for buffer_region in sel:
      # buffer_region = sublime.Region(0, self.view.size())
      buffer_text = self.view.substr(buffer_region)
      if buffer_text == "":
        return
      self.save_viewport_state()
      beautified_buffer = self.pipe(self.cmd(), buffer_text)
      fix_lines = beautified_buffer.replace(os.linesep,'\n')
      self.check_valid_output(fix_lines)
      self.view.replace(edit, buffer_region, fix_lines)
      self.reset_viewport_state()

This beautifies just the selections, or the entire file if there is no selection. However, BeautifyRuby treats it as if the selection is all there is in the file, so indentation is stripped down to the base indentation. To fix this, we could use python's textwrap module.

import textwrap
# skip a bunch of lines
  def beautify_buffer(self, edit):
    sel = self.view.sel()
    if all(selection.empty() for selection in sel):
      sel = [sublime.Region(0, self.view.size())]
    for buffer_region in sel:
      # buffer_region = sublime.Region(0, self.view.size())
      buffer_text = self.view.substr(buffer_region)
      indentation = len(buffer_text) - len(buffer_text.lstrip()) # this line
      if buffer_text == "":
        return
      self.save_viewport_state()
      beautified_buffer = self.pipe(self.cmd(), buffer_text)
      fix_lines = beautified_buffer.replace(os.linesep,'\n')
      fix_lines = textwrap.indent(fix_lines, ' ' * indentation) # and this one
      self.check_valid_output(fix_lines)
      self.view.replace(edit, buffer_region, fix_lines)
      self.reset_viewport_state()

Quincunx271 avatar Jul 22 '15 16:07 Quincunx271