Creating a Vim Quickfix List Programmatically

A Quickfix list in vim is a special buffer that stores a list of file and line locations. Using this list and some commands, you can quickly move through a list of edits.

Normally, a quickfix list is created when you run the grep command, but there are lots of applications where you want may want a list of files and locations. For instance, imagine you create a list of places in your source code that you want to look into later. I have a vim plugin that pulls Github PRs comments into a quickfix list, so I can review comments in my editor and make updates right where I need to.

The key to creating and opening a quickfix list programmatically is the cexpr command. cexpr takes a newline delimited string in a certain format. The format is defined by errorformat. You can set your own errorformat using:

1
:set efm=<your error format>

using special format % items. Here's a partial list of them:

1
2
3
%f     file name (finds a string)
%l      line number (finds a number)
%m      error message (finds a string)

See :help errorformat for the full docs.

Note that errorformat can hold multiple patterns, delimted by commas, so before you set yours, check what you already have on it with :set efm?.

Putting this altogether, lets say you create a file (quickfix.txt) of places you want to inspect like this:

1
2
3
file-a.py:14:this looks interesting
file-b.py:26:I have to remember to update this
file-c.py:84:This can be deleted when I am done

And you have set your errorformat like this:

1
:set efm=%f:%l:%m

Then you can open that into a quickfix list like this:

1
:cexp(readfile('quickfix.txt'))

2023-05-13