How do you sort a range of lines by length?

前端 未结 3 670
情深已故
情深已故 2020-12-29 02:39

Often I just want to sort all my #include\'s at the top of my source and header files by their length.

vim allows me to sort alphanumerical

3条回答
  •  旧巷少年郎
    2020-12-29 03:17

    One way, neither elegant nor efficient, but it works:

    Add following function to your vimrc file. It inserts at the beginning of each line its number of characters, sort them numerically and deletes the numbers.

    function! SortLines() range
        execute a:firstline . "," . a:lastline . 's/^\(.*\)$/\=strdisplaywidth( submatch(0) ) . " " . submatch(0)/'
        execute a:firstline . "," . a:lastline . 'sort n'
        execute a:firstline . "," . a:lastline . 's/^\d\+\s//'
    endfunction
    

    Call it with a range of numbers, like

    :4,18call SortLines()
    

    or in Visual mode using V, like:

    :'<,'>call SortLines()
    

    EDIT: Ops, now I realised that this solution is very similar to yours. It was fine, only that % means the complete buffer instead :4,18 or :'<,:'> that selects specific lines.

提交回复
热议问题