Skip to content

Beautify selection only? #69

Open
Open

Description

@findchris

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

Activity

  1. brian-vogogo commented on Jan 28, 2015

    @brian-vogogo

    +1

  2. andersennl commented on Jun 9, 2015

    @andersennl

    +1

  3. Quincunx271 commented on Jul 22, 2015

    @Quincunx271

    +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()
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions