Movatterモバイル変換


[0]ホーム

URL:


Quickfix

Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.


This subject is introduced in section30.1 of the user manual.

1. Using QuickFix commandsQuickfixE42

Vim has a special mode to speedup the edit-compile-edit cycle. This isinspired by the quickfix option of the Manx's Aztec C compiler on the Amiga.The idea is to save the error messages from the compiler in a file and use Vimto jump to the errors one by one. You can examine each problem and fix it,without having to remember all the error messages.
In Vim the quickfix commands are used more generally to find a list ofpositions in files. For example,:vimgrep finds pattern matches. You canuse the positions in a script with thegetqflist() function. Thus you cando a lot more than the edit/compile/fix cycle!
If you have the error messages in a file you can start Vim with:
vim -q filename
From inside Vim an easy way to run a command and handle the output is with the:make command (see below).
The'errorformat' option should be set to match the error messages from yourcompiler (seeerrorformat below).
quickfix-stackquickfix-IDEach quickfix list has a unique identifier called the quickfix ID and thisnumber will not change within a Vim session. Thegetqflist() function can beused to get the identifier assigned to a list. There is also a quickfix listnumber which may change whenever more than'chistory' lists are added to aquickfix stack.
location-listE776A location list is a window-local quickfix list. You get one after commandslike:lvimgrep,:lgrep,:lhelpgrep,:lmake, etc., which create alocation list instead of a quickfix list as the corresponding:vimgrep,:grep,:helpgrep,:make do.location-list-file-window
A location list is associated with a window and each window can have aseparate location list. A location list can be associated with only onewindow. The location list is independent of the quickfix list.
When a window with a location list is split, the new window gets a copy of thelocation list. When there are no longer any references to a location list,the location list is destroyed.
quickfix-changedtick
Every quickfix and location list has a read-only changedtick variable thattracks the total number of changes made to the list. Every time the quickfixlist is modified, this count is incremented. This can be used to perform anaction only when the list has changed. Thegetqflist() andgetloclist()functions can be used to query the current value of changedtick. You cannotchange the changedtick variable.
The following quickfix commands can be used. The location list commands aresimilar to the quickfix commands, replacing the 'c' prefix in the quickfixcommand with 'l'.
E924
If the current window was closed by anautocommand while processing alocation list command, it will be aborted.
E925E926If the current quickfix or location list was changed by anautocommand whileprocessing a quickfix or location list command, it will be aborted.
:cc
:cc[!] [nr]Display error [nr]. If [nr] is omitted, the same:[nr]cc[!]error is displayed again. Without [!] this doesn'twork when jumping to another buffer, the current bufferhas been changed, there is the only window for thebuffer and both'hidden' and'autowrite' are off.When jumping to another buffer with [!] any changes tothe current buffer are lost, unless'hidden' is set orthere is another window for this buffer.The'switchbuf' settings are respected when jumpingto a buffer.When used in the quickfix window the line number canbe used, including "." for the current line and "$"for the last line.
:ll
:ll[!] [nr]Same as ":cc", except the location list for the:[nr]ll[!]current window is used instead of the quickfix list.
:cn:cne:cnextE553:[count]cn[ext][!]Display the [count] next error in the list thatincludes a file name. If there are no file names atall, go to the [count] next error. See:cc for[!] and'switchbuf'.
]q
]qMapped to:cnext.default-mappings
:lne:lnext:[count]lne[xt][!]Same as ":cnext", except the location list for thecurrent window is used instead of the quickfix list.
]l
]lMapped to:lnext.default-mappings
:[count]cN[ext][!]:cp:cprevious:cprev:cN:cNext:[count]cp[revious][!]Display the [count] previous error in the list thatincludes a file name. If there are no file names atall, go to the [count] previous error. See:cc for[!] and'switchbuf'.
[q
[qMapped to:cprevious.default-mappings
:[count]lN[ext][!]:lp:lprevious:lprev:lN:lNext:[count]lp[revious][!]Same as ":cNext" and ":cprevious", except the locationlist for the current window is used instead of thequickfix list.
[l
[lMapped to:lprevious.default-mappings
:cabo:cabove:[count]cabo[ve]Go to the [count] error above the current line in thecurrent buffer. If [count] is omitted, then 1 isused. If there are no errors, then an error messageis displayed. Assumes that the entries in a quickfixlist are sorted by their buffer number and linenumber. If there are multiple errors on the same line,then only the first entry is used. If [count] exceedsthe number of entries above the current line, then thefirst error in the file is selected.
:lab:labove:[count]lab[ove]Same as ":cabove", except the location list for thecurrent window is used instead of the quickfix list.
:cbel:cbelow:[count]cbel[ow]Go to the [count] error below the current line in thecurrent buffer. If [count] is omitted, then 1 isused. If there are no errors, then an error messageis displayed. Assumes that the entries in a quickfixlist are sorted by their buffer number and linenumber. If there are multiple errors on the sameline, then only the first entry is used. If [count]exceeds the number of entries below the current line,then the last error in the file is selected.
:lbel:lbelow:[count]lbel[ow]Same as ":cbelow", except the location list for thecurrent window is used instead of the quickfix list.
:cbe:cbefore:[count]cbe[fore]Go to the [count] error before the current cursorposition in the current buffer. If [count] isomitted, then 1 is used. If there are no errors, thenan error message is displayed. Assumes that theentries in a quickfix list are sorted by their buffer,line and column numbers. If [count] exceeds thenumber of entries before the current position, thenthe first error in the file is selected.
:lbe:lbefore:[count]lbe[fore]Same as ":cbefore", except the location list for thecurrent window is used instead of the quickfix list.
:caf:cafter:[count]caf[ter]Go to the [count] error after the current cursorposition in the current buffer. If [count] isomitted, then 1 is used. If there are no errors, thenan error message is displayed. Assumes that theentries in a quickfix list are sorted by their buffer,line and column numbers. If [count] exceeds thenumber of entries after the current position, thenthe last error in the file is selected.
:laf:lafter:[count]laf[ter]Same as ":cafter", except the location list for thecurrent window is used instead of the quickfix list.
:cnf:cnfile:[count]cnf[ile][!]Display the first error in the [count] next file inthe list that includes a file name. If there are nofile names at all or if there is no next file, go tothe [count] next error. See:cc for [!] and'switchbuf'.
]CTRL-Q
]CTRL-QMapped to:cnfile.default-mappings
:lnf:lnfile:[count]lnf[ile][!]Same as ":cnfile", except the location list for thecurrent window is used instead of the quickfix list.
]CTRL-L
]CTRL-LMapped to:lnfile.default-mappings
:[count]cNf[ile][!]:cpf:cpfile:cNf:cNfile:[count]cpf[ile][!]Display the last error in the [count] previous file inthe list that includes a file name. If there are nofile names at all or if there is no next file, go tothe [count] previous error. See:cc for [!] and'switchbuf'.
[CTRL-Q
[CTRL-QMapped to:cpfile.default-mappings
:[count]lNf[ile][!]:lpf:lpfile:lNf:lNfile:[count]lpf[ile][!]Same as ":cNfile" and ":cpfile", except the locationlist for the current window is used instead of thequickfix list.
[CTRL-L
[CTRL-LMapped to:lpfile.default-mappings
:crewind:cr:cr[ewind][!] [nr]Display error [nr]. If [nr] is omitted, the FIRSTerror is displayed. See:cc.
[Q
[QMapped to:crewind.default-mappings
:lrewind:lr:lr[ewind][!] [nr]Same as ":crewind", except the location list for thecurrent window is used instead of the quickfix list.
[L
[LMapped to:lrewind.default-mappings
:cfirst:cfir:cfir[st][!] [nr]Same as ":crewind".
:lfirst:lfir:lfir[st][!] [nr]Same as ":lrewind".
:clast:cla:cla[st][!] [nr]Display error [nr]. If [nr] is omitted, the LASTerror is displayed. See:cc.
]Q
]QMapped to:clast.
:llast:lla:lla[st][!] [nr]Same as ":clast", except the location list for thecurrent window is used instead of the quickfix list.
]L
]LMapped to:llast.
:cq:cquit:cq[uit][!]:{N}cq[uit][!]:cq[uit][!]{N}Quit Vim with error code{N}.{N} defaults to one.Useful when Vim is called from another program:e.g., a compiler will not compile the same file again,git commit will abort the committing process,fc(built-in for shells like bash and zsh) will notexecute the command, etc.{N} can also be zero, in which case Vim exitsnormally.WARNING: All changes in files are lost. It works like":qall!":qall, except that Nvim exits non-zero or[count].
:cf:cfi:cfile:cf[ile][!] [errorfile]Read the error file and jump to the first error.This is done automatically when Vim is started withthe -q option. You can use this command when youkeep Vim running while compiling. If you give thename of the errorfile, the'errorfile' option willbe set to [errorfile]. See:cc for [!].If the encoding of the error file differs from the'encoding' option, you can use the'makeencoding'option to specify the encoding.
:lf:lfi:lfile:lf[ile][!] [errorfile]Same as ":cfile", except the location list for thecurrent window is used instead of the quickfix list.You can not use the -q command-line option to setthe location list.
:cg[etfile] [errorfile]:cg:cgetfileRead the error file. Just like ":cfile" but don'tjump to the first error.If the encoding of the error file differs from the'encoding' option, you can use the'makeencoding'option to specify the encoding.
:lg[etfile] [errorfile]:lg:lge:lgetfileSame as ":cgetfile", except the location list for thecurrent window is used instead of the quickfix list.
:caddf:caddfile:caddf[ile] [errorfile]Read the error file and add the errors from theerrorfile to the current quickfix list. If a quickfixlist is not present, then a new list is created.If the encoding of the error file differs from the'encoding' option, you can use the'makeencoding'option to specify the encoding.
:laddf:laddfile:laddf[ile] [errorfile]Same as ":caddfile", except the location list for thecurrent window is used instead of the quickfix list.
:cb:cbufferE681:[range]cb[uffer][!] [bufnr]Read the error list from the current buffer.When [bufnr] is given it must be the number of aloaded buffer. That buffer will then be used insteadof the current buffer.A range can be specified for the lines to be used.Otherwise all lines in the buffer are used.See:cc for [!].
:lb:lbuffer:[range]lb[uffer][!] [bufnr]Same as ":cbuffer", except the location list for thecurrent window is used instead of the quickfix list.
:cgetb:cgetbuffer:[range]cgetb[uffer] [bufnr]Read the error list from the current buffer. Justlike ":cbuffer" but don't jump to the first error.
:lgetb:lgetbuffer:[range]lgetb[uffer] [bufnr]Same as ":cgetbuffer", except the location list forthe current window is used instead of the quickfixlist.
:cad:cadd:caddbuffer:[range]cad[dbuffer] [bufnr]Read the error list from the current buffer and addthe errors to the current quickfix list. If aquickfix list is not present, then a new list iscreated. Otherwise, same as ":cbuffer".
:laddb:laddbuffer:[range]laddb[uffer] [bufnr]Same as ":caddbuffer", except the location list forthe current window is used instead of the quickfixlist.
:cex:cexprE777:cex[pr][!]{expr}Create a quickfix list using the result of{expr} andjump to the first error.If{expr} is a String, then each newline terminatedline in the String is processed using the global valueof'errorformat' and the result is added to thequickfix list.If{expr} is a List, then each String item in the listis processed and added to the quickfix list. NonString items in the List are ignored.See:cc for [!].Examples:
:cexpr system('grep -n xyz *'):cexpr getline(1, '$')
:lex:lexpr:lex[pr][!]{expr}Same as:cexpr, except the location list for thecurrent window is used instead of the quickfix list.
:cgete:cgetexpr:cgete[xpr]{expr}Create a quickfix list using the result of{expr}.Just like:cexpr, but don't jump to the first error.
:lgete:lgetexpr:lgete[xpr]{expr}Same as:cgetexpr, except the location list for thecurrent window is used instead of the quickfix list.
:cadde:caddexpr:cadde[xpr]{expr}Evaluate{expr} and add the resulting lines to thecurrent quickfix list. If a quickfix list is notpresent, then a new list is created. The currentcursor position will not be changed. See:cexpr formore information.Example:
:g/mypattern/caddexpr expand("%") .. ":" .. line(".") ..  ":" .. getline(".")
:lad:ladd:laddexpr:lad[dexpr]{expr}Same as ":caddexpr", except the location list for thecurrent window is used instead of the quickfix list.
:cl:clist:cl[ist] [from] [, [to]]List all errors that are validquickfix-valid.If numbers [from] and/or [to] are given, the respectiverange of errors is listed. A negative number countsfrom the last error backwards, -1 being the last error.The:filter command can be used to display only thequickfix entries matching a supplied pattern. Thepattern is matched against the filename, module name,pattern and text of the entry.
:cl[ist] +{count}List the current and next{count} valid errors. Thisis similar to ":clist from from+count", where "from"is the current error position.
:cl[ist]! [from] [, [to]]List all errors.
:cl[ist]! +{count}List the current and next{count} error lines. Thisis useful to see unrecognized lines after the currentone. For example, if ":clist" shows:
8384 testje.java:252: error: cannot find symbol
Then using ":cl! +3" shows the reason:
8384 testje.java:252: error: cannot find symbol
8385: ZexitCode = Fmainx();
8386: ^
8387: symbol: method Fmainx()
:lli[st] [from] [, [to]]:lli:llistSame as ":clist", except the location list for thecurrent window is used instead of the quickfix list.
:lli[st]! [from] [, [to]]List all the entries in the location list for thecurrent window.
If you insert or delete lines, mostly the correct error location is stillfound because hidden marks are used. Sometimes, when the mark has beendeleted for some reason, the message "line changed" is shown to warn you thatthe error location may not be correct. If you quit Vim and start again themarks are lost and the error locations may not be correct anymore.
Two autocommands are available for running commands before and after aquickfix command (':make', ':grep' and so on) is executed. SeeQuickFixCmdPre andQuickFixCmdPost for details.
QuickFixCmdPost-example
When'encoding' differs from the locale, the error messages may have adifferent encoding from what Vim is using. To convert the messages you canuse this code:
function QfMakeConv()   let qflist = getqflist()   for i in qflist      let i.text = iconv(i.text, "cp936", "utf-8")   endfor   call setqflist(qflist)endfunctionau QuickfixCmdPost make call QfMakeConv()
Another option is using'makeencoding'.
quickfix-title
Every quickfix and location list has a title. By default the title is set tothe command that created the list. Thegetqflist() andgetloclist()functions can be used to get the title of a quickfix and a location listrespectively. Thesetqflist() andsetloclist() functions can be used tomodify the title of a quickfix and location list respectively. Examples:
call setqflist([], 'a', {'title' : 'Cmd output'})echo getqflist({'title' : 1})call setloclist(3, [], 'a', {'title' : 'Cmd output'})echo getloclist(3, {'title' : 1})
quickfix-index
When you jump to a quickfix/location list entry using any of the quickfixcommands (e.g.:cc,:cnext,:cprev, etc.), that entry becomes thecurrently selected entry. The index of the currently selected entry in aquickfix/location list can be obtained using the getqflist()/getloclist()functions. Examples:
echo getqflist({'idx' : 0}).idxecho getqflist({'id' : qfid, 'idx' : 0}).idxecho getloclist(2, {'idx' : 0}).idx
For a new quickfix list, the first entry is selected and the index is 1. Anyentry in any quickfix/location list can be set as the currently selected entryusing the setqflist() function. Examples:
call setqflist([], 'a', {'idx' : 12})call setqflist([], 'a', {'id' : qfid, 'idx' : 7})call setloclist(1, [], 'a', {'idx' : 7})
quickfix-size
You can get the number of entries (size) in a quickfix and a location listusing thegetqflist() andgetloclist() functions respectively. Examples:
echo getqflist({'size' : 1})echo getloclist(5, {'size' : 1})
quickfix-context
Any Vim type can be associated as a context with a quickfix or location list.Thesetqflist() and thesetloclist() functions can be used to associate acontext with a quickfix and a location list respectively. Thegetqflist()and thegetloclist() functions can be used to retrieve the context of aquickfix and a location list respectively. This is useful for a Vim plugindealing with multiple quickfix/location lists.Examples:
let somectx = {'name' : 'Vim', 'type' : 'Editor'}call setqflist([], 'a', {'context' : somectx})echo getqflist({'context' : 1})let newctx = ['red', 'green', 'blue']call setloclist(2, [], 'a', {'id' : qfid, 'context' : newctx})echo getloclist(2, {'id' : qfid, 'context' : 1})
quickfix-parse
You can parse a list of lines using'errorformat' without creating ormodifying a quickfix list using thegetqflist() function. Examples:
echo getqflist({'lines' : ["F1:10:Line10", "F2:20:Line20"]})echo getqflist({'lines' : systemlist('grep -Hn quickfix *')})
This returns a dictionary where the "items" key contains the list of quickfixentries parsed from lines. The following shows how to use a custom'errorformat' to parse the lines without modifying the'errorformat' option:
echo getqflist({'efm' : '%f#%l#%m', 'lines' : ['F1#10#Line']})
EXECUTE A COMMAND IN ALL THE BUFFERS IN QUICKFIX OR LOCATION LIST::cdo
:cdo[!]{cmd}Execute{cmd} in each valid entry in the quickfix list.It works like doing this:
:cfirst:{cmd}:cnext:{cmd}etc.
When the current file can't beabandoned and the [!]is not present, the command fails.When going to the next entry fails execution stops.The last buffer (or where an error occurred) becomesthe current buffer.{cmd} can contain '|' to concatenate several commands.
Only valid entries in the quickfix list are used.A range can be used to select entries, e.g.:
:10,$cdo cmd
To skip entries 1 to 9.
Note: While this command is executing, the Syntaxautocommand event is disabled by adding it to'eventignore'. This considerably speeds up editingeach buffer.Also see:bufdo,:tabdo,:argdo,:windo,:ldo,:cfdo and:lfdo.
:cfdo
:cfdo[!]{cmd}Execute{cmd} in each file in the quickfix list.It works like doing this:
:cfirst:{cmd}:cnfile:{cmd}etc.
Otherwise it works the same as:cdo.
:ldo
:ld[o][!]{cmd}Execute{cmd} in each valid entry in the location listfor the current window.It works like doing this:
:lfirst:{cmd}:lnext:{cmd}etc.
Only valid entries in the location list are used.Otherwise it works the same as:cdo.
:lfdo
:lfdo[!]{cmd}Execute{cmd} in each file in the location list forthe current window.It works like doing this:
:lfirst:{cmd}:lnfile:{cmd}etc.
Otherwise it works the same as:ldo.
FILTERING A QUICKFIX OR LOCATION LIST:cfilter-plugin:Cfilter:Lfilterpackage-cfilterIf you have too many entries in a quickfix list, you can use the cfilterplugin to reduce the number of entries. Load the plugin with:
packadd cfilter
Then you can use the following commands to filter a quickfix/location list:
:Cfilter[!] /{pat}/:Lfilter[!] /{pat}/
The:Cfilter command creates a new quickfix list from the entries matching{pat} in the current quickfix list.{pat} is a Vimregular-expressionpattern. Both the file name and the text of the entries are matched against{pat}. If the optional ! is supplied, then the entries not matching{pat} areused. The pattern can be optionally enclosed using one of the followingcharacters: ', ", /. If the pattern is empty, then the last used searchpattern is used.
The:Lfilter command does the same as:Cfilter but operates on the currentlocation list.
The current quickfix/location list is not modified by these commands, so youcan go back to the unfiltered list using the:colder/|:lolder| command.

2. The error windowquickfix-window

:cope:copenw:quickfix_title:cope[n] [height]Open a window to show the current list of errors.
When [height] is given, the window becomes that high(if there is room). When [height] is omitted thewindow is made ten lines high.
If there already is a quickfix window, it will be madethe current window. It is not possible to open asecond quickfix window. If [height] is given theexisting window will be resized to it.
quickfix-buffer
The window will contain a special buffer, with'buftype' equal to "quickfix". Don't change this!The window will have the w:quickfix_title variable setwhich will indicate the command that produced thequickfix list. This can be used to compose a customstatus line if the value of'statusline' is adjustedproperly. Whenever this buffer is modified by aquickfix command or function, theb:changedtickvariable is incremented. You can get the number ofthis buffer using the getqflist() and getloclist()functions by passing the "qfbufnr" item. For alocation list, this buffer is wiped out when thelocation list is removed.
:lop:lopen:lop[en] [height]Open a window to show the location list for thecurrent window. Works only when the location list forthe current window is present. You can have more thanone location window opened at a time. Otherwise, itacts the same as ":copen".
:ccl:cclose:ccl[ose]Close the quickfix window.
:lcl:lclose:lcl[ose]Close the window showing the location list for thecurrent window.
:cw:cwindow:cw[indow] [height]Open the quickfix window when there are recognizederrors. If the window is already open and there areno recognized errors, close the window.
:lw:lwindow:lw[indow] [height]Same as ":cwindow", except use the window showing thelocation list for the current window.
:cbo:cbottom:cbo[ttom]Put the cursor in the last line of the quickfix windowand scroll to make it visible. This is useful forwhen errors are added by an asynchronous callback.Only call it once in a while if there are manyupdates to avoid a lot of redrawing.
:lbo:lbottom:lbo[ttom]Same as ":cbottom", except use the window showing thelocation list for the current window.
Normally the quickfix window is at the bottom of the screen. If there arevertical splits, it's at the bottom of the rightmost column of windows. Tomake it always occupy the full width:
:botright cwindow
You can move the window around withwindow-moving commands.For example, to move it to the top:CTRL-W KThe'winfixheight' option will be set, which means that the window will mostlykeep its height, ignoring'winheight' and'equalalways'. You can change theheight manually (e.g., by dragging the status line above it with the mouse).
In the quickfix window, each line is one error. The line number is equal tothe error number. The current entry is highlighted with the QuickFixLinehighlighting. You can change it to your liking, e.g.:
:hi QuickFixLine ctermbg=Yellow guibg=Yellow
You can use ":.cc" to jump to the error under the cursor.Hitting the<Enter> key or double-clicking the mouse on a line has the sameeffect. The file containing the error is opened in the window above thequickfix window. If there already is a window for that file, it is usedinstead. If the buffer in the used window has changed, and the error is inanother file, jumping to the error will fail. You will first have to makesure the window contains a buffer which can be abandoned.
When you select a file from the quickfix window, the following steps are usedto find a window to edit the file:
1. If a window displaying the selected file is present in the current tabpage (starting with the window before the quickfix window), then that window is used.2. If the above step fails and if'switchbuf' contains "usetab" and a window displaying the selected file is present in any one of the tabpages (starting with the first tabpage) then that window is used.3. If the above step fails then a window in the current tabpage displaying a buffer with'buftype' not set (starting with the window before the quickfix window) is used.4. If the above step fails and if'switchbuf' contains "uselast", then the previously accessed window is used.5. If the above step fails then the window before the quickfix window is used. If there is no previous window, then the window after the quickfix window is used.6. If the above step fails, then a new horizontally split window above the quickfix window is used.
CTRL-W_<Enter>CTRL-W_<CR>You can useCTRL-W<Enter> to open a new window and jump to the error there.
When the quickfix window has been filled, two autocommand events aretriggered. First the'filetype' option is set to "qf", which triggers theFileType event (also seeqf.vim). Then the BufReadPost event is triggered,using "quickfix" for the buffer name. This can be used to perform some actionon the listed errors. Example:
au BufReadPost quickfix  setlocal modifiable        \ | silent exe 'g/^/s//\=line(".") .. " "/'        \ | setlocal nomodifiable
This prepends the line number to each line. Note the use of "\=" in thesubstitute string of the ":s" command, which is used to evaluate anexpression.The BufWinEnter event is also triggered, again using "quickfix" for the buffername.
Note: When adding to an existing quickfix list the autocommand are nottriggered.
Note: Making changes in the quickfix window has no effect on the list oferrors.'modifiable' is off to avoid making changes. If you delete or insertlines anyway, the relation between the text and the error number is messed up.If you really want to do this, you could write the contents of the quickfixwindow to a file and use ":cfile" to have it parsed and used as the new errorlist.
location-list-window
The location list window displays the entries in a location list. When youopen a location list window, it is created below the current window anddisplays the location list for the current window. The location list windowis similar to the quickfix window, except that you can have more than onelocation list window open at a time. When you use a location list command inthis window, the displayed location list is used.
When you select a file from the location list window, the following steps areused to find a window to edit the file:
1. If a non-quickfix window associated with the location list is present in the current tabpage, then that window is used.2. If the above step fails and if the file is already opened in another window in the current tabpage, then that window is used.3. If the above step fails and'switchbuf' contains "usetab" and if the file is opened in a window in any one of the tabpages, then that window is used.4. If the above step fails then a window in the current tabpage showing a buffer with'buftype' not set is used.5. If the above step fails, then the file is edited in a new window.
In all of the above cases, if the location list for the selected window is notyet set, then it is set to the location list displayed in the location listwindow.
quickfix-window-ID
You can use thegetqflist() andgetloclist() functions to obtain thewindow ID of the quickfix window and location list window respectively (ifpresent). Examples:
echo getqflist({'winid' : 1}).winidecho getloclist(2, {'winid' : 1}).winid
getqflist-examples
Thegetqflist() andgetloclist() functions can be used to get the variousattributes of a quickfix and location list respectively. Some examples forusing these functions are below:
" get the title of the current quickfix list:echo getqflist({'title' : 0}).title" get the identifier of the current quickfix list:let qfid = getqflist({'id' : 0}).id" get the identifier of the fourth quickfix list in the stack:let qfid = getqflist({'nr' : 4, 'id' : 0}).id" check whether a quickfix list with a specific identifier exists:if getqflist({'id' : qfid}).id == qfid" get the index of the current quickfix list in the stack:let qfnum = getqflist({'nr' : 0}).nr" get the items of a quickfix list specified by an identifier:echo getqflist({'id' : qfid, 'items' : 0}).items" get the number of entries in a quickfix list specified by an id:echo getqflist({'id' : qfid, 'size' : 0}).size" get the context of the third quickfix list in the stack:echo getqflist({'nr' : 3, 'context' : 0}).context" get the number of quickfix lists in the stack:echo getqflist({'nr' : '$'}).nr" get the number of times the current quickfix list is changed:echo getqflist({'changedtick' : 0}).changedtick" get the current entry in a quickfix list specified by an identifier:echo getqflist({'id' : qfid, 'idx' : 0}).idx" get all the quickfix list attributes using an identifier:echo getqflist({'id' : qfid, 'all' : 0})" parse text from a List of lines and return a quickfix list:let myList = ["a.java:10:L10", "b.java:20:L20"]:echo getqflist({'lines' : myList}).items" parse text using a custom 'efm' and return a quickfix list:echo getqflist({'lines' : ['a.c#10#Line 10'], 'efm':'%f#%l#%m'}).items" get the quickfix list window id:echo getqflist({'winid' : 0}).winid" get the quickfix list window buffer number:echo getqflist({'qfbufnr' : 0}).qfbufnr" get the context of the current location list:echo getloclist(0, {'context' : 0}).context" get the location list window id of the third window:echo getloclist(3, {'winid' : 0}).winid" get the location list window buffer number of the third window:echo getloclist(3, {'qfbufnr' : 0}).qfbufnr" get the file window id of a location list window (winnr: 4):echo getloclist(4, {'filewinid' : 0}).filewinid
setqflist-examples
Thesetqflist() andsetloclist() functions can be used to set the variousattributes of a quickfix and location list respectively. Some examples forusing these functions are below:
" create an empty quickfix list with a title and a context:let t = 'Search results':let c = {'cmd' : 'grep'}:call setqflist([], ' ', {'title' : t, 'context' : c})" set the title of the current quickfix list:call setqflist([], 'a', {'title' : 'Mytitle'})" change the current entry in the list specified by an identifier:call setqflist([], 'a', {'id' : qfid, 'idx' : 10})" set the context of a quickfix list specified by an identifier:call setqflist([], 'a', {'id' : qfid, 'context' : {'val' : 100}})" create a new quickfix list from a command output:call setqflist([], ' ', {'lines' : systemlist('grep -Hn main *.c')})" parse text using a custom efm and add to a particular quickfix list:call setqflist([], 'a', {'id' : qfid,            \ 'lines' : ["a.c#10#L10", "b.c#20#L20"], 'efm':'%f#%l#%m'})" add items to the quickfix list specified by an identifier:let newItems = [{'filename' : 'a.txt', 'lnum' : 10, 'text' : "Apple"},                \ {'filename' : 'b.txt', 'lnum' : 20, 'text' : "Orange"}]:call setqflist([], 'a', {'id' : qfid, 'items' : newItems})" empty a quickfix list specified by an identifier:call setqflist([], 'r', {'id' : qfid, 'items' : []})" free all the quickfix lists in the stack:call setqflist([], 'f')" set the title of the fourth quickfix list:call setqflist([], 'a', {'nr' : 4, 'title' : 'SomeTitle'})" create a new quickfix list at the end of the stack:call setqflist([], ' ', {'nr' : '$',                    \ 'lines' : systemlist('grep -Hn class *.java')})" create a new location list from a command output:call setloclist(0, [], ' ', {'lines' : systemlist('grep -Hn main *.c')})" replace the location list entries for the third window:call setloclist(3, [], 'r', {'items' : newItems})

3. Using more than one list of errorsquickfix-error-lists

So far it has been assumed that there is only one list of errors. Actuallythere can be multiple used lists that are remembered; see'chistory' and'lhistory'.When starting a new list, the previous ones are automatically kept. Twocommands can be used to access older error lists. They set one of theexisting error lists as the current one.
:colder:colE380:col[der] [count]Go to older error list. When [count] is given, dothis [count] times. When already at the oldest errorlist, an error message is given.
:lolder:lol:lol[der] [count]Same as:colder, except use the location list forthe current window instead of the quickfix list.
:cnewer:cnewE381:cnew[er] [count]Go to newer error list. When [count] is given, dothis [count] times. When already at the newest errorlist, an error message is given.
:lnewer:lnew:lnew[er] [count]Same as:cnewer, except use the location list forthe current window instead of the quickfix list.
:chistory:chi:[count]chi[story]Show the list of error lists. The current list ismarked with ">". The output looks like:
  error list 1 of 3; 43 errors   :make> error list 2 of 3; 0 errors    :helpgrep tag  error list 3 of 3; 15 errors   :grep ex_help *.c
When [count] is given, then the count'th quickfixlist is made the current list. Example:
" Make the 4th quickfix list current:4chistory
:lhistory:lhi:[count]lhi[story]Show the list of location lists, otherwise like:chistory.
When adding a new error list, it becomes the current list.
When ":colder" has been used and ":make" or ":grep" is used to add a new errorlist, one newer list is overwritten. This is especially useful if you arebrowsing with ":grep"grep. If you want to keep the more recent errorlists, use ":cnewer 99" first.
To get the number of lists in the quickfix and location list stack, you canuse thegetqflist() andgetloclist() functions respectively with the listnumber set to the special value '$'. Examples:
echo getqflist({'nr' : '$'}).nrecho getloclist(3, {'nr' : '$'}).nr
To get the number of the current list in the stack:
echo getqflist({'nr' : 0}).nr

4. Using :make:make_makeprg

:mak:make:mak[e][!] [arguments]1. All relevantQuickFixCmdPre autocommands are executed.2. If the'autowrite' option is on, write any changed buffers3. An errorfile name is made from'makeef'. If'makeef' doesn't contain "##", and a file with this name already exists, it is deleted.4. The program given with the'makeprg' option is started (default "make") with the optional [arguments] and the output is saved in the errorfile (for Unix it is also echoed on the screen).5. The errorfile is read using'errorformat'.6. All relevantQuickFixCmdPost autocommands are executed. See example below.7. If [!] is not given the first error is jumped to.8. The errorfile is deleted.9. You can now move through the errors with commands like:cnext and:cprevious, see above.This command does not accept a comment, any "characters are considered part of the arguments.If the encoding of the program output differs from the'encoding' option, you can use the'makeencoding'option to specify the encoding.
:lmak:lmake:lmak[e][!] [arguments]Same as ":make", except the location list for thecurrent window is used instead of the quickfix list.
The ":make" command executes the command given with the'makeprg' option.This is done by passing the command to the shell given with the'shell'option. This works almost like typing
":!{makeprg} [arguments]{shellpipe}{errorfile}".
{makeprg} is the string given with the'makeprg' option. Any command can beused, not just "make". Characters '%' and '#' are expanded as usual on acommand-line. You can use "%<" to insert the current file name withoutextension, or "#<" to insert the alternate file name without extension, forexample:
:set makeprg=make\ #<.o
[arguments] is anything that is typed after ":make".{shellpipe} is the'shellpipe' option.{errorfile} is the'makeef' option, with ## replaced to make it unique.
The placeholder "$*" can be used for the argument list in{makeprg} if thecommand needs some additional characters after its arguments. The $* isreplaced then by all arguments. Example:
:set makeprg=latex\ \\\\nonstopmode\ \\\\input\\{$*}
or simpler
:let &mp = 'latex \\nonstopmode \\input\{$*}'
"$*" can be given multiple times, for example:
:set makeprg=gcc\ -o\ $*\ $*
The'shellpipe' option defaults to "2>&1| tee" for Win32.This means that the output of the compiler is saved in a file and not shown onthe screen directly. For Unix "| tee" is used. The compiler output is shownon the screen and saved in a file the same time. Depending on the shell used"|& tee" or "2>&1| tee" is the default, so stderr output will be included.
If'shellpipe' is empty, the{errorfile} part will be omitted. This is usefulfor compilers that write to an errorfile themselves.
Using QuickFixCmdPost to fix the encoding
It may be that'encoding' is set to an encoding that differs from the messagesyour build program produces. This example shows how to fix this after Vim hasread the error messages:
function QfMakeConv()   let qflist = getqflist()   for i in qflist      let i.text = iconv(i.text, "cp936", "utf-8")   endfor   call setqflist(qflist)endfunctionau QuickfixCmdPost make call QfMakeConv()
(Example by Faque Cheng)Another option is using'makeencoding'.

5. Using :vimgrep and :grepgreplid

Vim has two ways to find matches for a pattern: internal and external. Theadvantage of the internal grep is that it works on all systems and uses thepowerful Vim search patterns. An external grep program can be used when theVim grep does not do what you want.
The internal method will be slower, because files are read into memory. Theadvantages are:
Line separators and encoding are automatically recognized, as if a file is being edited.
Uses Vim search patterns. Multi-line patterns can be used.
When plugins are enabled: compressed and remote files can be searched.gzipnetrw
To be able to do this Vim loads each file as if it is being edited. Whenthere is no match in the file the associated buffer is wiped out again. The'hidden' option is ignored here to avoid running out of memory or filedescriptors when searching many files. However, when the:hide commandmodifier is used the buffers are kept loaded. This makes following searchesin the same files a lot faster.
Note that:copen (or:lopen for:lgrep) may be used to open a buffercontaining the search results in linked form. The:silent command may beused to suppress the default full screen grep output. The ":grep!" form ofthe:grep command doesn't jump to the first match automatically. Thesecommands can be combined to create a NewGrep command:
command! -nargs=+ NewGrep execute 'silent grep! <args>' | copen 42
5.1 Using Vim's internal grep
:vim:vimgrepE682E683:vim[grep][!] /{pattern}/[g][j][f]{file} ...Search for{pattern} in the files{file} ... and setthe error list to the matches. Files matching'wildignore' are ignored; files in'suffixes' aresearched last.
{pattern} is a Vim search pattern. Instead ofenclosing it in / any non-ID character (see'isident') can be used, so long as it does notappear in{pattern}.'ignorecase' applies. To overrule it put/\c in thepattern to ignore case or/\C to match case.'smartcase' is not used.If{pattern} is empty (e.g. // is specified), the lastused search pattern is used.last-pattern
Flags:'g' Without the 'g' flag each line is added only once. With 'g' every match is added.
'j' Without the 'j' flag Vim jumps to the first match. With 'j' only the quickfix list is updated. With the [!] any changes in the current buffer are abandoned.
'f' When the 'f' flag is specified, fuzzy string matching is used to find matching lines. In this case,{pattern} is treated as a literal string instead of a regular expression. Seefuzzy-matching for more information about fuzzy matching strings.
QuickFixCmdPre andQuickFixCmdPost are triggered.A file that is opened for matching may use a buffernumber, but it is reused if possible to avoidconsuming buffer numbers.
:{count}vim[grep] ...When a number is put before the command this is usedas the maximum number of matches to find. Use":1vimgrep pattern file" to find only the first.Useful if you only want to check if there is a matchand quit quickly when it's found.
Every second or so the searched file name is displayedto give you an idea of the progress made.Examples:
:vimgrep /an error/ *.c:vimgrep /\<FileName\>/ *.h include/*:vimgrep /myfunc/ **/*.c
For the use of "**" seestarstar-wildcard.
:vim[grep][!]{pattern}{file} ...Like above, but instead of enclosing the pattern in anon-ID character use a white space separated pattern.The pattern must start with an ID character.Example:
:vimgrep Error *.c
:lv:lvimgrep:lv[imgrep][!] /{pattern}/[g][j][f]{file} ...:lv[imgrep][!]{pattern}{file} ...Same as ":vimgrep", except the location list for thecurrent window is used instead of the quickfix list.
:vimgrepa:vimgrepadd:vimgrepa[dd][!] /{pattern}/[g][j][f]{file} ...:vimgrepa[dd][!]{pattern}{file} ...Just like ":vimgrep", but instead of making a new listof errors the matches are appended to the currentlist.
:lvimgrepa:lvimgrepadd:lvimgrepa[dd][!] /{pattern}/[g][j][f]{file} ...:lvimgrepa[dd][!]{pattern}{file} ...Same as ":vimgrepadd", except the location list forthe current window is used instead of the quickfixlist.
5.2 External grep
Vim can interface with "grep" and grep-like programs (such as the GNUid-utils) in a similar way to its compiler integration (see:make above).
[Unix trivia: The name for the Unix "grep" command comes from ":g/re/p", where"re" stands for Regular Expression.]
:gr:grep:gr[ep][!] [arguments]Just like ":make", but use'grepprg' instead of'makeprg' and'grepformat' instead of'errorformat'.When'grepprg' is "internal" this works like:vimgrep. Note that the pattern needs to beenclosed in separator characters then.If the encoding of the program output differs from the'encoding' option, you can use the'makeencoding'option to specify the encoding.
:lgr:lgrep:lgr[ep][!] [arguments]Same as ":grep", except the location list for thecurrent window is used instead of the quickfix list.
:grepa:grepadd:grepa[dd][!] [arguments]Just like ":grep", but instead of making a new list oferrors the matches are appended to the current list.Example:
:call setqflist([]):bufdo grepadd! something %
The first command makes a new error list which isempty. The second command executes "grepadd" for eachlisted buffer. Note the use of ! to avoid that":grepadd" jumps to the first error, which is notallowed with:bufdo.An example that uses the argument list and avoidserrors for files without matches:
:silent argdo try  \ | grepadd! something %  \ | catch /E480:/  \ | endtry"
If the encoding of the program output differs from the'encoding' option, you can use the'makeencoding'option to specify the encoding.
:lgrepa:lgrepadd:lgrepa[dd][!] [arguments]Same as ":grepadd", except the location list for thecurrent window is used instead of the quickfix list.
5.3 Setting up external grep
If you have a standard "grep" program installed, the :grep command may workwell with the defaults. The syntax is very similar to the standard command:
:grep foo *.c
Will search all files with the .c extension for the substring "foo". Thearguments to :grep are passed straight to the "grep" program, so you can usewhatever options your "grep" supports.
By default, :grep invokes grep with the -n option (show file and linenumbers). You can change this with the'grepprg' option. You will need to set'grepprg' if:
a)You are using a program that isn't called "grep"b)You have to call grep with a full pathc)You want to pass other options automatically (e.g. case insensitivesearch.)
Once "grep" has executed, Vim parses the results using the'grepformat'option. This option works in the same way as the'errorformat' option - seethat for details. You may need to change'grepformat' from the default ifyour grep outputs in a non-standard format, or you are using some otherprogram with a special format.
Once the results are parsed, Vim loads the first file containing a match andjumps to the appropriate line, in the same way that it jumps to a compilererror inquickfix mode. You can then use the:cnext,:clist, etc.commands to see the other matches.
5.4 Using :grep with id-utils
You can set up :grep to work with the GNU id-utils like this:
:set grepprg=lid\ -Rgrep\ -s:set grepformat=%f:%l:%m
then
:grep (regexp)
works just as you'd expect.(provided you remembered to mkid first :)
5.5 Browsing source code with :vimgrep or :grep
Using the stack of error lists that Vim keeps, you can browse your files tolook for functions and the functions they call. For example, suppose that youhave to add an argument to the read_file() function. You enter this command:
:vimgrep /\<read_file\>/ *.c
You use ":cn" to go along the list of matches and add the argument. At oneplace you have to get the new argument from a higher level function msg(), andneed to change that one too. Thus you use:
:vimgrep /\<msg\>/ *.c
While changing the msg() functions, you find another function that needs toget the argument from a higher level. You can again use ":vimgrep" to findthese functions. Once you are finished with one function, you can use
:colder
to go back to the previous one.
This works like browsing a tree: ":vimgrep" goes one level deeper, creating alist of branches. ":colder" goes back to the previous level. You can mixthis use of ":vimgrep" and "colder" to browse all the locations in a tree-likeway. If you do this consistently, you will find all locations without theneed to write down a "todo" list.

6. Selecting a compilercompiler-select

:comp:compilerE666:comp[iler][!]{name}Set options to work with compiler{name}.Without the "!" options are set for thecurrent buffer. With "!" global options areset.If you use ":compiler foo" in "file.foo" andthen ":compiler! bar" in another buffer, Vimwill keep on using "foo" in "file.foo".
The Vim plugins in the "compiler" directory will set options to use theselected compiler. For:compiler local options are set, for:compiler!global options.current_compiler
To support older Vim versions, the plugins always use "current_compiler" andnot "b:current_compiler". What the command actually does is the following:
Delete the "current_compiler" and "b:current_compiler" variables.
Define the "CompilerSet" user command. With "!" it does ":set", without "!" it does ":setlocal".
Execute ":runtime! compiler/{name}.{vim,lua}". The plugins are expected to set options with "CompilerSet" and set the "current_compiler" variable to the name of the compiler.
Delete the "CompilerSet" user command.
Set "b:current_compiler" to the value of "current_compiler".
Without "!" the old value of "current_compiler" is restored.
For writing a compiler plugin, seewrite-compiler-plugin.
Use thecompiler-make plugin to undo the effect of a compiler plugin.

CPPCHECKquickfix-cppcheckcompiler-cppcheck

Use g/b:`c_cppcheck_params` to set cppcheck parameters. The globalsettings by default include
--verbose: Enables verbose output.
--force: Forces checking of all configurations.
--inline-suppr: Allows inline suppressions.
--enable=...: Enables specific checks like warnings, style, performance, portability, information, and missing includes.
-j: Utilizes multiple processors if available, determined by thegetconf command if available (requires omitting the unusedFunction check)
For C++ files (filetype == 'cpp'), the--language=c++ option is added toensure Cppcheck treats the file as C++.
If compile_commands.json is present in the current directory, it is added as a--project parameter to the command line. Otherwise, by default thedirectories in &path are passed as include directories. These can be set byg/b:`c_cppcheck_includes` as a list of-I flags. Tim Pope's vim-apathyplug-in [0] can expand &path. To also append the folders in a git repo use
let &l:path = join(systemlist('git ls-tree -d --name-only -r HEAD'), ',')
[0]https://github.com/tpope/vim-apathy

DOTNETcompiler-dotnet

The .NET CLI compiler outputs both errors and warnings by default. The outputmay be limited to include only errors, by setting the g:dotnet_errors_onlyvariable tov:true.
The associated project name is included in each error and warning. To suppressthe project name, set the g:dotnet_show_project_file variable tov:false.
Example: limit output to only display errors, and suppress the project name:
let dotnet_errors_only = v:truelet dotnet_show_project_file = v:falsecompiler dotnet

GCCquickfix-gcccompiler-gcc

There's one variable you can set for the GCC compiler:
g:compiler_gcc_ignore_unmatched_linesIgnore lines that don't match any patternsdefined for GCC. Useful if output fromcommands run from make are generating falsepositives.

JAVACcompiler-javac

Commonly used compiler options can be added to'makeprg' by setting theb/g:javac_makeprg_params variable. For example:
let g:javac_makeprg_params = "-Xlint:all -encoding utf-8"

MAVENcompiler-maven

Commonly used compiler options can be added to'makeprg' by setting theb/g:maven_makeprg_params variable. For example:
let g:maven_makeprg_params = "-DskipTests -U -X"

SPOTBUGScompiler-spotbugs

SpotBugs is a static analysis tool that can be used to find bugs in Java.It scans the Java bytecode of all classes in the currently open buffer.(Therefore,:compiler! spotbugs is not supported.)
Commonly used compiler options can be added to'makeprg' by setting the"b:" or "g:spotbugs_makeprg_params" variable. For example:
let b:spotbugs_makeprg_params = "-longBugCodes -effort:max -low"
The global default is "-workHard -experimental".
By default, the class files are searched in the directory where the sourcefiles are placed. However, typical Java projects use distinct directoriesfor source files and class files. To make both known to SpotBugs, assigntheir paths (distinct and relative to their common root directory) to thefollowing properties (using the example of a common Maven project):
let g:spotbugs_properties = {        \ 'sourceDirPath':['src/main/java'],        \ 'classDirPath':['target/classes'],        \ 'testSourceDirPath':['src/test/java'],        \ 'testClassDirPath':['target/test-classes'],\ }
Note that source and class path entries are expected to come in pairs: defineboth "sourceDirPath" and "classDirPath" when you are considering at least one,and apply the same logic to "testSourceDirPath" and "testClassDirPath".Note that values for the path keys describe only for SpotBugs where to lookfor files; refer to the documentation for particular compiler plugins for moreinformation.
The default pre- and post-compiler actions are provided for Ant, Maven, andJavac compiler plugins and can be selected by assigning the name of a compilerplugin (ant,maven, orjavac) to the "compiler" key:
let g:spotbugs_properties = {        \ 'compiler':'maven',\ }
This single setting is essentially equivalent to all the settings below, withthe exception made for the "PreCompilerAction" and "PreCompilerTestAction"values: their listedFuncrefs will obtain no-op implementations whereas theimplicit Funcrefs of the "compiler" key will obtain the requested defaults ifavailable.
let g:spotbugs_properties = {        \ 'PreCompilerAction':                \ function('spotbugs#DefaultPreCompilerAction'),        \ 'PreCompilerTestAction':                \ function('spotbugs#DefaultPreCompilerTestAction'),        \ 'PostCompilerAction':                \ function('spotbugs#DefaultPostCompilerAction'),        \ 'sourceDirPath':['src/main/java'],        \ 'classDirPath':['target/classes'],        \ 'testSourceDirPath':['src/test/java'],        \ 'testClassDirPath':['target/test-classes'],\ }
With default actions, the compiler of choice will attempt to rebuild the classfiles for the buffer (and possibly for the whole project) as soon as a Javasyntax file is loaded; then,spotbugs will attempt to analyze the quality ofthe compilation unit of the buffer.
Vim commands proficient in'makeprg' [0] can be composed with default actions.Begin by considering which of the supported keys, "DefaultPreCompilerCommand","DefaultPreCompilerTestCommand", or "DefaultPostCompilerCommand", you need towrite an implementation for, observing that each of these keys corresponds toa particular "*Action" key. Follow it by defining a new function that alwaysdeclares an only parameter of type string and puts to use a command equivalentof:make, and assigning itsFuncref to the selected key. For example:
function! GenericPostCompilerCommand(arguments) abort        execute 'make ' . a:argumentsendfunctionlet g:spotbugs_properties = {        \ 'DefaultPostCompilerCommand':                \ function('GenericPostCompilerCommand'),\ }
When "PostCompilerAction" is available, "PostCompilerActionExecutor" is alsosupported. Its value must be a Funcref pointing to a function that alwaysdeclares a single parameter of type string and decides whether:execute canbe dispatched on its argument, containing a pending post-compiler action,after ascertaining the current status of:cc (or:ll):
function! GenericPostCompilerActionExecutor(action) abort        try                cc        catch /\<E42:/                execute a:action        endtryendfunction
Complementary, some or all of the available "Pre*Action"s (or "*Pre*Command"s)may run:doautocmd java_spotbugs_post User in their implementations before:make (or its equivalent) to define a once-onlyShellCmdPost:autocmdthat will arrange for "PostCompilerActionExecutor" to be invoked; and then run:doautocmd java_spotbugs_post ShellCmdPost to consume this event:
function! GenericPreCompilerCommand(arguments) abort        if !exists('g:spotbugs_compilation_done')                doautocmd java_spotbugs_post User                execute 'make ' . a:arguments                " only run doautocmd when :make was synchronous                " see note below                doautocmd java_spotbugs_post ShellCmdPost " XXX: (a)                let g:spotbugs_compilation_done = 1        else                cc        endifendfunctionfunction! GenericPreCompilerTestCommand(arguments) abort        if !exists('g:spotbugs_test_compilation_done')                doautocmd java_spotbugs_post User                execute 'make ' . a:arguments                " only run doautocmd when :make was synchronous                " see note below                doautocmd java_spotbugs_post ShellCmdPost " XXX: (b)                let g:spotbugs_test_compilation_done = 1        else                cc        endifendfunctionlet g:spotbugs_properties = {        \ 'compiler':'maven',        \ 'DefaultPreCompilerCommand':                \ function('GenericPreCompilerCommand'),        \ 'DefaultPreCompilerTestCommand':                \ function('GenericPreCompilerTestCommand'),        \ 'PostCompilerActionExecutor':                \ function('GenericPostCompilerActionExecutor'),\ }
If a command equivalent of:make is capable of asynchronous execution andconsumingShellCmdPost events,:doautocmd java_spotbugs_post ShellCmdPostmust be removed from such "*Action" (or "*Command") implementations (i.e. thelines(a) and(b) in the listed examples) to retain a sequential order fornon-blocking execution, and any notification (see below) must be suppressed.AShellCmdPost:autocmd can be associated with any:augroup by assigningits name to the "augroupForPostCompilerAction" key.
When default actions are not suited to a desired workflow, proceed by writingarbitrary functions yourself and matching their Funcrefs to the supportedkeys: "PreCompilerAction", "PreCompilerTestAction", and "PostCompilerAction".
The next example re-implements the default pre-compiler actions for a Mavenproject and requests other default Maven settings with the "compiler" entry:
function! MavenPreCompilerAction() abort        call spotbugs#DeleteClassFiles()        compiler maven        make compile        ccendfunctionfunction! MavenPreCompilerTestAction() abort        call spotbugs#DeleteClassFiles()        compiler maven        make test-compile        ccendfunctionlet g:spotbugs_properties = {        \ 'compiler':'maven',        \ 'PreCompilerAction':                \ function('MavenPreCompilerAction'),        \ 'PreCompilerTestAction':                \ function('MavenPreCompilerTestAction'),\ }
Note that all entered custom settings will take precedence over the matchingdefault settings in "g:spotbugs_properties".Note that it is necessary to notify the plugin of the result of a pre-compileraction before further work can be undertaken. Using:cc after:make (or:ll after:lmake) as the last command of an action is the supported meansof such communication.
Two commands, "SpotBugsRemoveBufferAutocmd" and "SpotBugsDefineBufferAutocmd",are provided to toggle actions for buffer-local autocommands. For example, toalso run actions on anyBufWritePost andSignal event, add these lines to~/.config/nvim/after/ftplugin/java.vim:
if exists(':SpotBugsDefineBufferAutocmd') == 2        SpotBugsDefineBufferAutocmd BufWritePost Signalendif
Otherwise, you can turn to:doautocmd java_spotbugs User at any time.
The "g:spotbugs_properties" variable is consulted by the Java filetype plugin(ft-java-plugin) to arrange for the described automation, and, therefore, itmust be defined beforeFileType events can take place for the buffers loadedwith Java source files. It could, for example, be set in a project-localvimrc loaded by [1].
Both "g:spotbugs_properties" and "b:spotbugs_properties" are recognized andmust be modifiable (:unlockvar). The "*Command" entries are always treatedas global functions to be shared among all Java buffers.
The SpotBugs Java library and, by extension, its distributed shell scripts donot support in the-textui mode listed pathnames with directory filenamesthat contain blank characters [2]. To work around this limitation, considermaking a symbolic link to such a directory from a directory that does not haveblank characters in its name and passing this information to SpotBugs:
let g:spotbugs_alternative_path = {        \ 'fromPath':'path/to/dir_without_blanks',        \ 'toPath':'path/to/dir with blanks',\ }
[0]https://github.com/Konfekt/vim-compilers[1]https://github.com/MarcWeber/vim-addon-local-vimrc[2]https://github.com/spotbugs/spotbugs/issues/909

GNU MAKEcompiler-make

Since the default make program is "make", the compiler plugin for make,:compiler make, will reset the'makeprg' and'errorformat' option tothe default values and unlet any variables that may have been set by aprevious compiler plugin.

GROFFquickfix-groffcompiler-groff

The GROFF compiler plugin uses the mom macro set (documented in the groff_mommanpage) as input and expects that the output file type extension is passed tomake, say :make html or :make pdf.
Additional arguments can be passed to groff by setting them inb:groff_compiler_args org:groff_compiler_args. Thelanguage argumentpassed to groff is set using'spelllang'; it can be overridden by settingb:groff_compiler_lang. The default encoding isUTF-8 and can be changedby settingb:groff_compiler_encoding org:groff_compiler_encoding.

PANDOCquickfix-pandoccompiler-pandoc

The Pandoc compiler plugin expects that an output file type extension ispassed to make, say :make html or :make pdf.
Additional arguments can be passed to pandoc:
either by appending them to make, say:make html --self-contained .
or setting them inb:pandoc_compiler_args org:pandoc_compiler_args.
The--from argument is an educated guess using the buffer file type;it can be overridden by settingb:pandoc_compiler_from.The--metadata lang argument is set using'spelllang';If--from=markdown is assumed and no title set in a title header orYAML block, then the filename (without extension) is used as the title.

PERLquickfix-perlcompiler-perl

The Perl compiler plugin doesn't actually compile, but invokes Perl's internalsyntax checking feature and parses the output for possible errors so you cancorrect them in quick-fix mode.
Warnings are forced regardless of "no warnings" or "$^W = 0" within the filebeing checked. To disable this set g:perl_compiler_force_warnings to a zerovalue. For example:
let g:perl_compiler_force_warnings = 0

MYPY TYPE CHECKERcompiler-mypy

Commonly used compiler options can be added to'makeprg' by setting theb/g:mypy_makeprg_params variable. For example:
let b:mypy_makeprg_params = "--warn-unused-ignores"
The global default is "--strict --ignore-missing-imports".

RUFF LINTERcompiler-ruff

Commonly used compiler options can be added to'makeprg' by setting theb/g:ruff_makeprg_params variable. For example:
let b:ruff_makeprg_params = "--max-line-length "..&textwidth
The global default is "--preview".

PYLINT LINTERcompiler-pylint

Commonly used compiler options can be added to'makeprg' by setting theb/g:pylint_makeprg_params variable. For example:
let b:pylint_makeprg_params = "--max-line-length "..&textwidth
The global default is "--jobs=0" to use (almost) all cores.

PYUNIT COMPILERcompiler-pyunit

This is not actually a compiler, but a unit testing framework for thePython language. It is included into standard Python distributionstarting from version 2.0. For older versions, you can get it fromhttps://pyunit.sourceforge.net.
When you run your tests with the help of the framework, possible errorsare parsed by Vim and presented for you in quick-fix mode.
Unfortunately, there is no standard way to run the tests.The alltests.py script seems to be used quite often, that's all.Useful values for the'makeprg' options therefore are: setlocal makeprg=./alltests.py " Run a testsuite setlocal makeprg=python\ %:S " Run a single testcase

PYTEST COMPILERcompiler-pytest

Commonly used compiler options can be added to'makeprg' by setting theb/g:pytest_makeprg_params variable. For example:
let b:pytest_makeprg_params = "--verbose --no-summary --disable-warnings"
The global default is "--tb=short --quiet"; Python warnings are suppressed.

TEX COMPILERcompiler-tex

Included in the distribution compiler for TeX ($VIMRUNTIME/compiler/tex.vim)uses make command if possible. If the compiler finds a file named "Makefile"or "makefile" in the current directory, it supposes that you want to processyour*TeX files with make, and the makefile does the right work. In this casecompiler sets'errorformat' for*TeX output and leaves'makeprg' untouched. Ifneither "Makefile" nor "makefile" is found, the compiler will not use make.You can force the compiler to ignore makefiles by definingb:tex_ignore_makefile or g:tex_ignore_makefile variable (they are checked forexistence only).
If the compiler chose not to use make, it needs to choose a right program forprocessing your input. If b:tex_flavor or g:tex_flavor (in this precedence)variable exists, it defines TeX flavor for :make (actually, this is the nameof executed command), and if both variables do not exist, it defaults to"latex". For example, while editing chapter2.tex \input-ed from mypaper.texwritten in AMS-TeX:
:let b:tex_flavor = 'amstex':compiler tex
[editing...]
:make mypaper
Note that you must specify a name of the file to process as an argument (toprocess the right file when editing \input-ed or \include-ed file; portablesolution for substituting % for no arguments is welcome). This is not in thesemantics of make, where you specify a target, not source, but you may specifyfilename without extension ".tex" and mean this as "make filename.dvi orfilename.pdf or filename.some_result_extension according to compiler".
Note: tex command line syntax is set to usable both for MikTeX (suggestionby Srinath Avadhanula) and teTeX (checked by Artem Chuprina). Suggestionfromerrorformat-LaTeX is too complex to keep it working for differentshells and OSes and also does not allow to use other available TeX options,if any. If your TeX doesn't support "-interaction=nonstopmode", pleasereport it with different means to express \nonstopmode from the command line.

TSC COMPILERcompiler-tsc

The executable and compiler options can be added to'makeprg' by setting theb/g:tsc_makeprg variable. For example:
let b:tsc_makeprg = "npx tsc --noEmit"

TYPST COMPILERcompiler-typst

Vim includes a compiler plugin for Typst files. This compiler is enabledautomatically in Typst buffers by the Typst filetype pluginft-typst-plugin.Run:make to compile the current Typst file.
g:typst_cmd
By default Vim will use "typst" as the command to run the Typst compiler. Thiscan be changed by setting theg:typst_cmd variable:
let g:typst_cmd = "/path/to/other/command"

7. The error formaterror-file-format

errorformatE372E373E374E375E376E377E378The'errorformat' option specifies a list of formats that are recognized. Thefirst format that matches with an error message is used. You can add severalformats for different messages your compiler produces, or even entries formultiple compilers. Seeefm-entries.
Each entry in'errorformat' is a scanf-like string that describes the format.First, you need to know how scanf works. Look in the documentation of yourC compiler. Below you find the % items that Vim understands. Others areinvalid.
Special characters in'errorformat' are comma and backslash. Seeefm-entries for how to deal with them. Note that a literal "%" is matchedby "%%", thus it is not escaped with a backslash.Keep in mind that in the:make and:grep output all NUL characters arereplaced with SOH (0x01).
Note: By default the difference between upper and lowercase is ignored. Ifyou want to match case, add "\C" to the pattern/\C.
Vim will read lines of any length, but only the first 4095 bytes are used, therest is ignored. Items can only be 1023 bytes long.
Basic items
%ffile name (finds a string)%bbuffer number (finds a number)%omodule name (finds a string)%lline number (finds a number)%eend line number (finds a number)%ccolumn number (finds a number representing charactercolumn of the error, byte index, a<tab> is 1character column)%vvirtual column number (finds a number representingscreen column of the error (1<tab> == 8 screencolumns))%kend column number (finds a number representingthe character column of the error, byte index, or anumber representing screen end column of the error ifit's used with %v)%terror type (finds a single character): e - error message w - warning message i - info message n - note message%nerror number (finds a number)%merror message (finds a string)%rmatches the "rest" of a single-line file message %O/P/Q%ppointer line (finds a sequence of '-', '.', ' ' ortabs and uses the length for the column number)%*{conv}any scanf non-assignable conversion%%the single '%' character%ssearch text (finds a string)
The "%f" conversion may depend on the current'isfname' setting. "~/" isexpanded to the home directory and environment variables are expanded.
The "%f" and "%m" conversions have to detect the end of the string. Thisnormally happens by matching following characters and items. When nothing isfollowing the rest of the line is matched. If "%f" is followed by a '%' or abackslash, it will look for a sequence of'isfname' characters.
On Windows a leading "C:" will be included in "%f", even when using "%f:".This means that a file name which is a single alphabetical letter will not bedetected.
The "%b" conversion is used to parse a buffer number. This is useful forreferring to lines in a scratch buffer or a buffer with no name. If a bufferwith the matching number doesn't exist, then that line is used as a non-errorline.
The "%p" conversion is normally followed by a "^". It's used for compilersthat output a line like:
^
or
---------^
to indicate the column of the error. This is to be used in a multi-line errormessage. Seeerrorformat-javac for a useful example.
The "%s" conversion specifies the text to search for, to locate the error line.The text is used as a literal string. The anchors "^" and "$" are added tothe text to locate the error line exactly matching the search text and thetext is prefixed with the "\V" atom to make it "very nomagic". The "%s"conversion can be used to locate lines without a line number in the erroroutput. Like the output of the "grep" shell command.When the pattern is present the line number will not be used.
The "%o" conversion specifies the module name in quickfix entry. If presentit will be used in quickfix error window instead of the filename. The modulename is used only for displaying purposes, the file name is used when jumpingto the file.
Changing directory
The following uppercase conversion characters specify the type of specialformat strings. At most one of them may be given as a prefix at the beginningof a single comma-separated format pattern.Some compilers produce messages that consist of directory names that have tobe prepended to each file name read by %f (example: GNU make). The followingcodes can be used to scan these directory names; they will be stored in aninternal directory stack.E379
%D"enter directory" format string; expects a following %f that finds the directory name%X"leave directory" format string; expects following %f
When defining an "enter directory" or "leave directory" format, the "%D" or"%X" has to be given at the start of that substring. Vim tracks the directorychanges and prepends the current directory to each erroneous file found with arelative path. Seequickfix-directory-stack for details, tips andlimitations.
Multi-line messageserrorformat-multi-line
It is possible to read the output of programs that produce multi-linemessages, i.e. error strings that consume more than one line. Possibleprefixes are:%Estart of a multi-line error message%Wstart of a multi-line warning message%Istart of a multi-line informational message%Nstart of a multi-line note message%Astart of a multi-line message (unspecified type)%>for next line start with current pattern againefm-%>%Ccontinuation of a multi-line message%Zend of a multi-line messageThese can be used with '+' and '-', seeefm-ignore below.
Using "\n" in the pattern won't work to match multi-line messages.
Example: Your compiler happens to write out errors in the following format(leading line numbers not being part of the actual output):
1Error 275
2line 42
3column 3
4' ' expected after '--'
The appropriate error format string has to look like this:
:set efm=%EError\ %n,%Cline\ %l,%Ccolumn\ %c,%Z%m
And the:clist error message generated for this error is:
1:42 col 3 error 275: ' ' expected after '--'
Another example: Think of a Python interpreter that produces the followingerror message (line numbers are not part of the actual output):
1============================================================== 2FAIL: testGetTypeIdCachesResult (dbfacadeTest.DjsDBFacadeTest) 3-------------------------------------------------------------- 4Traceback (most recent call last): 5 File "unittests/dbfacadeTest.py", line 89, in testFoo 6 self.assertEquals(34, dtid) 7 File "/usr/lib/python3.8/unittest.py", line 286, in 8 failUnlessEqual 9 raise self.failureException, \ 10AssertionError: 34 != 33 11 12-------------------------------------------------------------- 13Ran 27 tests in 0.063s
Say you want:clist write the relevant information of this message only,namely: 5 unittests/dbfacadeTest.py:89: AssertionError: 34 != 33
Then the error format string could be defined as follows:
:set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m
Note that the %C string is given before the %A here: since the expression' %.%#' (which stands for the regular expression ' .*') matches every linestarting with a space, followed by any characters to the end of the line,it also hides line 7 which would trigger a separate error message otherwise.Error format strings are always parsed pattern by pattern until the firstmatch occurs.efm-%>
The %> item can be used to avoid trying patterns that appear earlier in'errorformat'. This is useful for patterns that match just about anything.For example, if the error looks like this:
Error in line 123 of foo.c:
unknown variable "i"
This can be found with:
:set efm=xxx,%E%>Error in line %l of %f:,%Z%m
Where "xxx" has a pattern that would also match the second line.
Important: There is no memory of what part of the errorformat matched before;every line in the error file gets a complete new run through the error formatlines. For example, if one has:
setlocal efm=aa,bb,cc,dd,ee
Where aa, bb, etc. are error format strings. Each line of the error file willbe matched to the pattern aa, then bb, then cc, etc. Just because cc matchedthe previous error line does _not_ mean that dd will be tried first on thecurrent line, even if cc and dd are multi-line errorformat strings.
Separate file nameerrorformat-separate-filename
These prefixes are useful if the file name is given once and multiple messagesfollow that refer to this file name.%Osingle-line file message: overread the matched part%Psingle-line file message: push file %f onto the stack%Qsingle-line file message: pop the last file from stack
Example: Given a compiler that produces the following error logfile (withoutleading line numbers):
1[a1.tt] 2(1,17) error: ';' missing 3(21,2) warning: variable 'z' not defined 4(67,3) error: end of file found before string ended 5 6[a2.tt] 7 8[a3.tt] 9NEW compiler v1.1 10(2,2) warning: variable 'x' not defined 11(67,3) warning: 's' already defined
This logfile lists several messages for each file enclosed in [...] which areproperly parsed by an error format like this:
:set efm=%+P[%f],(%l\\,%c)%*[\ ]%t%*[^:]:\ %m,%-Q
A call of:clist writes them accordingly with their correct filenames:
2 a1.tt:1 col 17 error: ';' missing 3 a1.tt:21 col 2 warning: variable 'z' not defined 4 a1.tt:67 col 3 error: end of file found before string ended 8 a3.tt:2 col 2 warning: variable 'x' not defined 9 a3.tt:67 col 3 warning: 's' already defined
Unlike the other prefixes that all match against whole lines, %P, %Q and %Ocan be used to match several patterns in the same line. Thus it is possibleto parse even nested files like in the following line:
{"file1" {"file2" error1} error2 {"file3" error3 {"file4" error4 error5}}}
The %O then parses over strings that do not contain any push/pop file nameinformation. Seeerrorformat-LaTeX for an extended example.
Ignoring and using whole messagesefm-ignore
The codes '+' or '-' can be combined with the uppercase codes above; in thatcase they have to precede the letter, e.g. '%+A' or '%-G':%-do not include the matching multi-line in any output%+include the whole matching line in the %m error string
One prefix is only useful in combination with '+' or '-', namely %G. It parsesover lines containing general information like compiler version strings orother headers that can be skipped.%-Gignore this message%+Ggeneral message
Pattern matching
The scanf()-like "%*[]" notation is supported for backward-compatibilitywith previous versions of Vim. However, it is also possible to specify(nearly) any Vim supported regular expression in format strings.Since meta characters of the regular expression language can be part ofordinary matching strings or file names (and therefore internally have tobe escaped), meta symbols have to be written with leading '%':%\The single '\' character. Note that this has to beescaped ("%\\") in ":set errorformat=" definitions.%.The single '.' character.%#The single "*"(!) character.%^The single '^' character. Note that this is notuseful, the pattern already matches start of line.%$The single '$' character. Note that this is notuseful, the pattern already matches end of line.%[The single '[' character for a [] character range.%~The single '~' character.When using character classes in expressions (see/\i for an overview),terms containing the "\+" quantifier can be written in the scanf() "%*"notation. Example: "%\\d%\\+" ("\d\+", "any number") is equivalent to "%*\\d".Important note: The \(...\) grouping of sub-matches can not be used in formatspecifications because it is reserved for internal conversions.
Multiple entries in'errorformat'efm-entries
To be able to detect output from several compilers, several format patternsmay be put in'errorformat', separated by commas (note: blanks after the commaare ignored). The first pattern that has a complete match is used. If nomatch is found, matching parts from the last one will be used, although thefile name is removed and the error message is set to the whole message. Ifthere is a pattern that may match output from several compilers (but not in aright way), put it after one that is more restrictive.
To include a comma in a pattern precede it with a backslash (you have to typetwo in a ":set" command). To include a backslash itself give two backslashes(you have to type four in a ":set" command). You also need to put a backslashbefore a space for ":set".
Valid matchesquickfix-valid
If a line does not completely match one of the entries in'errorformat', thewhole line is put in the error message and the entry is marked "not valid"These lines are skipped with the ":cn" and ":cp" commands (unless there isno valid line at all). You can use ":cl!" to display all the error messages.
If the error format does not contain a file name Vim cannot switch to thecorrect file. You will have to do this by hand.
For example, the format of the output from the Amiga Aztec compiler is:
filename>linenumber:columnnumber:errortype:errornumber:errormessage
filenamename of the file in which the error was detectedlinenumberline number where the error was detectedcolumnnumbercolumn number where the error was detectederrortypetype of the error, normally a single 'E' or 'W'errornumbernumber of the error (for lookup in the manual)errormessagedescription of the error
This can be matched with this'errorformat' entry:%f>%l:%c:%t:%n:%m
Some examples for C compilers that produce single-line error outputs:%f:%l:\ %t%*[^0123456789]%n:\ %mfor Manx/Aztec C error messages(scanf() doesn't understand [0-9])%f\ %l\ %t%*[^0-9]%n:\ %mfor SAS C\"%f\"\\,%*[^0-9]%l:\ %mfor generic C compilers%f:%l:\ %mfor GCC%f:%l:\ %m,%Dgmake[%*\\d]:\ Entering\ directory\%f',%Dgmake[%*\\d]:\ Leaving\ directory\%f'for GCC with gmake (concat the lines!)%f(%l)\ :\ %*[^:]:\ %mold SCO C compiler (pre-OS5)%f(%l)\ :\ %t%*[^0-9]%n:\ %midem, with error type and number%f:%l:\ %m,In\ file\ included\ from\ %f:%l:,\^I\^Ifrom\ %f:%l%mfor GCC, with some extras
Extended examples for the handling of multi-line messages are given below,seeerrorformat-Jikes anderrorformat-LaTeX.
Note the backslash in front of a space and double quote. It is required forthe :set command. There are two backslashes in front of a comma, one for the:set command and one to avoid recognizing the comma as a separator of errorformats.
Filtering messages
If you have a compiler that produces error messages that do not fit in theformat string, you could write a program that translates the error messagesinto this format. You can use this program with the ":make" command bychanging the'makeprg' option. For example:
:set mp=make\ \\\|&\ error_filter
The backslashes before the pipe character are required to avoid it to berecognized as a command separator. The backslash before each space isrequired for the set command.

8. The directory stackquickfix-directory-stack

Quickfix maintains a stack for saving all used directories parsed from themake output. For GNU-make this is rather simple, as it always prints theabsolute path of all directories it enters and leaves. Regardless if this isdone via a'cd' command in the makefile or with the parameter "-C dir" (changeto directory before reading the makefile). It may be useful to use the switch"-w" to force GNU-make to print out the working directory before and afterprocessing.
Maintaining the correct directory is more complicated if you don't useGNU-make. AIX-make for example doesn't print any information about itsworking directory. Then you need to enhance the makefile. In the makefile ofLessTif there is a command which echoes "Making{target} in{dir}". Thespecial problem here is that it doesn't print information on leaving thedirectory and that it doesn't print the absolute path.
To solve the problem with relative paths and missing "leave directory"messages Vim uses the following algorithm:
1) Check if the given directory is a subdirectory of the current directory. If this is true, store it as the current directory.2) If it is not a subdir of the current directory, try if this is a subdirectory of one of the upper directories.3) If the directory still isn't found, it is assumed to be a subdirectory of Vim's current directory.
Additionally it is checked for every file, if it really exists in theidentified directory. If not, it is searched in all other directories of thedirectory stack (NOT the directory subtree!). If it is still not found, it isassumed that it is in Vim's current directory.
There are limitations in this algorithm. These examples assume that make justprints information about entering a directory in the form "Making all in dir".
1) Assume you have following directories and files: ./dir1 ./dir1/file1.c ./file1.c
If make processes the directory "./dir1" before the current directory and there is an error in the file "./file1.c", you will end up with the file "./dir1/file.c" loaded by Vim.
This can only be solved with a "leave directory" message.
2) Assume you have following directories and files: ./dir1 ./dir1/dir2 ./dir2
You get the following:
Make output Directory interpreted by Vim ------------------------ ---------------------------- Making all in dir1 ./dir1 Making all in dir2 ./dir1/dir2 Making all in dir2 ./dir1/dir2
This can be solved by printing absolute directories in the "enter directory" message or by printing "leave directory" messages.
To avoid this problem, ensure to print absolute directory names and "leavedirectory" messages.
Examples for Makefiles:
Unix: libs: for dn in $(LIBDIRS); do\(cd $$dn; echo "Entering dir '$$(pwd)'"; make); \echo "Leaving dir";\ done
Add %DEntering\ dir\ '%f',%XLeaving\ dirto your'errorformat' to handle the above output.
Note that Vim doesn't check if the directory name in a "leave directory"messages is the current directory. This is why you could just use the message"Leaving dir".

9. Specific error file formatserrorformats

errorformat-Jikes
Jikes(TM), a source-to-bytecode Java compiler published by IBM Research,produces simple multi-line error messages.
An'errorformat' string matching the produced messages is shown below.The following lines can be placed in the user'sinit.vim to overwrite Vim'srecognized default formats, or see:set+= how to install this formatadditionally to the default.
:set efm=%A%f:%l:%c:%*\\d:%*\\d:,      \%C%*\\s%trror:%m,      \%+C%*[^:]%trror:%m,      \%C%*\\s%tarning:%m,      \%C%m
Jikes(TM) produces a single-line error message when invoked with the option"+E", and can be matched with the following:
:setl efm=%f:%l:%v:%*\\d:%*\\d:%*\\s%m
errorformat-javac
This'errorformat' has been reported to work well for javac, which outputs aline with "^" to indicate the column of the error:
:setl efm=%A%f:%l:\ %m,%-Z%p^,%-C%.%#
or:
:setl efm=%A%f:%l:\ %m,%+Z%p^,%+C%.%#,%-G%.%#
Here is an alternative from Michael F. Lamb for Unix that filters the errorsfirst:
:setl errorformat=%Z%f:%l:\ %m,%A%p^,%-G%*[^sl]%.%#:setl makeprg=javac\ %:S\ 2>&1\ \\\|\ vim-javac-filter
You need to put the following in "vim-javac-filter" somewhere in your path(e.g., in ~/bin) and make it executable:
#!/bin/sed -f/\^$/s/\t/\ /g;/:[0-9]\+:/{h;d};/^[ \t]*\^/G;
In English, that sed script:
Changes single tabs to single spaces and
Moves the line with the filename, line number, error message to just after the pointer line. That way, the unused error text between doesn't break vim's notion of a "multi-line message" and also doesn't force us to include it as a "continuation of a multi-line message."
errorformat-ant
For ant (https://jakarta.apache.org/) the above errorformat has to be modifiedto honour the leading [javac] in front of each javac output line:
:set efm=%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%#
The'errorformat' can also be configured to handle ant together with eitherjavac or jikes. If you're using jikes, you should tell ant to use jikes' +Ecommand line switch which forces jikes to generate one-line error messages.This is what the second line (of a build.xml file) below does:
<property name = "build.compiler"       value = "jikes"/><property name = "build.compiler.emacs" value = "true"/>
The'errorformat' which handles ant with both javac and jikes is:
:set efm=\ %#[javac]\ %#%f:%l:%c:%*\\d:%*\\d:\ %t%[%^:]%#:%m,         \%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%#
errorformat-jade
parsing jade (seehttp://www.jclark.com/) errors is simple:
:set efm=jade:%f:%l:%c:%t:%m
errorformat-LaTeX
The following is an example how an'errorformat' string can be specifiedfor the (La)TeX typesetting system which displays error messages overmultiple lines. The output of ":clist" and ":cc" etc. commands displaysmulti-lines in a single line, leading white space is removed.It should be easy to adopt the above LaTeX errorformat to any compiler outputconsisting of multi-line errors.
The commands can be placed in avimrc file or some other Vim script file,e.g. a script containing LaTeX related stuff which is loaded only when editingLaTeX sources.Make sure to copy all lines of the example (in the given order), afterwardsremove the comment lines. For the '\' notation at the start of some lines seeline-continuation.
First prepare'makeprg' such that LaTeX will report multipleerrors; do not stop when the first error has occurred:
:set makeprg=latex\ \\\\nonstopmode\ \\\\input\\{$*}
Start of multi-line error messages:
:set efm=%E!\ LaTeX\ %trror:\ %m,       \%E!\ %m,
Start of multi-line warning messages; the first two alsoinclude the line number. Meaning of some regular expressions:
"%.%#" (".*") matches a (possibly empty) string
"%*\\d" ("\d\+") matches a number
\%+WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%#,\%+W%.%#\ at\ lines\ %l--%*\\d,\%WLaTeX\ %.%#Warning:\ %m,
Possible continuations of error/warning messages; the firstone also includes the line number:
\%Cl.%l\ %m,\%+C\ \ %m.,\%+C%.%#-%.%#,\%+C%.%#[]%.%#,\%+C[]%.%#,\%+C%.%#%[{}\\]%.%#,\%+C<%.%#>%.%#,\%C\ \ %m,
Lines that match the following patterns do not contain anyimportant information; do not include them in messages:
\%-GSee\ the\ LaTeX%m,\%-GType\ \ H\ <return>%m,\%-G\ ...%.%#,\%-G%.%#\ (C)\ %.%#,\%-G(see\ the\ transcript%.%#),
Generally exclude any empty or whitespace-only line frombeing displayed:
\%-G\\s%#,
The LaTeX output log does not specify the names of erroneoussource files per line; rather they are given globally,enclosed in parentheses.The following patterns try to match these names and storethem in an internal stack. The patterns possibly scan overthe same input line (one after another), the trailing "%r"conversion indicates the "rest" of the line that will beparsed in the next go until the end of line is reached.
Overread a file name enclosed in '('...')'; do not push iton a stack since the file apparently does not contain anyerror:
\%+O(%f)%r,
Push a file name onto the stack. The name is given after '(':
\%+P(%f%r,\%+P\ %\\=(%f%r,\%+P%*[^()](%f%r,\%+P[%\\d%[^()]%#(%f%r,
Pop the last stored file name when a ')' is scanned:
\%+Q)%r,\%+Q%*[^()])%r,\%+Q[%\\d%*[^()])%r
Note that in some cases file names in the LaTeX output log cannot be parsedproperly. The parser might have been messed up by unbalanced parenthesesthen. The above example tries to catch the most relevant cases only.You can customize the given setting to suit your own purposes, for example,all the annoying "Overfull ..." warnings could be excluded from beingrecognized as an error.Alternatively to filtering the LaTeX compiler output, it is also possibleto directly read the*.log file that is produced by the [La]TeX compiler.This contains even more useful information about possible error causes.However, to properly parse such a complex file, an external filter shouldbe used. See the description further above how to make such a filter knownby Vim.

10. Customizing the quickfix windowquickfix-window-function

The default format for the lines displayed in the quickfix window and locationlist window is:
<filename>|<lnum> col <col>|<text>
The values displayed in each line correspond to the "bufnr", "lnum", "col" and"text" fields returned by thegetqflist() function.
For some quickfix/location lists, the displayed text needs to be customized.For example, if only the filename is present for a quickfix entry, then thetwo "|" field separator characters after the filename are not needed. Anotheruse case is to customize the path displayed for a filename. By default, thecomplete path (which may be too long) is displayed for files which are notunder the current directory tree. The file path may need to be simplified to acommon parent directory.
The displayed text can be customized by setting the'quickfixtextfunc' optionto a Vim function. This function will be called with a dict argument andshould return a List of strings to be displayed in the quickfix or locationlist window. The dict argument will have the following fields:
quickfixset to 1 when called for a quickfix list and 0 when called fora location list. winidfor a location list, set to the id of the window with thelocation list. For a quickfix list, set to 0. Can be used ingetloclist() to get the location list entry. idquickfix or location list identifier start_idxindex of the first entry for which text should be returned end_idxindex of the last entry for which text should be returned
The function should return a single line of text to display in the quickfixwindow for each entry from start_idx to end_idx. The function can obtaininformation about the entries using thegetqflist() function and specifyingthe quickfix list identifier "id". For a location list, getloclist() functioncan be used with the "winid" argument. If an empty list is returned, then thedefault format is used to display all the entries. If an item in the returnedlist is an empty string, then the default format is used to display thecorresponding entry.
If a quickfix or location list specific customization is needed, then the'quickfixtextfunc' attribute of the list can be set using thesetqflist() orsetloclist() function. This overrides the global'quickfixtextfunc' option.
The example below displays the list of old files (v:oldfiles) in a quickfixwindow. As there is no line, column number and error text informationassociated with each entry, the'quickfixtextfunc' function returns only thefilename.Example:
" create a quickfix list from v:oldfilescall setqflist([], ' ', {'lines' : v:oldfiles, 'efm' : '%f',                                    \ 'quickfixtextfunc' : 'QfOldFiles'})func QfOldFiles(info)    " get information about a range of quickfix entries    let items = getqflist({'id' : a:info.id, 'items' : 1}).items    let l = []    for idx in range(a:info.start_idx - 1, a:info.end_idx - 1)        " use the simplified file name      call add(l, fnamemodify(bufname(items[idx].bufnr), ':p:.'))    endfor    return lendfunc
Main
Commands index
Quick reference

1. Using QuickFix commands
2. The error window
3. Using more than one list of errors
4. Using :make
5. Using :vimgrep and :grep
6. Selecting a compiler
CPPCHECK
DOTNET
GCC
JAVAC
MAVEN
SPOTBUGS
GNU MAKE
GROFF
PANDOC
PERL
MYPY TYPE CHECKER
RUFF LINTER
PYLINT LINTER
PYUNIT COMPILER
PYTEST COMPILER
TEX COMPILER
TSC COMPILER
TYPST COMPILER
7. The error format
8. The directory stack
9. Specific error file formats
10. Customizing the quickfix window

[8]ページ先頭

©2009-2025 Movatter.jp