1

This function outputs data between braces as joined lines in a quickfix window. The output is sorted based on line numbers.

I'm searching for a method to sort the data alphabetically.

I tried to exclude bufnr and lnum, but that breaks the relocation to the actual buffer.

function! Overview() abort
    0
    let bufnr = bufnr('%')
    let items = []
    while 1
        let start = search('^{', 'cW')
        if !start
            break
        endif
        let end = search('^}', 'W')
        let lines = getline(start, end)
        let lines = map(lines, 'trim(v:val)')
        call add(items, {
            \ 'bufnr': bufnr,
            \ 'lnum': start,
            \ 'text': join(lines, ' '),
        \ })
    endwhile
    call setloclist(winnr(), items)
    lopen
endfunction
1
  • have you tried putting a sort() call after the endwhile? Commented Feb 1, 2019 at 14:28

1 Answer 1

1

Include a call to sort() with a custom sorting function. This works for me based on your description:

" custom function that sorts the items by the 'text' key
function! Sorter(i1, i2) abort
 return a:i1['text'] == a:i2['text'] ? 0 : a:i1['text'] > a:i2['text'] ? 1 : -1
endfunction

function! Overview() abort
    0
    let bufnr = bufnr('%')
    let items = []
    while 1
        let start = search('^{', 'cW')
        if !start
            break
        endif
        let end = search('^}', 'W')
        let lines = getline(start, end)
        let lines = map(lines, 'trim(v:val)')
        call add(items, {
            \ 'bufnr': bufnr,
            \ 'lnum': start,
            \ 'text': join(lines, ' '),
        \ })
    endwhile
    " sort using the Sorter function to compare items
    call sort(items, 'Sorter')
    call setloclist(winnr(), items)
    lopen
endfunction

See also :help sort() for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.