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

kev*_*kev 19 vim

我得到一个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;
}
Run Code Online (Sandbox Code Playgroud)

我想在{...}之间按字母顺序排列

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;
}
Run Code Online (Sandbox Code Playgroud)

我映射F7去做

nmap <F7> /{/+1<CR>vi{:sort<CR>
Run Code Online (Sandbox Code Playgroud)

但我需要F7一遍又一遍地按压才能完成工作.
如果CSS文件很大,那就太费时间而且很容易感到无聊.
我希望用管道传输cmds.所以,我只按F7一次!
任何的想法?谢谢!

DrA*_*rAl 40

:g#\({\n\)\@<=#.,/}/sort
Run Code Online (Sandbox Code Playgroud)

说明:

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
Run Code Online (Sandbox Code Playgroud)

您当然可以将其映射到键盘快捷键或将其作为命令:

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

" Or:

:command! SortCSSBraceContents :g#\({\n\)\@<=#.,/}/sort
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地点击F7或运行:

:SortCSSBraceContents
Run Code Online (Sandbox Code Playgroud)


ZyX*_*ZyX 7

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

这就是它的作用:

  1. zR 打开所有折叠.
  2. gg 将光标移动到第一行.
  3. search("{$") 在行尾搜索左括号并将光标移动到找到的位置.
  4. search(, 'W')防止search()包装在文件末尾,因此它将在最后找到的位置后返回false.
  5. .+1,/}$/-1将范围设置为«从(+1)光标位置(.)之后的一行到行之前的行(-1)()行结尾处的右括号/}$/.
  6. sort 你知道吗?