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

19

我得到了一个 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;
}

我将F7键映射为执行该操作。

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

但是我需要一遍又一遍地按F7才能完成工作。
如果CSS文件很大,这将耗费时间并且容易感到厌倦。
我想要把命令管道化。这样,我只需要按一次F7!
有什么好的想法吗?谢谢!


这个问题怎么会完全不相关呢,更接近主题了吧? - meder omuraliev
这真的很不错,但这可能会导致许多新的与CSS相关的错误,因为属性已按特定顺序定义。 - travis
4个回答

42
: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

唯一的问题是,如果我在一个带有CSS和JavaScript的HTML文件中运行它,它也会尝试对所有JS对象进行排序。 - Darren Newton
1
你有什么想法可以让排序后的-webkit-和-moz-值靠近,但始终在其跨浏览器对应项之前?我正在使用“sort {pattern}”功能在排序时忽略“-*-”内容,但不能按照我希望的方式对-moz/-webkit/(real)进行排序:sort/\s(-\a-\|)/ - Doug Avery

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)到行末的右括号前一行(/}$/)。”
  6. sort排序,你知道的。

1

对于SCSS样式表:

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

这个命令查找闭合的花括号或另一个开放的花括号,并选择它之前的行。


0

对于 Vue 单文件组件、内联样式等,如果你需要让命令只在 <template> 元素内运行:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接