2010-06-16 14 views
19

我得到一個CSS文件:如何按字母順序排列一個CSS文件中的Vim

div#header h1 { 
    z-index: 101; 
    color: #000; 
    position: relative; 
    line-height: 24px; 
    margin-right: 48px; 
    border-bottom: 1px solid #dedede; 
    font-size: 18px; 
} 

div#header h2 { 
    z-index: 101; 
    color: #000; 
    position: relative; 
    line-height: 24px; 
    margin-right: 48px; 
    border-bottom: 1px solid #dedede; 
    font-size: 18px; 
} 

我想按字母順序排列之間{...}

div#header h1 { 
    border-bottom: 1px solid #dedede; 
    color: #000; 
    font-size: 18px; 
    line-height: 24px; 
    margin-right: 48px; 
    position: relative; 
    z-index: 101; 
} 

div#header h2 { 
    border-bottom: 1px solid #dedede; 
    color: #000; 
    font-size: 18px; 
    line-height: 24px; 
    margin-right: 48px; 
    position: relative; 
    z-index: 101; 
} 

我映射F7做它

nmap <F7> /{/+1<CR>vi{:sort<CR> 

但我需要一遍又一遍地按F7才能完成工作。
如果CSS文件比較大,很容易就會很無聊。
我想獲取cmd管道。所以,我只按一次F7
有什麼想法?謝謝!

+0

這是如何準確題外話,拉近? – 2010-06-16 06:37:37

+0

這真的很好,但這可能會導致很多新的CSS相關的錯誤,這些錯誤的屬性已經按照特定的順序定義了 – travis 2012-03-03 20:19:38

回答

40
:g#\({\n\)\@<=#.,/}/sort 

說明:

g  " Work over the whole file running .,/}/sort on each line that matches 
     " the pattern \({\n\)\@<= 
#...#... " Delimiters: first bit is search pattern, second bit is what 
     " to do on each matching line 
\(  " Grouping, containing: 
    {\n " Open brace followed by new line 
\)  " End of grouping 
\@<=  " Negative look-behind, so match after the new-line, but make sure that 
     " the match point is preceded by an open brace and a new-line 

.,/}/ " From this line to the next closing brace... 
sort  " Sort the lines 

你當然可以這樣映射到鍵盤快捷鍵或使之成爲一個命令:

:nmap <F7> :g#\({\n\)\@<=#.,/}/sort<CR> 

" Or: 

:command! SortCSSBraceContents :g#\({\n\)\@<=#.,/}/sort 

然後,你可以簡單地按下F7或運行:

:SortCSSBraceContents 
+3

phew!這很酷!! – 2010-06-17 15:13:39

+0

唯一的解決方法是,如果我在一個使用CSS和Javascript的HTML文件中運行它,它還會嘗試對所有的JS對象進行排序。 – 2010-12-24 16:38:18

+1

關於如何將-webkit-和-moz-values排序靠近但始終在跨瀏覽器的對應位置之前的任何想法?我正在使用「排序{模式}」功能在排序時忽略 - * - 內容,但不會按照我的意願排序-moz/-webkit /(real): sort/\ s * \( - \一* - \\ | \)/ – 2011-03-07 22:43:55

7
nnoremap <S-F7> zRgg:while search("{$", 'W') \| .+1,/}$/-1sort \| endwhile<CR> 

這是它做什麼:

  1. zR打開所有的摺疊。
  2. gg將光標移動到第一行。
  3. search("{$")在行尾搜索開口大括號並將光標移動到找到的位置。
  4. search(, 'W')防止search()包裝在文件末尾,所以它會在上次找到位置後返回false。
  5. .+1,/}$/-1設置範圍«從一條線之後(+1)的光標位置(.)到前行(-1)在管線(/}$/)的端部的閉括號»到。
  6. sort排序,你知道的。
1

對於SCSS樣式表:

:g#\({\n\)\@<=#.,/\.*[{}]\@=/-1 sort

這看起來爲任何一個右大括號或其他大括號和之前,它選擇行。

0

對於Vuejs單文件組件,內嵌式的,等等 - 在您需要的命令只有在運行元素:

:/<style>/,/<\/style>/:g#\({\n\)\@<=#.,/}/sort