2011-08-23 95 views
2

当我在vim中格式化PHP文件时没问题,但是当我格式化Ruby文件时,VIM格式代码不好。糟糕的格式化Vim中的ruby代码

例如:

class PostsController < ApplicationController 

       skip_before_filter :authorize, :only => [ :index, :show ] 

    def index 
     @posts = Post.all 
    end 

    def show 
    @post = Post.find(:first, :conditions => [ "id = ?", params[:id]], :include => [ :user, :category, :gallery ]) 
        @photos = Photo.where(:gallery_id => @post.gallery.id).all 
     end 
    end 

当我输入命令GG = G,我得到。

class PostsController < ApplicationController 

skip_before_filter :authorize, :only => [ :index, :show ] 

def index 
@posts = Post.all 
end 

def show 
@post = Post.find(:first, :conditions => [ "id = ?", params[:id]], :include => [ :user, :category, :gallery ]) 
@photos = Photo.where(:gallery_id => @post.gallery.id).all 
end 
end 

请帮帮我。

+0

你使用vim红宝石?这可能有所帮助:https://github.com/vim-ruby/vim-ruby –

回答

4

要让Ruby缩进工作,您需要提供缩进配置。 Vim本身不能缩进Ruby代码,你可以将indentexpr变量设置为一些类似的语言(比如basic),但是你不会对结果满意。检查smartindent和indentexpr变量:

:set si? 
:set indentexpr? 

在我的情况下,他们设置:

nosmartindent 
indentexpr=GetRubyIndent() 

为红宝石配置VIM的最好方法是使用vim-ruby的插件:https://github.com/vim-ruby/vim-ruby

+0

Okey,我安装了这个插件,现在呢?我应该怎么做才能修复不好的格式?对不起,但我是新手。 – B4k3r

+0

是的,一旦你安装它,Ruby应该格式化好。 – lzap

+0

你可以告诉Vim使用'='动作缩进某些代码 - 例如'= 10j'来缩进接下来的10行,或者'= G'缩进文件末尾。一旦你安装了一个插件或以其他方式告诉Vim如何格式化一些代码,你可以使用它来修复压缩不好的代码。请注意,1)添加插件后必须重新启动Vim; 2)缩进取决于文件类型检测。 vim-ruby [检测大多数Ruby文件](https://github.com/vim-ruby/vim-ruby/blob/master/ftdetect/ruby.vim),但你也可以添加你自己的ftdetect文件。 –

0

一存在更通用的格式化插件,称为vim-autoformat。 其中,它集成了rbeautify以提供更强的格式化,而不仅仅是修复缩进。

0

我不知道我是否有任何Vim插件,因为我在工作中使用它(并已安装)。但是,对于它的价值,这里是我的一些.vimrc文件。

syntax enable    " Enable syntax highlighting 
syntax on 
set expandtab    " Use spaces instead of tabs 
set shiftwidth=2   " 1 tab == 4 spaces 
set tabstop=2    " 1 tab == 4 spaces 

我实际上已在文件中注释掉了set smartindent[1]

如果你想更换任何制表字符用空格(在上面.vimrc设置),我在你的工作文件中提出了以下命令:set :retab[2]