user2153281
user2153281

Reputation: 43

How to automatically sort Quickfix entries by line text in Vim?

I’m trying to automatically sort the lines in the Quickfix list alphabetically by the contents of the lines themselves (by default, it sorts by the order they appear in the file). I’ve put the below in my .vimrc, but for some reason it sorts according to the line numbers. As far as I can tell, the Quickfix list is a list of dictionaries, so the Sortqfbytext function below should only be sorting by the text content of each list item and ignoring the rest (including the line numbers).

function! s:Sortqfbytext(i1, i2)
  let textlist = []
  let textlist = [a:i1.text,a:i2.text]
  call sort(textlist)
  if textlist[0] == textlist[1]
    return 0
  elseif textlist[0] == a:i1.text
    return 1
  elseif textlist[0] == a:i2.text
    return -1
  endif
endfunction

function! s:Makesortedqflist()
  let xlist = sort(getqflist(), 's:Sortqfbytext')
  call setqflist(xlist)
endfunction

autocmd! QuickfixCmdPost * call s:Makesortedqflist()

Upvotes: 2

Views: 1103

Answers (2)

ib.
ib.

Reputation: 28964

I would implement this idea as follows.

autocmd! QuickfixCmdPost * call SortQuickfix('QfStrCmp')

function! SortQuickfix(fn)
    call setqflist(sort(getqflist(), a:fn))
endfunction

function! QfStrCmp(e1, e2)
    let [t1, t2] = [a:e1.text, a:e2.text]
    return t1 <# t2 ? -1 : t1 ==# t2 ? 0 : 1
endfunction

Upvotes: 1

Tsuyoshi CHO
Tsuyoshi CHO

Reputation: 11

QuickFix list update setqflist() needs the 'r' flag.

Just change call setqflist(xlist) to call setqflist(xlist, 'r')

Upvotes: 1

Related Questions