tags:

views:

208

answers:

2

I get a CSS file:

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

I want to Alphabetize lines between the {...}

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 map F7 to do it

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

But I need to press F7 over and over again to get the work done.
If the CSS file is big, It's time-consuming & easily get bored.
I want to get the cmds piped. So that, I only press F7 once!
Any idea? thanks!

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

This is what it does:

  1. zR opens all folds.
  2. gg moves the cursor to the first line.
  3. search("{$") searches for the opening brace at the end of line and moves cursor to the found position.
  4. search(, 'W') prevents search() from wrapping over the end of file, so it will return false after last found position.
  5. .+1,/}$/-1 sets the range to «from one line after (+1) cursor position (.) to the line before (-1) the closing brace at the end of line (/}$/)».
  6. sort sorts, you know it.
ZyX
+7  A: 
:g#\({\n\)\@<=#.,/}/sort

Explanation:

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

You can of course map this to a keyboard shortcut or make it into a command:

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

" Or:

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

Then you can simply hit F7 or run:

:SortCSSBraceContents
Al
phew! thats cool!!
Vijay Dev