2011-08-23 27 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]