代码之家  ›  专栏  ›  技术社区  ›  kev

如何在VIM中按字母顺序排列CSS文件

vim
  •  19
  • kev  · 技术社区  · 14 年前

    我得到一个CSS文件:

    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;
    }
    

    I映射 F7 做这件事

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

    但我要按 F7 一次又一次地完成工作。
    如果CSS文件很大,很容易让人厌烦,而且很耗时。
    我想通过管道传输命令。所以,我只按 F7 曾经!
    有什么想法吗?谢谢!

    4 回复  |  直到 8 年前
        1
  •  40
  •   DrAl    14 年前
    :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
    
        2
  •  7
  •   ZyX    14 年前
    nnoremap <S-F7> zRgg:while search("{$", 'W') \| .+1,/}$/-1sort \| endwhile<CR>
    

    这就是它的作用:

    1. zR 打开所有折叠。
    2. gg 将光标移到第一行。
    3. search("{$") 在行尾搜索左大括号并将光标移动到找到的位置。
    4. search(, 'W') 防止 search() 从包装结束的文件,所以它将返回假后,最后找到的位置。
    5. .+1,/}$/-1 将范围设置为“从后一行到后一行”( +1 )光标位置( . )前一行( -1 )线条末端的右大括号( /}$/ )
    6. sort 好吧,你知道的。
        3
  •  1
  •   Colin Shevlin    9 年前

    对于SCSS样式表:

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

    这将查找右大括号或另一个左大括号,并选择前面的行。

        4
  •  0
  •   tom eustace    8 年前

    对于VueJS单个文件组件、内联样式等,您只需要在元素中运行命令:

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