Using vi, how can I make CSS rules into one liners?

后端 未结 7 910
眼角桃花
眼角桃花 2020-12-05 05:55

Example bad:

#main {
      padding:0;
      margin: 10px auto;
}

Example good:

#main {padding:0;margin:10px auto;}
<         


        
相关标签:
7条回答
  • 2020-12-05 06:36

    Here's a one-liner:

    :%s/{\_.\{-}}/\=substitute(submatch(0), '\n', '', 'g')/
    

    \_. matches any character, including a newline, and \{-} is the non-greedy version of *, so {\_.\{-}} matches everything between a matching pair of curly braces, inclusive.

    The \= allows you to substitute the result of a vim expression, which we here use to strip out all the newlines '\n' from the matched text (in submatch(0)) using the substitute() function.

    The inverse (converting the one-line version to multi-line) can also be done as a one liner:

    :%s/{\_.\{-}}/\=substitute(submatch(0), '[{;]', '\0\r', 'g')/
    
    0 讨论(0)
  • 2020-12-05 06:41

    Go to the first line of the file, and use the command gqG to run the whole file through the formatter. Assuming runs of nonempty lines should be collapsed in the whole file.

    0 讨论(0)
  • 2020-12-05 06:46

    A convenient way of doing this transformation is to run the following short command:

    :g/{/,/}/j
    
    0 讨论(0)
  • 2020-12-05 06:49

    I won’t answer the question directly, but instead I suggest you to reconsider your needs. I think that your “bad” example is in fact the better one. It is more readable, easier to modify and reason about. Good indentation is very important not only when it comes to programming languages, but also in CSS and HTML.

    You mention that CSS rules are “taking up too many lines”. If you are worried about file size, you should consider using CSS and JS minifiers like YUI Compressor instead of making the code less readable.

    0 讨论(0)
  • 2020-12-05 06:52

    If you are at the beginning or end of the rule, V%J will join it into a single line:

    • Go to the opening (or closing) brace
    • Hit V to enter visual mode
    • Hit % to match the other brace, selecting the whole rule
    • Hit J to join the lines
    0 讨论(0)
  • 2020-12-05 06:55

    Try something like this:

    :%s/{\n/{/g
    :%s/;\n/;/g
    :%s/{\s+/{/g
    :%s/;\s+/;/g
    

    This removes the newlines after opening braces and semicolons ('{' and ';') and then removes the extra whitespace between the concatenated lines.

    0 讨论(0)
提交回复
热议问题