On Tue, Jul 25, 2006 at 12:36:44AM +0400, Pavel Volkovitskiy wrote:
> Hello!
> 
> I have to sort python's list quite often, so i want to make a script to 
> do that
> 
> for example i have:
>    a = [
>       'aaa'  ,   'XXX',   'tttt','dsgrg', 'sdgsfdg', 'gfdgffg', 
> 'dfgfdgw:swf', 'sdfsdg', 'sdfgsdg', 'sdgsg', 'sdgsfdg'  , 'sdgdsg'
>    ]
> 
> and i need:
>    a = [
>        'aaa', 'dfgfdgw:swf', 'dsgrg', 'gfdgffg', 'sdfgsdg', 'sdfsdg',
>        'sdgdsg', 'sdgsfdg', 'sdgsfdg', 'sdgsg', 'tttt', 'XXX'
>    ]
> 
> left margin = 2 tab, textwidth=80, sorted case insensitive
> 
> i wrote script with "cut-and-paste" method, so i guess it can be optimized
> and now it works only in vim7, but i think it can be written in vim6 
> compatible mode, right?
> 
> script:
> ===================================================
> func! StrICmp(str1, str2)
>    if (a:str1 <? a:str2)
>       return -1
>    elseif (a:str1 >? a:str2)
>       return 1
>    else
>       return 0
>    endif
> endfunction
> 
> let s:cmpref = function( 'StrICmp' )
> 
> fun! PySort()
> 
>    let ai_revert = 0
>    let tw_revert = 0
>    let ignorecase_revert = 0
>    if ! &autoindent
>        let ai_revert = 1
>        set autoindent
>    endif
>    if &textwidth == 0
>        let tw_revert = 1
>        set textwidth=80
>    endif

     I think it is simpler to use

  let ai_revert = &l:ai
  let tw_revert = &l:tw
  setlocal autoindent textwidth=80

here and then 

  let &l:tw = tw_revert
  let &l:ai = ai_revert

below.

>    normal! gv"ay
>    let text = matchstr(@a, '\s*\zs.*\ze\s*')
>    let list = split(text, '\_s*,\_s*')
>    call sort(list, s:cmpref)
>    let @a = join(list, ', ')
>    normal! gv"ap

     Instead of these lines, I would do something like

  '<,'>s/,\s*/,\r/g
  '<,'>sort

If you want to use vim pre-7.0 and have an external sort program, then
use

  '<,'>!sort

instead of the second line.  Either way, you do not need the StrICmp()
function.  Finish up with something like the lines below to join the
lines and correct the indentation.

>        normal! >>
>        normal! >>
>        normal! gqq
> 
>    if ai_revert
>        set noautoindent
>    endif
>    if tw_revert
>        set textwidth=0
>    endif
> 
> endfun
> 
> map <C-S> :call PySort()<CR>

     How about calling it directly from Visual mode?

:vmap <C-S> :<C-U> PySort()<CR>

> ===================================================
> 
> Please, comment!

HTH                                     --Benji Fisher

Reply via email to