diff options
53 files changed, 1795 insertions, 1079 deletions
diff --git a/runtime/autoload/netrw.vim b/runtime/autoload/netrw.vim index a4d6c41b78..fb551ac675 100644 --- a/runtime/autoload/netrw.vim +++ b/runtime/autoload/netrw.vim @@ -2074,9 +2074,9 @@ fun! netrw#NetRead(mode,...) let wholechoice = wholechoice . " " . choice let ichoice = ichoice + 1 if ichoice > a:0 - if !exists("g:netrw_quiet") - call netrw#ErrorMsg(s:ERROR,"Unbalanced string in filename '". wholechoice ."'",3) - endif + if !exists("g:netrw_quiet") + call netrw#ErrorMsg(s:ERROR,"Unbalanced string in filename '". wholechoice ."'",3) + endif " call Dret("netrw#NetRead :2 getcwd<".getcwd().">") return endif @@ -2497,9 +2497,9 @@ fun! netrw#NetWrite(...) range let wholechoice= wholechoice . " " . choice let ichoice = ichoice + 1 if choice > a:0 - if !exists("g:netrw_quiet") - call netrw#ErrorMsg(s:ERROR,"Unbalanced string in filename '". wholechoice ."'",13) - endif + if !exists("g:netrw_quiet") + call netrw#ErrorMsg(s:ERROR,"Unbalanced string in filename '". wholechoice ."'",13) + endif " call Dret("netrw#NetWrite") return endif @@ -4956,12 +4956,12 @@ fun! s:NetrwBrowseChgDir(islocal,newdir,...) if g:netrw_chgwin >= 1 " call Decho("edit-a-file: changing window to #".g:netrw_chgwin.": (due to g:netrw_chgwin)",'~'.expand("<slnum>")) if winnr("$")+1 == g:netrw_chgwin - " if g:netrw_chgwin is set to one more than the last window, then - " vertically split the last window to make that window available. - let curwin= winnr() - exe "NetrwKeepj keepalt ".winnr("$")."wincmd w" - vs - exe "NetrwKeepj keepalt ".g:netrw_chgwin."wincmd ".curwin + " if g:netrw_chgwin is set to one more than the last window, then + " vertically split the last window to make that window available. + let curwin= winnr() + exe "NetrwKeepj keepalt ".winnr("$")."wincmd w" + vs + exe "NetrwKeepj keepalt ".g:netrw_chgwin."wincmd ".curwin endif exe "NetrwKeepj keepalt ".g:netrw_chgwin."wincmd w" endif @@ -6070,7 +6070,7 @@ fun! s:NetrwServerEdit(islocal,fname) " used something like <cr>. " call Decho("user must have closed server AND did not use ctrl-r",'~'.expand("<slnum>")) if exists("g:netrw_browse_split") - unlet g:netrw_browse_split + unlet g:netrw_browse_split endif let g:netrw_browse_split= 0 if exists("s:netrw_browse_split_".winnr()) @@ -6104,7 +6104,7 @@ fun! s:NetrwServerEdit(islocal,fname) if !ctrlr " call Decho("server<".g:netrw_servername."> not available and ctrl-r not used",'~'.expand("<slnum>")) if exists("g:netrw_browse_split") - unlet g:netrw_browse_split + unlet g:netrw_browse_split endif let g:netrw_browse_split= 0 call s:NetrwBrowse(islocal,s:NetrwBrowseChgDir(islocal,a:fname)) @@ -7446,7 +7446,7 @@ fun! s:NetrwMarkFileExe(islocal,enbloc) for fname in s:netrwmarkfilelist_{curbufnr} if a:islocal if g:netrw_keepdir - let fname= s:ShellEscape(netrw#WinPath(s:ComposePath(curdir,fname))) + let fname= s:ShellEscape(netrw#WinPath(s:ComposePath(curdir,fname))) endif else let fname= s:ShellEscape(netrw#WinPath(b:netrw_curdir.fname)) @@ -10575,7 +10575,7 @@ fun! s:NetrwRemoteRmFile(path,rmfile,all) let ret= system(netrw_rm_cmd) if v:shell_error != 0 if exists("b:netrw_curdir") && b:netrw_curdir != getcwd() && !g:netrw_keepdir - call netrw#ErrorMsg(s:ERROR,"remove failed; perhaps due to vim's current directory<".getcwd()."> not matching netrw's (".b:netrw_curdir.") (see :help netrw-cd)",102) + call netrw#ErrorMsg(s:ERROR,"remove failed; perhaps due to vim's current directory<".getcwd()."> not matching netrw's (".b:netrw_curdir.") (see :help netrw-cd)",102) else call netrw#ErrorMsg(s:WARNING,"cmd<".netrw_rm_cmd."> failed",60) endif @@ -11083,16 +11083,16 @@ fun! s:LocalListing() " call Decho("pfile <".pfile.">",'~'.expand("<slnum>")) if w:netrw_liststyle == s:LONGLIST - let longfile= printf("%-".g:netrw_maxfilenamelen."S",pfile) - let sz = getfsize(filename) - let szlen = 15 - (strdisplaywidth(longfile) - g:netrw_maxfilenamelen) - let szlen = (szlen > 0) ? szlen : 0 + let longfile = printf("%-".g:netrw_maxfilenamelen."S",pfile) + let sz = getfsize(filename) + let szlen = 15 - (strdisplaywidth(longfile) - g:netrw_maxfilenamelen) + let szlen = (szlen > 0) ? szlen : 0 if g:netrw_sizestyle =~# "[hH]" let sz= s:NetrwHumanReadable(sz) endif let fsz = printf("%".szlen."S",sz) - let pfile = longfile." ".fsz." ".strftime(g:netrw_timefmt,getftime(filename)) + let pfile= longfile." ".fsz." ".strftime(g:netrw_timefmt,getftime(filename)) " call Decho("longlist support: sz=".sz." fsz=".fsz,'~'.expand("<slnum>")) endif @@ -12112,7 +12112,7 @@ fun! s:NetrwLcd(newdir) if (has("win32") || has("win95") || has("win64") || has("win16")) && !g:netrw_cygwin if a:newdir =~ '^\\\\\w\+' || a:newdir =~ '^//\w\+' let dirname = '\' - exe 'NetrwKeepj sil lcd '.fnameescape(dirname) + exe 'NetrwKeepj sil lcd '.fnameescape(dirname) endif endif catch /^Vim\%((\a\+)\)\=:E472/ diff --git a/runtime/autoload/tar.vim b/runtime/autoload/tar.vim index e242fe98e3..5ecce8579f 100644 --- a/runtime/autoload/tar.vim +++ b/runtime/autoload/tar.vim @@ -163,9 +163,9 @@ fun! tar#Browse(tarfile) " call Decho("1: exe silent r! gzip -d -c -- ".shellescape(tarfile,1)." | ".g:tar_cmd." -".g:tar_browseoptions." - ") exe "sil! r! gzip -d -c -- ".shellescape(tarfile,1)." | ".g:tar_cmd." -".g:tar_browseoptions." - " - elseif tarfile =~# '\.\(tgz\)$' || tarfile =~# '\.\(tbz\)$' || tarfile =~# '\.\(txz\)$' || tarfile =~# '\.\(tzs\)$' + elseif tarfile =~# '\.\(tgz\)$' || tarfile =~# '\.\(tbz\)$' || tarfile =~# '\.\(txz\)$' || tarfile =~# '\.\(tzst\)$' if has("unix") && executable("file") - let filekind= system("file ".shellescape(tarfile,1)) =~ "bzip2" + let filekind= system("file ".shellescape(tarfile,1)) else let filekind= "" endif @@ -192,7 +192,7 @@ fun! tar#Browse(tarfile) elseif tarfile =~# '\.\(xz\|txz\)$' " call Decho("3: exe silent r! xz --decompress --stdout -- ".shellescape(tarfile,1)." | ".g:tar_cmd." -".g:tar_browseoptions." - ") exe "sil! r! xz --decompress --stdout -- ".shellescape(tarfile,1)." | ".g:tar_cmd." -".g:tar_browseoptions." - " - elseif tarfile =~# '\.\(zst\|tzs\)$' + elseif tarfile =~# '\.\(zst\|tzst\)$' exe "sil! r! zstd --decompress --stdout -- ".shellescape(tarfile,1)." | ".g:tar_cmd." -".g:tar_browseoptions." - " else if tarfile =~ '^\s*-' @@ -230,7 +230,7 @@ fun! tar#Browse(tarfile) " set up maps supported for tar setlocal noma nomod ro noremap <silent> <buffer> <cr> :call <SID>TarBrowseSelect()<cr> - noremap <silent> <buffer> x :call tar#Extract()<cr> + noremap <silent> <buffer> x :call tar#Extract()<cr> if &mouse != "" noremap <silent> <buffer> <leftmouse> <leftmouse>:call <SID>TarBrowseSelect()<cr> endif @@ -468,9 +468,9 @@ fun! tar#Write(fname) let compress= "xz -- ".shellescape(tarfile,0) " call Decho("compress<".compress.">") elseif tarfile =~# '\.zst' - call system("zstd --decompress -- ".shellescape(tarfile,0)) + call system("zstd --decompress --rm -- ".shellescape(tarfile,0)) let tarfile = substitute(tarfile,'\.zst','','e') - let compress= "zstd -- ".shellescape(tarfile,0) + let compress= "zstd --rm -- ".shellescape(tarfile,0) elseif tarfile =~# '\.lzma' call system("lzma -d -- ".shellescape(tarfile,0)) let tarfile = substitute(tarfile,'\.lzma','','e') @@ -486,7 +486,7 @@ fun! tar#Write(fname) else " call Decho("tarfile<".tarfile."> fname<".fname.">") - + if fname =~ '/' let dirpath = substitute(fname,'/[^/]\+$','','e') if has("win32unix") && executable("cygpath") @@ -502,7 +502,7 @@ fun! tar#Write(fname) let tarfile = substitute(tarfile, '-', './-', '') endif " call Decho("tarfile<".tarfile."> fname<".fname.">") - + if exists("g:tar_secure") let tar_secure= " -- " else @@ -512,7 +512,7 @@ fun! tar#Write(fname) if has("win32unix") && executable("cygpath") let tarfile = substitute(system("cygpath ".shellescape(tarfile,0)),'\n','','e') endif - + " delete old file from tarfile " call Decho("system(".g:tar_cmd." ".g:tar_delfile." ".shellescape(tarfile,0)." -- ".shellescape(fname,0).")") call system(g:tar_cmd." ".g:tar_delfile." ".shellescape(tarfile,0).tar_secure.shellescape(fname,0)) @@ -521,8 +521,8 @@ fun! tar#Write(fname) " call Decho("***error*** (tar#Write) sorry, unable to update ".fnameescape(tarfile)." with ".fnameescape(fname)) echohl Error | echo "***error*** (tar#Write) sorry, unable to update ".fnameescape(tarfile)." with ".fnameescape(fname) | echohl None else - - " update tarfile with new file + + " update tarfile with new file " call Decho(g:tar_cmd." -".g:tar_writeoptions." ".shellescape(tarfile,0).tar_secure.shellescape(fname,0)) call system(g:tar_cmd." -".g:tar_writeoptions." ".shellescape(tarfile,0).tar_secure.shellescape(fname,0)) if v:shell_error != 0 @@ -555,7 +555,7 @@ fun! tar#Write(fname) unlet s:tblfile_{winnr()} endif endif - + " cleanup and restore current directory cd .. call s:Rmdir("_ZIPVIM_") @@ -696,13 +696,13 @@ fun! tar#Extract() echo "***note*** successfully extracted ".fname endif - elseif filereadable(tarbase.".tzs") + elseif filereadable(tarbase.".tzst") let extractcmd= substitute(extractcmd,"-","--zstd","") -" call Decho("system(".extractcmd." ".shellescape(tarbase).".tzs ".shellescape(fname).")") - call system(extractcmd." ".shellescape(tarbase).".txz ".shellescape(fname)) +" call Decho("system(".extractcmd." ".shellescape(tarbase).".tzst ".shellescape(fname).")") + call system(extractcmd." ".shellescape(tarbase).".tzst ".shellescape(fname)) if v:shell_error != 0 - echohl Error | echo "***error*** ".extractcmd." ".tarbase.".tzs ".fname.": failed!" | echohl NONE -" call Decho("***error*** ".extractcmd." ".tarbase.".tzs ".fname.": failed!") + echohl Error | echo "***error*** ".extractcmd." ".tarbase.".tzst ".fname.": failed!" | echohl NONE +" call Decho("***error*** ".extractcmd." ".tarbase.".tzst ".fname.": failed!") else echo "***note*** successfully extracted ".fname endif @@ -710,7 +710,7 @@ fun! tar#Extract() elseif filereadable(tarbase.".tar.zst") let extractcmd= substitute(extractcmd,"-","--zstd","") " call Decho("system(".extractcmd." ".shellescape(tarbase).".tar.zst ".shellescape(fname).")") - call system(extractcmd." ".shellescape(tarbase).".tar.xz ".shellescape(fname)) + call system(extractcmd." ".shellescape(tarbase).".tar.zst ".shellescape(fname)) if v:shell_error != 0 echohl Error | echo "***error*** ".extractcmd." ".tarbase.".tar.zst ".fname.": failed!" | echohl NONE " call Decho("***error*** ".extractcmd." ".tarbase.".tar.zst ".fname.": failed!") diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index 07e4473ac2..b5a49f6002 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -1277,7 +1277,8 @@ nvim_paste({data}, {crlf}, {phase}) *nvim_paste()* • {data} Multiline input. May be binary (containing NUL bytes). • {crlf} Also break lines at CR and CRLF. • {phase} -1: paste in a single call (i.e. without streaming). To - "stream" a paste, call `nvim_paste` sequentially with these `phase` values: + "stream" a paste, call `nvim_paste` sequentially + with these `phase` values: • 1: starts the paste (exactly once) • 2: continues the paste (zero or more times) • 3: ends the paste (exactly once) @@ -2095,7 +2096,8 @@ nvim_buf_attach({buffer}, {send_buffer}, {*opts}) *nvim_buf_attach()* will be `nvim_buf_changedtick_event`. Not for Lua callbacks. • {opts} Optional parameters. - • on_lines: Lua callback invoked on change. Return `true` to detach. Args: + • on_lines: Lua callback invoked on change. Return `true` to + detach. Args: • the string "lines" • buffer handle • b:changedtick @@ -2108,7 +2110,8 @@ nvim_buf_attach({buffer}, {send_buffer}, {*opts}) *nvim_buf_attach()* • on_bytes: Lua callback invoked on change. This callback receives more granular information about the - change compared to on_lines. Return `true` to detach. Args: + change compared to on_lines. Return `true` to + detach. Args: • the string "bytes" • buffer handle • b:changedtick @@ -2704,7 +2707,8 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) wrapped lines. • hl_mode : control how highlights are combined with the highlights of the text. Currently only affects virt_text - highlights, but might affect `hl_group` in later versions. + highlights, but might affect `hl_group` in + later versions. • "replace": only show the virt_text color. This is the default. • "combine": combine with background text color. @@ -3141,8 +3145,8 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* • height: Window height (in character cells). Minimum of 1. • bufpos: Places float relative to buffer text (only when relative="win"). Takes a tuple of zero-indexed [line, - column]. `row` and `col` if given are applied relative to this position, else they - default to: + column]. `row` and `col` if given are + applied relative to this position, else they default to: • `row=1` and `col=0` if `anchor` is "NW" or "NE" • `row=0` and `col=0` if `anchor` is "SW" or "SE" (thus like a tooltip near the buffer text). @@ -3157,8 +3161,9 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* • external: GUI should display the window as an external top-level window. Currently accepts no other positioning configuration together with this. - • zindex: Stacking order. floats with higher `zindex` go on top on floats with lower indices. Must be larger - than zero. The following screen elements have hard-coded + • zindex: Stacking order. floats with higher `zindex` go on + top on floats with lower indices. Must be larger than + zero. The following screen elements have hard-coded z-indices: • 100: insert completion popupmenu • 200: message scrollback @@ -3351,7 +3356,8 @@ nvim_clear_autocmds({*opts}) *nvim_clear_autocmds()* • NOTE: Cannot be used with {pattern} • group: (string|int) The augroup name or id. - • NOTE: If not passed, will only delete autocmds not in any group. + • NOTE: If not passed, will only delete autocmds not in any + group. nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()* Create or get an autocommand group |autocmd-groups|. @@ -3375,7 +3381,8 @@ nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()* • |autocmd-groups| nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* - Creates an |autocommand| event handler, defined by `callback` (Lua function or Vimscript function name string) or `command` (Ex command string). + Creates an |autocommand| event handler, defined by `callback` (Lua function + or Vimscript function name string) or `command` (Ex command string). Example using Lua callback: >lua vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt index 45d7a4244c..ce3af01073 100644 --- a/runtime/doc/autocmd.txt +++ b/runtime/doc/autocmd.txt @@ -986,6 +986,11 @@ TermLeave After leaving |Terminal-mode|. TermClose When a |terminal| job ends. Sets these |v:event| keys: status + *TermRequest* +TermRequest When a |terminal| job emits an OSC or DCS + sequence. Sets |v:termrequest|. When used from + Lua, the request string is included in the + "data" field of the autocommand callback. *TermResponse* TermResponse When Nvim receives an OSC or DCS response from the terminal. Sets |v:termresponse|. When used diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt index 106e130a41..5ff1c3bab5 100644 --- a/runtime/doc/diagnostic.txt +++ b/runtime/doc/diagnostic.txt @@ -390,7 +390,7 @@ config({opts}, {namespace}) *vim.diagnostic.config()* any of the above. Parameters: ~ - • {opts} (table|nil) When omitted or "nil", retrieve the current + • {opts} (`table?`) When omitted or "nil", retrieve the current configuration. Otherwise, a configuration table with the following keys: • underline: (default true) Use underline for @@ -475,55 +475,55 @@ config({opts}, {namespace}) *vim.diagnostic.config()* severities are displayed before lower severities (e.g. ERROR is displayed before WARN). Options: • reverse: (boolean) Reverse sort order - • {namespace} (integer|nil) Update the options for the given namespace. + • {namespace} (`integer?`) Update the options for the given namespace. When omitted, update the global diagnostic options. Return: ~ - (table|nil) table of current diagnostic config if `opts` is omitted. + (`table?`) table of current diagnostic config if `opts` is omitted. count({bufnr}, {opts}) *vim.diagnostic.count()* Get current diagnostics count. Parameters: ~ - • {bufnr} (integer|nil) Buffer number to get diagnostics from. Use 0 - for current buffer or nil for all buffers. - • {opts} (table|nil) A table with the following keys: + • {bufnr} (`integer?`) Buffer number to get diagnostics from. Use 0 for + current buffer or nil for all buffers. + • {opts} (`table?`) A table with the following keys: • namespace: (number) Limit diagnostics to the given namespace. • lnum: (number) Limit diagnostics to the given line number. • severity: See |diagnostic-severity|. Return: ~ - (table) A table with actually present severity values as keys (see + (`table`) A table with actually present severity values as keys (see |diagnostic-severity|) and integer counts as values. disable({bufnr}, {namespace}) *vim.diagnostic.disable()* Disable diagnostics in the given buffer. Parameters: ~ - • {bufnr} (integer|nil) Buffer number, or 0 for current buffer. - When omitted, disable diagnostics in all buffers. - • {namespace} (integer|nil) Only disable diagnostics for the given + • {bufnr} (`integer?`) Buffer number, or 0 for current buffer. When + omitted, disable diagnostics in all buffers. + • {namespace} (`integer?`) Only disable diagnostics for the given namespace. enable({bufnr}, {namespace}) *vim.diagnostic.enable()* Enable diagnostics in the given buffer. Parameters: ~ - • {bufnr} (integer|nil) Buffer number, or 0 for current buffer. - When omitted, enable diagnostics in all buffers. - • {namespace} (integer|nil) Only enable diagnostics for the given + • {bufnr} (`integer?`) Buffer number, or 0 for current buffer. When + omitted, enable diagnostics in all buffers. + • {namespace} (`integer?`) Only enable diagnostics for the given namespace. fromqflist({list}) *vim.diagnostic.fromqflist()* Convert a list of quickfix items to a list of diagnostics. Parameters: ~ - • {list} table[] List of quickfix items from |getqflist()| or + • {list} (`table[]`) List of quickfix items from |getqflist()| or |getloclist()|. Return: ~ - Diagnostic [] array of |diagnostic-structure| + (`Diagnostic[]`) array of |diagnostic-structure| get({bufnr}, {opts}) *vim.diagnostic.get()* Get current diagnostics. @@ -532,75 +532,77 @@ get({bufnr}, {opts}) *vim.diagnostic.get()* diagnostics in a buffer, use |vim.diagnostic.set()|. Parameters: ~ - • {bufnr} (integer|nil) Buffer number to get diagnostics from. Use 0 - for current buffer or nil for all buffers. - • {opts} (table|nil) A table with the following keys: + • {bufnr} (`integer?`) Buffer number to get diagnostics from. Use 0 for + current buffer or nil for all buffers. + • {opts} (`table?`) A table with the following keys: • namespace: (number) Limit diagnostics to the given namespace. • lnum: (number) Limit diagnostics to the given line number. • severity: See |diagnostic-severity|. Return: ~ - Diagnostic [] table A list of diagnostic items |diagnostic-structure|. Keys `bufnr` , `end_lnum` , `end_col` , and `severity` are guaranteed to be present. + (`Diagnostic[]`) table A list of diagnostic items + |diagnostic-structure|. Keys `bufnr` , `end_lnum` , `end_col` , and `severity` are + guaranteed to be present. get_namespace({namespace}) *vim.diagnostic.get_namespace()* Get namespace metadata. Parameters: ~ - • {namespace} (integer) Diagnostic namespace + • {namespace} (`integer`) Diagnostic namespace Return: ~ - (table) Namespace metadata + (`table`) Namespace metadata get_namespaces() *vim.diagnostic.get_namespaces()* Get current diagnostic namespaces. Return: ~ - (table) A list of active diagnostic namespaces |vim.diagnostic|. + (`table`) A list of active diagnostic namespaces |vim.diagnostic|. get_next({opts}) *vim.diagnostic.get_next()* Get the next diagnostic closest to the cursor position. Parameters: ~ - • {opts} (table|nil) See |vim.diagnostic.goto_next()| + • {opts} (`table?`) See |vim.diagnostic.goto_next()| Return: ~ - Diagnostic|nil Next diagnostic + (`Diagnostic?`) Next diagnostic get_next_pos({opts}) *vim.diagnostic.get_next_pos()* Return the position of the next diagnostic in the current buffer. Parameters: ~ - • {opts} (table|nil) See |vim.diagnostic.goto_next()| + • {opts} (`table?`) See |vim.diagnostic.goto_next()| Return: ~ - table|false Next diagnostic position as a (row, col) tuple or false if - no next diagnostic. + (`table|false`) Next diagnostic position as a (row, col) tuple or + false if no next diagnostic. get_prev({opts}) *vim.diagnostic.get_prev()* Get the previous diagnostic closest to the cursor position. Parameters: ~ - • {opts} nil|table See |vim.diagnostic.goto_next()| + • {opts} (`table?`) See |vim.diagnostic.goto_next()| Return: ~ - Diagnostic|nil Previous diagnostic + (`Diagnostic?`) Previous diagnostic get_prev_pos({opts}) *vim.diagnostic.get_prev_pos()* Return the position of the previous diagnostic in the current buffer. Parameters: ~ - • {opts} (table|nil) See |vim.diagnostic.goto_next()| + • {opts} (`table?`) See |vim.diagnostic.goto_next()| Return: ~ - table|false Previous diagnostic position as a (row, col) tuple or + (`table|false`) Previous diagnostic position as a (row, col) tuple or false if there is no prior diagnostic goto_next({opts}) *vim.diagnostic.goto_next()* Move to the next diagnostic. Parameters: ~ - • {opts} (table|nil) Configuration table with the following keys: + • {opts} (`table?`) Configuration table with the following keys: • namespace: (number) Only consider diagnostics from the given namespace. • cursor_position: (cursor position) Cursor position as a @@ -621,7 +623,7 @@ goto_prev({opts}) *vim.diagnostic.goto_prev()* Move to the previous diagnostic in the current buffer. Parameters: ~ - • {opts} (table|nil) See |vim.diagnostic.goto_next()| + • {opts} (`table?`) See |vim.diagnostic.goto_next()| hide({namespace}, {bufnr}) *vim.diagnostic.hide()* Hide currently displayed diagnostics. @@ -634,22 +636,22 @@ hide({namespace}, {bufnr}) *vim.diagnostic.hide()* |vim.diagnostic.disable()|. Parameters: ~ - • {namespace} (integer|nil) Diagnostic namespace. When omitted, hide diagnostics from all - namespaces. - • {bufnr} (integer|nil) Buffer number, or 0 for current buffer. - When omitted, hide diagnostics in all buffers. + • {namespace} (`integer?`) Diagnostic namespace. When omitted, hide + diagnostics from all namespaces. + • {bufnr} (`integer?`) Buffer number, or 0 for current buffer. When + omitted, hide diagnostics in all buffers. is_disabled({bufnr}, {namespace}) *vim.diagnostic.is_disabled()* Check whether diagnostics are disabled in a given buffer. Parameters: ~ - • {bufnr} (integer|nil) Buffer number, or 0 for current buffer. - • {namespace} (integer|nil) Diagnostic namespace. When omitted, checks if all diagnostics are - disabled in {bufnr}. Otherwise, only checks if - diagnostics from {namespace} are disabled. + • {bufnr} (`integer?`) Buffer number, or 0 for current buffer. + • {namespace} (`integer?`) Diagnostic namespace. When omitted, checks if + all diagnostics are disabled in {bufnr}. Otherwise, only + checks if diagnostics from {namespace} are disabled. Return: ~ - (boolean) + (`boolean`) *vim.diagnostic.match()* match({str}, {pat}, {groups}, {severity_map}, {defaults}) @@ -667,25 +669,25 @@ match({str}, {pat}, {groups}, {severity_map}, {defaults}) < Parameters: ~ - • {str} (string) String to parse diagnostics from. - • {pat} (string) Lua pattern with capture groups. - • {groups} (table) List of fields in a |diagnostic-structure| to - associate with captures from {pat}. - • {severity_map} (table) A table mapping the severity field from + • {str} (`string`) String to parse diagnostics from. + • {pat} (`string`) Lua pattern with capture groups. + • {groups} (`table`) List of fields in a |diagnostic-structure| + to associate with captures from {pat}. + • {severity_map} (`table`) A table mapping the severity field from {groups} with an item from |vim.diagnostic.severity|. - • {defaults} (table|nil) Table of default values for any fields not + • {defaults} (`table?`) Table of default values for any fields not listed in {groups}. When omitted, numeric values default to 0 and "severity" defaults to ERROR. Return: ~ - Diagnostic|nil: |diagnostic-structure| or `nil` if {pat} fails to - match {str}. + (`Diagnostic?`) |diagnostic-structure| or `nil` if {pat} fails to match + {str}. open_float({opts}, {...}) *vim.diagnostic.open_float()* Show diagnostics in a floating window. Parameters: ~ - • {opts} (table|nil) Configuration table with the same keys as + • {opts} (`table?`) Configuration table with the same keys as |vim.lsp.util.open_floating_preview()| in addition to the following: • bufnr: (number) Buffer number to show diagnostics from. @@ -735,7 +737,7 @@ open_float({opts}, {...}) *vim.diagnostic.open_float()* from |vim.diagnostic.config()|. Return: ~ - integer|nil, integer|nil: ({float_bufnr}, {win_id}) + (`integer?, integer?`) ({float_bufnr}, {win_id}) reset({namespace}, {bufnr}) *vim.diagnostic.reset()* Remove all diagnostics from the given namespace. @@ -746,27 +748,27 @@ reset({namespace}, {bufnr}) *vim.diagnostic.reset()* re-displayed, use |vim.diagnostic.hide()|. Parameters: ~ - • {namespace} (integer|nil) Diagnostic namespace. When omitted, remove diagnostics from all - namespaces. - • {bufnr} (integer|nil) Remove diagnostics for the given buffer. + • {namespace} (`integer?`) Diagnostic namespace. When omitted, remove + diagnostics from all namespaces. + • {bufnr} (`integer?`) Remove diagnostics for the given buffer. When omitted, diagnostics are removed for all buffers. set({namespace}, {bufnr}, {diagnostics}, {opts}) *vim.diagnostic.set()* Set diagnostics for the given namespace and buffer. Parameters: ~ - • {namespace} (integer) The diagnostic namespace - • {bufnr} (integer) Buffer number - • {diagnostics} (table) A list of diagnostic items + • {namespace} (`integer`) The diagnostic namespace + • {bufnr} (`integer`) Buffer number + • {diagnostics} (`table`) A list of diagnostic items |diagnostic-structure| - • {opts} (table|nil) Display options to pass to + • {opts} (`table?`) Display options to pass to |vim.diagnostic.show()| setloclist({opts}) *vim.diagnostic.setloclist()* Add buffer diagnostics to the location list. Parameters: ~ - • {opts} (table|nil) Configuration table with the following keys: + • {opts} (`table?`) Configuration table with the following keys: • namespace: (number) Only add diagnostics from the given namespace. • winnr: (number, default 0) Window number to set location @@ -781,7 +783,7 @@ setqflist({opts}) *vim.diagnostic.setqflist()* Add all diagnostics to the quickfix list. Parameters: ~ - • {opts} (table|nil) Configuration table with the following keys: + • {opts} (`table?`) Configuration table with the following keys: • namespace: (number) Only add diagnostics from the given namespace. • open: (boolean, default true) Open quickfix list after @@ -795,17 +797,17 @@ show({namespace}, {bufnr}, {diagnostics}, {opts}) Display diagnostics for the given namespace and buffer. Parameters: ~ - • {namespace} (integer|nil) Diagnostic namespace. When omitted, show diagnostics from all - namespaces. - • {bufnr} (integer|nil) Buffer number, or 0 for current buffer. + • {namespace} (`integer?`) Diagnostic namespace. When omitted, show + diagnostics from all namespaces. + • {bufnr} (`integer?`) Buffer number, or 0 for current buffer. When omitted, show diagnostics in all buffers. - • {diagnostics} (table|nil) The diagnostics to display. When omitted, + • {diagnostics} (`table?`) The diagnostics to display. When omitted, use the saved diagnostics for the given namespace and buffer. This can be used to display a list of diagnostics without saving them or to display only a subset of diagnostics. May not be used when {namespace} or {bufnr} is nil. - • {opts} (table|nil) Display options. See + • {opts} (`table?`) Display options. See |vim.diagnostic.config()|. toqflist({diagnostics}) *vim.diagnostic.toqflist()* @@ -813,9 +815,9 @@ toqflist({diagnostics}) *vim.diagnostic.toqflist()* passed to |setqflist()| or |setloclist()|. Parameters: ~ - • {diagnostics} (table) List of diagnostics |diagnostic-structure|. + • {diagnostics} (`table`) List of diagnostics |diagnostic-structure|. Return: ~ - table[] of quickfix list items |setqflist-what| + (`table[]`) of quickfix list items |setqflist-what| vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index bbf19f9569..7e1c0a4a15 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -642,12 +642,12 @@ buf_attach_client({bufnr}, {client_id}) *vim.lsp.buf_attach_client()* Without calling this, the server won't be notified of changes to a buffer. Parameters: ~ - • {bufnr} (integer) Buffer handle, or 0 for current - • {client_id} (integer) Client id + • {bufnr} (`integer`) Buffer handle, or 0 for current + • {client_id} (`integer`) Client id Return: ~ - (boolean) success `true` if client was attached successfully; `false` - otherwise + (`boolean`) success `true` if client was attached successfully; + `false` otherwise buf_detach_client({bufnr}, {client_id}) *vim.lsp.buf_detach_client()* Detaches client from the specified buffer. Note: While the server is @@ -655,26 +655,26 @@ buf_detach_client({bufnr}, {client_id}) *vim.lsp.buf_detach_client()* send notifications should it ignore this notification. Parameters: ~ - • {bufnr} (integer) Buffer handle, or 0 for current - • {client_id} (integer) Client id + • {bufnr} (`integer`) Buffer handle, or 0 for current + • {client_id} (`integer`) Client id buf_is_attached({bufnr}, {client_id}) *vim.lsp.buf_is_attached()* Checks if a buffer is attached for a particular client. Parameters: ~ - • {bufnr} (integer) Buffer handle, or 0 for current - • {client_id} (integer) the client id + • {bufnr} (`integer`) Buffer handle, or 0 for current + • {client_id} (`integer`) the client id buf_notify({bufnr}, {method}, {params}) *vim.lsp.buf_notify()* Send a notification to a server Parameters: ~ - • {bufnr} (integer|nil) The number of the buffer - • {method} (string) Name of the request method - • {params} (any) Arguments to send to the server + • {bufnr} (`integer?`) The number of the buffer + • {method} (`string`) Name of the request method + • {params} (`any`) Arguments to send to the server Return: ~ - (boolean) success true if any client returns true; false otherwise + (`boolean`) success true if any client returns true; false otherwise *vim.lsp.buf_request_all()* buf_request_all({bufnr}, {method}, {params}, {handler}) @@ -682,14 +682,15 @@ buf_request_all({bufnr}, {method}, {params}, {handler}) executes the `handler` callback with the combined result. Parameters: ~ - • {bufnr} (integer) Buffer handle, or 0 for current. - • {method} (string) LSP method name - • {params} (table|nil) Parameters to send to the server - • {handler} (function) Handler called after all requests are completed. - Server results are passed as a `client_id:result` map. + • {bufnr} (`integer`) Buffer handle, or 0 for current. + • {method} (`string`) LSP method name + • {params} (`table?`) Parameters to send to the server + • {handler} (`function`) Handler called after all requests are + completed. Server results are passed as a + `client_id:result` map. Return: ~ - (function) cancel Function that cancels all requests. + (`function`) cancel Function that cancels all requests. *vim.lsp.buf_request_sync()* buf_request_sync({bufnr}, {method}, {params}, {timeout_ms}) @@ -700,15 +701,15 @@ buf_request_sync({bufnr}, {method}, {params}, {timeout_ms}) result is different. Waits a maximum of {timeout_ms} (default 1000) ms. Parameters: ~ - • {bufnr} (integer) Buffer handle, or 0 for current. - • {method} (string) LSP method name - • {params} (table|nil) Parameters to send to the server - • {timeout_ms} (integer|nil) Maximum time in milliseconds to wait for a + • {bufnr} (`integer`) Buffer handle, or 0 for current. + • {method} (`string`) LSP method name + • {params} (`table?`) Parameters to send to the server + • {timeout_ms} (`integer?`) Maximum time in milliseconds to wait for a result. Defaults to 1000 Return (multiple): ~ - (table) result Map of client_id:request_result. - (string|nil) err On timeout, cancel, or error, `err` is a string + (`table`) result Map of client_id:request_result. + (`string?`) err On timeout, cancel, or error, `err` is a string describing the failure reason, and `result` is nil. client() *vim.lsp.client* @@ -780,10 +781,10 @@ client_is_stopped({client_id}) *vim.lsp.client_is_stopped()* Checks whether a client is stopped. Parameters: ~ - • {client_id} (integer) + • {client_id} (`integer`) Return: ~ - (boolean) stopped true if client is stopped, false otherwise. + (`boolean`) stopped true if client is stopped, false otherwise. commands *vim.lsp.commands* Registry for client side commands. This is an extension point for plugins @@ -813,7 +814,7 @@ formatexpr({opts}) *vim.lsp.formatexpr()* 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})'`. Parameters: ~ - • {opts} (table) options for customizing the formatting expression + • {opts} (`table`) options for customizing the formatting expression which takes the following optional keys: • timeout_ms (default 500ms). The timeout period for the formatting request. @@ -823,26 +824,26 @@ get_buffers_by_client_id({client_id}) Returns list of buffers attached to client_id. Parameters: ~ - • {client_id} (integer) client id + • {client_id} (`integer`) client id Return: ~ - integer[] buffers list of buffer ids + (`integer[]`) buffers list of buffer ids get_client_by_id({client_id}) *vim.lsp.get_client_by_id()* Gets a client by id, or nil if the id is invalid. The returned client may not yet be fully initialized. Parameters: ~ - • {client_id} (integer) client id + • {client_id} (`integer`) client id Return: ~ - (nil|lsp.Client) client rpc object + (`lsp.Client?`) client rpc object get_clients({filter}) *vim.lsp.get_clients()* Get active clients. Parameters: ~ - • {filter} (table|nil) A table with key-value pairs used to filter the + • {filter} (`table?`) A table with key-value pairs used to filter the returned clients. The available keys are: • id (number): Only return clients with the given id • bufnr (number): Only return clients attached to this @@ -852,23 +853,23 @@ get_clients({filter}) *vim.lsp.get_clients()* method Return: ~ - lsp.Client []: List of |vim.lsp.client| objects + (`lsp.Client[]`) List of |vim.lsp.client| objects get_log_path() *vim.lsp.get_log_path()* Gets the path of the logfile used by the LSP client. Return: ~ - (string) path to log file + (`string`) path to log file omnifunc({findstart}, {base}) *vim.lsp.omnifunc()* Implements 'omnifunc' compatible LSP completion. Parameters: ~ - • {findstart} (integer) 0 or 1, decides behavior - • {base} (integer) findstart=0, text to match against + • {findstart} (`integer`) 0 or 1, decides behavior + • {base} (`integer`) findstart=0, text to match against Return: ~ - integer|table Decided by {findstart}: + (`integer|table`) Decided by {findstart}: • findstart=0: column where the completion starts, or -2 or -3 • findstart=1: list of matches (actually just calls |complete()|) @@ -887,7 +888,7 @@ set_log_level({level}) *vim.lsp.set_log_level()* Use `lsp.log_levels` for reverse lookup. Parameters: ~ - • {level} (integer|string) the case insensitive level name or number + • {level} (`integer|string`) the case insensitive level name or number See also: ~ • |vim.lsp.log_levels| @@ -932,9 +933,9 @@ start({config}, {opts}) *vim.lsp.start()* `ftplugin/<filetype_name>.lua` (See |ftplugin-name|) Parameters: ~ - • {config} (table) Same configuration as documented in + • {config} (`table`) Same configuration as documented in |vim.lsp.start_client()| - • {opts} (nil|lsp.StartOpts) Optional keyword arguments: + • {opts} (`lsp.StartOpts?`) Optional keyword arguments: • reuse_client (fun(client: client, config: table): boolean) Predicate used to decide if a client should be re-used. Used on all running clients. The default implementation @@ -943,7 +944,7 @@ start({config}, {opts}) *vim.lsp.start()* re-using a client (0 for current). Return: ~ - (integer|nil) client_id + (`integer?`) client_id start_client({config}) *vim.lsp.start_client()* Starts and initializes a client with the given configuration. @@ -951,7 +952,7 @@ start_client({config}) *vim.lsp.start_client()* Field `cmd` in {config} is required. Parameters: ~ - • {config} ( lsp.ClientConfig ) Configuration for the server: + • {config} (`lsp.ClientConfig`) Configuration for the server: • cmd: (string[]|fun(dispatchers: table):table) command a list of strings treated like |jobstart()|. The command must launch the language server process. `cmd` can also be @@ -1060,7 +1061,7 @@ start_client({config}) *vim.lsp.start_client()* initialization. Return: ~ - (integer|nil) client_id. |vim.lsp.get_client_by_id()| Note: client may + (`integer?`) client_id. |vim.lsp.get_client_by_id()| Note: client may not be fully initialized. Use `on_init` to do any actions once the client has been initialized. @@ -1069,7 +1070,7 @@ status() *vim.lsp.status()* a string. Empty if there are no clients or if no new messages Return: ~ - (string) + (`string`) stop_client({client_id}, {force}) *vim.lsp.stop_client()* Stops a client(s). @@ -1083,9 +1084,9 @@ stop_client({client_id}, {force}) *vim.lsp.stop_client()* for this client, then force-shutdown is attempted. Parameters: ~ - • {client_id} integer|table id or |vim.lsp.client| object, or list + • {client_id} (`integer|table`) id or |vim.lsp.client| object, or list thereof - • {force} (boolean|nil) shutdown forcefully + • {force} (`boolean?`) shutdown forcefully tagfunc({pattern}, {flags}) *vim.lsp.tagfunc()* Provides an interface between the built-in client and 'tagfunc'. @@ -1096,18 +1097,18 @@ tagfunc({pattern}, {flags}) *vim.lsp.tagfunc()* LSP servers, falls back to using built-in tags. Parameters: ~ - • {pattern} (string) Pattern used to find a workspace symbol - • {flags} (string) See |tag-function| + • {pattern} (`string`) Pattern used to find a workspace symbol + • {flags} (`string`) See |tag-function| Return: ~ - table[] tags A list of matching tags + (`table[]`) tags A list of matching tags with({handler}, {override_config}) *vim.lsp.with()* Function to manage overriding defaults for LSP handlers. Parameters: ~ - • {handler} (lsp.Handler) See |lsp-handler| - • {override_config} (table) Table containing the keys to override + • {handler} (`lsp.Handler`) See |lsp-handler| + • {override_config} (`table`) Table containing the keys to override behavior of the {handler} @@ -1126,9 +1127,10 @@ code_action({options}) *vim.lsp.buf.code_action()* Selects a code action available at the current cursor position. Parameters: ~ - • {options} (table|nil) Optional table which holds the following + • {options} (`table?`) Optional table which holds the following optional fields: - • context: (table|nil) Corresponds to `CodeActionContext` of the LSP specification: + • context: (table|nil) Corresponds to `CodeActionContext` of + the LSP specification: • diagnostics (table|nil): LSP `Diagnostic[]`. Inferred from the current position if not provided. • only (table|nil): List of LSP `CodeActionKind`s used to @@ -1157,7 +1159,7 @@ completion({context}) *vim.lsp.buf.completion()* called in Insert mode. Parameters: ~ - • {context} (table) (context support not yet implemented) Additional + • {context} (`table`) (context support not yet implemented) Additional information about the context in which a completion was triggered (how it was triggered, and by which trigger character, if applicable) @@ -1173,7 +1175,7 @@ declaration({options}) *vim.lsp.buf.declaration()* |vim.lsp.buf.definition()| instead. Parameters: ~ - • {options} (table|nil) additional options + • {options} (`table?`) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) |lsp-on-list-handler| replacing the @@ -1183,7 +1185,7 @@ definition({options}) *vim.lsp.buf.definition()* Jumps to the definition of the symbol under the cursor. Parameters: ~ - • {options} (table|nil) additional options + • {options} (`table?`) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) |lsp-on-list-handler| replacing the @@ -1207,7 +1209,7 @@ document_symbol({options}) *vim.lsp.buf.document_symbol()* Lists all symbols in the current buffer in the quickfix window. Parameters: ~ - • {options} (table|nil) additional options + • {options} (`table?`) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1215,7 +1217,7 @@ execute_command({command_params}) *vim.lsp.buf.execute_command()* Executes an LSP server command. Parameters: ~ - • {command_params} (table) A valid `ExecuteCommandParams` object + • {command_params} (`table`) A valid `ExecuteCommandParams` object See also: ~ • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand @@ -1225,7 +1227,7 @@ format({options}) *vim.lsp.buf.format()* server clients. Parameters: ~ - • {options} (table|nil) Optional table which holds the following + • {options} (`table?`) Optional table which holds the following optional fields: • formatting_options (table|nil): Can be used to specify FormattingOptions. Some unspecified options will be @@ -1267,7 +1269,7 @@ implementation({options}) *vim.lsp.buf.implementation()* quickfix window. Parameters: ~ - • {options} (table|nil) additional options + • {options} (`table?`) additional options • on_list: (function) |lsp-on-list-handler| replacing the default handler. Called for any non-empty result. @@ -1289,8 +1291,8 @@ references({context}, {options}) *vim.lsp.buf.references()* window. Parameters: ~ - • {context} (table|nil) Context for the request - • {options} (table|nil) additional options + • {context} (`table?`) Context for the request + • {options} (`table?`) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1306,9 +1308,9 @@ rename({new_name}, {options}) *vim.lsp.buf.rename()* Renames all references to the symbol under the cursor. Parameters: ~ - • {new_name} (string|nil) If not provided, the user will be prompted - for a new name using |vim.ui.input()|. - • {options} (table|nil) additional options + • {new_name} (`string?`) If not provided, the user will be prompted for + a new name using |vim.ui.input()|. + • {options} (`table?`) additional options • filter (function|nil): Predicate used to filter clients. Receives a client as argument and must return a boolean. Clients matching the predicate are included. @@ -1323,7 +1325,7 @@ type_definition({options}) *vim.lsp.buf.type_definition()* Jumps to the definition of the type of the symbol under the cursor. Parameters: ~ - • {options} (table|nil) additional options + • {options} (`table?`) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) |lsp-on-list-handler| replacing the @@ -1337,8 +1339,8 @@ workspace_symbol({query}, {options}) *vim.lsp.buf.workspace_symbol()* string means no filtering is done. Parameters: ~ - • {query} (string|nil) optional - • {options} (table|nil) additional options + • {query} (`string?`) optional + • {options} (`table?`) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1352,8 +1354,8 @@ get_namespace({client_id}, {is_pull}) |vim.diagnostic| for diagnostics Parameters: ~ - • {client_id} (integer) The id of the LSP client - • {is_pull} boolean? Whether the namespace is for a pull or push + • {client_id} (`integer`) The id of the LSP client + • {is_pull} (`boolean?`) Whether the namespace is for a pull or push client. Defaults to push *vim.lsp.diagnostic.on_diagnostic()* @@ -1382,8 +1384,9 @@ on_diagnostic({_}, {result}, {ctx}, {config}) < Parameters: ~ - • {ctx} lsp.HandlerContext - • {config} (table) Configuration table (see |vim.diagnostic.config()|). + • {ctx} (`lsp.HandlerContext`) + • {config} (`table`) Configuration table (see + |vim.diagnostic.config()|). *vim.lsp.diagnostic.on_publish_diagnostics()* on_publish_diagnostics({_}, {result}, {ctx}, {config}) @@ -1411,8 +1414,9 @@ on_publish_diagnostics({_}, {result}, {ctx}, {config}) < Parameters: ~ - • {ctx} lsp.HandlerContext - • {config} (table) Configuration table (see |vim.diagnostic.config()|). + • {ctx} (`lsp.HandlerContext`) + • {config} (`table`) Configuration table (see + |vim.diagnostic.config()|). ============================================================================== @@ -1422,33 +1426,33 @@ clear({client_id}, {bufnr}) *vim.lsp.codelens.clear()* Clear the lenses Parameters: ~ - • {client_id} (integer|nil) filter by client_id. All clients if nil - • {bufnr} (integer|nil) filter by buffer. All buffers if nil + • {client_id} (`integer?`) filter by client_id. All clients if nil + • {bufnr} (`integer?`) filter by buffer. All buffers if nil display({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.display()* Display the lenses using virtual text Parameters: ~ - • {lenses} lsp.CodeLens[]|nil lenses to display - • {bufnr} (integer) - • {client_id} (integer) + • {lenses} (`lsp.CodeLens[]?`) lenses to display + • {bufnr} (`integer`) + • {client_id} (`integer`) get({bufnr}) *vim.lsp.codelens.get()* Return all lenses for the given buffer Parameters: ~ - • {bufnr} (integer) Buffer number. 0 can be used for the current + • {bufnr} (`integer`) Buffer number. 0 can be used for the current buffer. Return: ~ - lsp.CodeLens[] + (`lsp.CodeLens[]`) *vim.lsp.codelens.on_codelens()* on_codelens({err}, {result}, {ctx}, {_}) |lsp-handler| for the method `textDocument/codeLens` Parameters: ~ - • {ctx} lsp.HandlerContext + • {ctx} (`lsp.HandlerContext`) refresh() *vim.lsp.codelens.refresh()* Refresh the codelens for the current buffer @@ -1466,9 +1470,9 @@ save({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.save()* Store lenses for a specific buffer and client Parameters: ~ - • {lenses} lsp.CodeLens[]|nil lenses to store - • {bufnr} (integer) - • {client_id} (integer) + • {lenses} (`lsp.CodeLens[]?`) lenses to store + • {bufnr} (`integer`) + • {client_id} (`integer`) ============================================================================== @@ -1481,8 +1485,8 @@ enable({bufnr}, {enable}) *vim.lsp.inlay_hint.enable()* This API is pre-release (unstable). Parameters: ~ - • {bufnr} (integer|nil) Buffer handle, or 0 or nil for current - • {enable} (boolean|nil) true/nil to enable, false to disable + • {bufnr} (`integer?`) Buffer handle, or 0 or nil for current + • {enable} (`boolean?`) true/nil to enable, false to disable get({filter}) *vim.lsp.inlay_hint.get()* Get the list of inlay hints, (optionally) restricted by buffer or range. @@ -1505,12 +1509,14 @@ get({filter}) *vim.lsp.inlay_hint.get()* This API is pre-release (unstable). Parameters: ~ - • {filter} vim.lsp.inlay_hint.get.filter ? Optional filters |kwargs|: + • {filter} (`vim.lsp.inlay_hint.get.filter?`) Optional filters + |kwargs|: • bufnr (integer?): 0 for current buffer • range (lsp.Range?) Return: ~ - vim.lsp.inlay_hint.get.ret [] Each list item is a table with the following fields: + (`vim.lsp.inlay_hint.get.ret[]`) Each list item is a table with the + following fields: • bufnr (integer) • client_id (integer) • inlay_hint (lsp.InlayHint) @@ -1520,10 +1526,10 @@ is_enabled({bufnr}) *vim.lsp.inlay_hint.is_enabled()* This API is pre-release (unstable). Parameters: ~ - • {bufnr} (integer|nil) Buffer handle, or 0 or nil for current + • {bufnr} (`integer?`) Buffer handle, or 0 or nil for current Return: ~ - (boolean) + (`boolean`) ============================================================================== @@ -1536,7 +1542,7 @@ force_refresh({bufnr}) *vim.lsp.semantic_tokens.force_refresh()* highlighting (|vim.lsp.semantic_tokens.start()| has been called for it) Parameters: ~ - • {bufnr} (integer|nil) filter by buffer. All buffers if nil, current + • {bufnr} (`integer?`) filter by buffer. All buffers if nil, current buffer if 0 *vim.lsp.semantic_tokens.get_at_pos()* @@ -1545,12 +1551,12 @@ get_at_pos({bufnr}, {row}, {col}) arguments, returns the token under the cursor. Parameters: ~ - • {bufnr} (integer|nil) Buffer number (0 for current buffer, default) - • {row} (integer|nil) Position row (default cursor position) - • {col} (integer|nil) Position column (default cursor position) + • {bufnr} (`integer?`) Buffer number (0 for current buffer, default) + • {row} (`integer?`) Position row (default cursor position) + • {col} (`integer?`) Position column (default cursor position) Return: ~ - (table|nil) List of tokens at position. Each token has the following + (`table?`) List of tokens at position. Each token has the following fields: • line (integer) line number, 0-based • start_col (integer) start column, 0-based @@ -1570,12 +1576,12 @@ highlight_token({token}, {bufnr}, {client_id}, {hl_group}, {opts}) use inside |LspTokenUpdate| callbacks. Parameters: ~ - • {token} (table) a semantic token, found as `args.data.token` in + • {token} (`table`) a semantic token, found as `args.data.token` in |LspTokenUpdate|. - • {bufnr} (integer) the buffer to highlight - • {client_id} (integer) The ID of the |vim.lsp.client| - • {hl_group} (string) Highlight group name - • {opts} (table|nil) Optional parameters. + • {bufnr} (`integer`) the buffer to highlight + • {client_id} (`integer`) The ID of the |vim.lsp.client| + • {hl_group} (`string`) Highlight group name + • {opts} (`table?`) Optional parameters. • priority: (integer|nil) Priority for the applied extmark. Defaults to `vim.highlight.priorities.semantic_tokens + 3` @@ -1593,9 +1599,9 @@ start({bufnr}, {client_id}, {opts}) *vim.lsp.semantic_tokens.start()* < Parameters: ~ - • {bufnr} (integer) - • {client_id} (integer) - • {opts} (nil|table) Optional keyword arguments + • {bufnr} (`integer`) + • {client_id} (`integer`) + • {opts} (`table?`) Optional keyword arguments • debounce (integer, default: 200): Debounce token requests to the server by the given number in milliseconds @@ -1610,8 +1616,8 @@ stop({bufnr}, {client_id}) *vim.lsp.semantic_tokens.stop()* from the buffer. Parameters: ~ - • {bufnr} (integer) - • {client_id} (integer) + • {bufnr} (`integer`) + • {client_id} (`integer`) ============================================================================== @@ -1630,8 +1636,8 @@ hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()* < Parameters: ~ - • {ctx} lsp.HandlerContext - • {config} (table) Configuration table. + • {ctx} (`lsp.HandlerContext`) + • {config} (`table`) Configuration table. • border: (default=nil) • Add borders to the floating window • See |vim.lsp.util.open_floating_preview()| for more @@ -1651,9 +1657,9 @@ signature_help({_}, {result}, {ctx}, {config}) < Parameters: ~ - • {result} (table) Response from the language server - • {ctx} lsp.HandlerContext Client context - • {config} (table) Configuration table. + • {result} (`table`) Response from the language server + • {ctx} (`lsp.HandlerContext`) Client context + • {config} (`table`) Configuration table. • border: (default=nil) • Add borders to the floating window • See |vim.lsp.util.open_floating_preview()| for more @@ -1669,9 +1675,9 @@ apply_text_document_edit({text_document_edit}, {index}, {offset_encoding}) document. Parameters: ~ - • {text_document_edit} (table) a `TextDocumentEdit` object - • {index} (integer) Optional index of the edit, if from a - list of edits (or nil, if not from a list) + • {text_document_edit} (`table`) a `TextDocumentEdit` object + • {index} (`integer`) Optional index of the edit, if from + a list of edits (or nil, if not from a list) See also: ~ • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentEdit @@ -1681,9 +1687,9 @@ apply_text_edits({text_edits}, {bufnr}, {offset_encoding}) Applies a list of text edits to a buffer. Parameters: ~ - • {text_edits} (table) list of `TextEdit` objects - • {bufnr} (integer) Buffer id - • {offset_encoding} (string) utf-8|utf-16|utf-32 + • {text_edits} (`table`) list of `TextEdit` objects + • {bufnr} (`integer`) Buffer id + • {offset_encoding} (`string`) utf-8|utf-16|utf-32 See also: ~ • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit @@ -1693,24 +1699,24 @@ apply_workspace_edit({workspace_edit}, {offset_encoding}) Applies a `WorkspaceEdit`. Parameters: ~ - • {workspace_edit} (table) `WorkspaceEdit` - • {offset_encoding} (string) utf-8|utf-16|utf-32 (required) + • {workspace_edit} (`table`) `WorkspaceEdit` + • {offset_encoding} (`string`) utf-8|utf-16|utf-32 (required) buf_clear_references({bufnr}) *vim.lsp.util.buf_clear_references()* Removes document highlights from a buffer. Parameters: ~ - • {bufnr} (integer|nil) Buffer id + • {bufnr} (`integer?`) Buffer id *vim.lsp.util.buf_highlight_references()* buf_highlight_references({bufnr}, {references}, {offset_encoding}) Shows a list of document highlights for a certain buffer. Parameters: ~ - • {bufnr} (integer) Buffer id - • {references} (table) List of `DocumentHighlight` objects to + • {bufnr} (`integer`) Buffer id + • {references} (`table`) List of `DocumentHighlight` objects to highlight - • {offset_encoding} (string) One of "utf-8", "utf-16", "utf-32". + • {offset_encoding} (`string`) One of "utf-8", "utf-16", "utf-32". See also: ~ • https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent @@ -1720,14 +1726,14 @@ character_offset({buf}, {row}, {col}, {offset_encoding}) Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. Parameters: ~ - • {buf} (integer) buffer number (0 for current) - • {row} 0-indexed line - • {col} 0-indexed byte offset in line - • {offset_encoding} (string) utf-8|utf-16|utf-32 defaults to + • {buf} (`integer`) buffer number (0 for current) + • {row} (`integer`) 0-indexed line + • {col} (`integer`) 0-indexed byte offset in line + • {offset_encoding} (`string`) utf-8|utf-16|utf-32 defaults to `offset_encoding` of first client of `buf` Return: ~ - (integer) `offset_encoding` index of the character in line {row} + (`integer`) `offset_encoding` index of the character in line {row} column {col} in buffer {buf} *vim.lsp.util.convert_input_to_markdown_lines()* @@ -1742,12 +1748,12 @@ convert_input_to_markdown_lines({input}, {contents}) modifications. Parameters: ~ - • {input} (`MarkedString` | `MarkedString[]` | `MarkupContent`) - • {contents} (table|nil) List of strings to extend with converted - lines. Defaults to {}. + • {input} (`lsp.MarkedString|lsp.MarkedString[]|lsp.MarkupContent`) + • {contents} (`table?`) List of strings to extend with converted lines. + Defaults to {}. Return: ~ - string[] extended with lines of converted markdown. + (`string[]`) extended with lines of converted markdown. See also: ~ • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover @@ -1757,15 +1763,15 @@ convert_signature_help_to_markdown_lines({signature_help}, {ft}, {triggers}) Converts `textDocument/signatureHelp` response to markdown lines. Parameters: ~ - • {signature_help} (table) Response of `textDocument/SignatureHelp` - • {ft} (string|nil) filetype that will be use as the `lang` + • {signature_help} (`table`) Response of `textDocument/SignatureHelp` + • {ft} (`string?`) filetype that will be use as the `lang` for the label markdown code block - • {triggers} (table|nil) list of trigger characters from the lsp + • {triggers} (`table?`) list of trigger characters from the lsp server. used to better determine parameter offsets Return (multiple): ~ - (table|nil) table list of lines of converted markdown. - (table|nil) table of active hl + (`table?`) table list of lines of converted markdown. + (`table?`) table of active hl See also: ~ • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp @@ -1774,10 +1780,10 @@ get_effective_tabstop({bufnr}) *vim.lsp.util.get_effective_tabstop()* Returns indentation size. Parameters: ~ - • {bufnr} (integer|nil) Buffer handle, defaults to current + • {bufnr} (`integer?`) Buffer handle, defaults to current Return: ~ - (integer) indentation size + (`integer`) indentation size See also: ~ • 'shiftwidth' @@ -1787,13 +1793,13 @@ jump_to_location({location}, {offset_encoding}, {reuse_win}) Jumps to a location. Parameters: ~ - • {location} (table) (`Location`|`LocationLink`) - • {offset_encoding} (string|nil) utf-8|utf-16|utf-32 - • {reuse_win} (boolean|nil) Jump to existing window if buffer is + • {location} (`table`) (`Location`|`LocationLink`) + • {offset_encoding} (`string?`) utf-8|utf-16|utf-32 + • {reuse_win} (`boolean?`) Jump to existing window if buffer is already open. Return: ~ - (boolean) `true` if the jump succeeded + (`boolean`) `true` if the jump succeeded *vim.lsp.util.locations_to_items()* locations_to_items({locations}, {offset_encoding}) @@ -1807,23 +1813,23 @@ locations_to_items({locations}, {offset_encoding}) |setloclist()|. Parameters: ~ - • {locations} lsp.Location[]|lsp.LocationLink[] - • {offset_encoding} (string) offset_encoding for locations + • {locations} (`lsp.Location[]|lsp.LocationLink[]`) + • {offset_encoding} (`string`) offset_encoding for locations utf-8|utf-16|utf-32 default to first client of buffer Return: ~ - vim.lsp.util.LocationItem [] list of items + (`vim.lsp.util.LocationItem[]`) list of items lookup_section({settings}, {section}) *vim.lsp.util.lookup_section()* Helper function to return nested values in language server settings Parameters: ~ - • {settings} (table) language server settings - • {section} string indicating the field of the settings table + • {settings} (`table`) language server settings + • {section} (`string`) indicating the field of the settings table Return: ~ - table|string The value of settings accessed via section + (`table|string`) The value of settings accessed via section *vim.lsp.util.make_floating_popup_options()* make_floating_popup_options({width}, {height}, {opts}) @@ -1831,9 +1837,9 @@ make_floating_popup_options({width}, {height}, {opts}) table can be passed to |nvim_open_win()|. Parameters: ~ - • {width} (integer) window width (in character cells) - • {height} (integer) window height (in character cells) - • {opts} (table) optional + • {width} (`integer`) window width (in character cells) + • {height} (`integer`) window height (in character cells) + • {opts} (`table`) optional • offset_x (integer) offset to add to `col` • offset_y (integer) offset to add to `row` • border (string or table) override `border` @@ -1849,7 +1855,7 @@ make_floating_popup_options({width}, {height}, {opts}) are not enough lines to display the full window height. Return: ~ - (table) Options + (`table`) Options *vim.lsp.util.make_formatting_params()* make_formatting_params({options}) @@ -1857,10 +1863,10 @@ make_formatting_params({options}) cursor position. Parameters: ~ - • {options} (table|nil) with valid `FormattingOptions` entries + • {options} (`table?`) with valid `FormattingOptions` entries Return: ~ - lsp.DocumentFormattingParams object + (`lsp.DocumentFormattingParams`) object See also: ~ • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting @@ -1871,18 +1877,18 @@ make_given_range_params({start_pos}, {end_pos}, {bufnr}, {offset_encoding}) similar to |vim.lsp.util.make_range_params()|. Parameters: ~ - • {start_pos} integer[]|nil {row,col} mark-indexed position. + • {start_pos} (`integer[]?`) {row,col} mark-indexed position. Defaults to the start of the last visual selection. - • {end_pos} integer[]|nil {row,col} mark-indexed position. + • {end_pos} (`integer[]?`) {row,col} mark-indexed position. Defaults to the end of the last visual selection. - • {bufnr} (integer|nil) buffer handle or 0 for current, + • {bufnr} (`integer?`) buffer handle or 0 for current, defaults to current - • {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults to + • {offset_encoding} (`"utf-8"|"utf-16"|"utf-32"?`) defaults to `offset_encoding` of first client of `bufnr` Return: ~ - (table) { textDocument = { uri = `current_file_uri` }, range = { start - = `start_position`, end = `end_position` } } + (`table`) { textDocument = { uri = `current_file_uri` }, range = { + start = `start_position`, end = `end_position` } } *vim.lsp.util.make_position_params()* make_position_params({window}, {offset_encoding}) @@ -1890,14 +1896,14 @@ make_position_params({window}, {offset_encoding}) cursor position. Parameters: ~ - • {window} (integer|nil) window handle or 0 for current, + • {window} (`integer?`) window handle or 0 for current, defaults to current - • {offset_encoding} (string|nil) utf-8|utf-16|utf-32|nil defaults to + • {offset_encoding} (`string?`) utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` Return: ~ - (table) `TextDocumentPositionParams` object + (`table`) `TextDocumentPositionParams` object See also: ~ • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams @@ -1910,25 +1916,25 @@ make_range_params({window}, {offset_encoding}) `textDocument/rangeFormatting`. Parameters: ~ - • {window} (integer|nil) window handle or 0 for current, + • {window} (`integer?`) window handle or 0 for current, defaults to current - • {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults to + • {offset_encoding} (`"utf-8"|"utf-16"|"utf-32"?`) defaults to `offset_encoding` of first client of buffer of `window` Return: ~ - (table) { textDocument = { uri = `current_file_uri` }, range = { start - = `current_position`, end = `current_position` } } + (`table`) { textDocument = { uri = `current_file_uri` }, range = { + start = `current_position`, end = `current_position` } } *vim.lsp.util.make_text_document_params()* make_text_document_params({bufnr}) Creates a `TextDocumentIdentifier` object for the current buffer. Parameters: ~ - • {bufnr} (integer|nil) Buffer handle, defaults to current + • {bufnr} (`integer?`) Buffer handle, defaults to current Return: ~ - (table) `TextDocumentIdentifier` + (`table`) `TextDocumentIdentifier` See also: ~ • https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier @@ -1938,19 +1944,19 @@ make_workspace_params({added}, {removed}) Create the workspace params Parameters: ~ - • {added} (table) - • {removed} (table) + • {added} (`table`) + • {removed} (`table`) *vim.lsp.util.open_floating_preview()* open_floating_preview({contents}, {syntax}, {opts}) Shows contents in a floating window. Parameters: ~ - • {contents} (table) of lines to show in window - • {syntax} (string) of syntax to set for opened buffer - • {opts} (table) with optional fields (additional keys are filtered - with |vim.lsp.util.make_floating_popup_options()| before - they are passed on to |nvim_open_win()|) + • {contents} (`table`) of lines to show in window + • {syntax} (`string`) of syntax to set for opened buffer + • {opts} (`table`) with optional fields (additional keys are + filtered with |vim.lsp.util.make_floating_popup_options()| + before they are passed on to |nvim_open_win()|) • height: (integer) height of floating window • width: (integer) width of floating window • wrap: (boolean, default true) wrap long lines @@ -1968,8 +1974,8 @@ open_floating_preview({contents}, {syntax}, {opts}) window with the same {focus_id} Return (multiple): ~ - (integer) bufnr of newly created float window - (integer) winid of newly created float window preview window + (`integer`) bufnr of newly created float window + (`integer`) winid of newly created float window preview window preview_location({location}, {opts}) *vim.lsp.util.preview_location()* Previews a location in a floating window @@ -1980,33 +1986,33 @@ preview_location({location}, {opts}) *vim.lsp.util.preview_location()* definition) Parameters: ~ - • {location} (table) a single `Location` or `LocationLink` + • {location} (`table`) a single `Location` or `LocationLink` Return (multiple): ~ - (integer|nil) buffer id of float window - (integer|nil) window id of float window + (`integer?`) buffer id of float window + (`integer?`) window id of float window rename({old_fname}, {new_fname}, {opts}) *vim.lsp.util.rename()* Rename old_fname to new_fname Parameters: ~ - • {opts} (table) + • {opts} (`table`) *vim.lsp.util.show_document()* show_document({location}, {offset_encoding}, {opts}) Shows document and optionally jumps to the location. Parameters: ~ - • {location} (table) (`Location`|`LocationLink`) - • {offset_encoding} (string|nil) utf-8|utf-16|utf-32 - • {opts} (table|nil) options + • {location} (`table`) (`Location`|`LocationLink`) + • {offset_encoding} (`string?`) utf-8|utf-16|utf-32 + • {opts} (`table?`) options • reuse_win (boolean) Jump to existing window if buffer is already open. • focus (boolean) Whether to focus/jump to location if possible. Defaults to true. Return: ~ - (boolean) `true` if succeeded + (`boolean`) `true` if succeeded *vim.lsp.util.stylize_markdown()* stylize_markdown({bufnr}, {contents}, {opts}) @@ -2021,8 +2027,8 @@ stylize_markdown({bufnr}, {contents}, {opts}) `open_floating_preview` instead Parameters: ~ - • {contents} (table) of lines to show in window - • {opts} (table) with optional fields + • {contents} (`table`) of lines to show in window + • {opts} (`table`) with optional fields • height of floating window • width of floating window • wrap_at character to wrap at for computing height @@ -2031,13 +2037,13 @@ stylize_markdown({bufnr}, {contents}, {opts}) • separator insert separator after code block Return: ~ - (table) stripped content + (`table`) stripped content symbols_to_items({symbols}, {bufnr}) *vim.lsp.util.symbols_to_items()* Converts symbols to quickfix list items. Parameters: ~ - • {symbols} (table) DocumentSymbol[] or SymbolInformation[] + • {symbols} (`table`) DocumentSymbol[] or SymbolInformation[] ============================================================================== @@ -2047,32 +2053,32 @@ get_filename() *vim.lsp.log.get_filename()* Returns the log filename. Return: ~ - (string) log filename + (`string`) log filename get_level() *vim.lsp.log.get_level()* Gets the current log level. Return: ~ - (integer) current log level + (`integer`) current log level set_format_func({handle}) *vim.lsp.log.set_format_func()* Sets formatting function used to format logs Parameters: ~ - • {handle} (function) function to apply to logging arguments, pass + • {handle} (`function`) function to apply to logging arguments, pass vim.inspect for multi-line formatting set_level({level}) *vim.lsp.log.set_level()* Sets the current log level. Parameters: ~ - • {level} (string|integer) One of `vim.lsp.log.levels` + • {level} (`string|integer`) One of `vim.lsp.log.levels` should_log({level}) *vim.lsp.log.should_log()* Checks whether the level is sufficient for logging. Parameters: ~ - • {level} (integer) log level + • {level} (`integer`) log level Return: ~ (bool) true if would log, false if not @@ -2086,11 +2092,12 @@ connect({host}, {port}) *vim.lsp.rpc.connect()* and port Parameters: ~ - • {host} (string) host to connect to - • {port} (integer) port to connect to + • {host} (`string`) host to connect to + • {port} (`integer`) port to connect to Return: ~ - fun(dispatchers: vim.lsp.rpc.Dispatchers ): vim.lsp.rpc.PublicClient function intended to be passed to |vim.lsp.start_client()| or + (`fun(dispatchers: vim.lsp.rpc.Dispatchers): vim.lsp.rpc.PublicClient`) + function intended to be passed to |vim.lsp.start_client()| or |vim.lsp.start()| on the field cmd *vim.lsp.rpc.domain_socket_connect()* @@ -2100,47 +2107,48 @@ domain_socket_connect({pipe_path}) name on Windows) Parameters: ~ - • {pipe_path} (string) file path of the domain socket (Unix) or name of - the named pipe (Windows) to connect to + • {pipe_path} (`string`) file path of the domain socket (Unix) or name + of the named pipe (Windows) to connect to Return: ~ - fun(dispatchers: vim.lsp.rpc.Dispatchers ): vim.lsp.rpc.PublicClient::function intended to be passed to - |vim.lsp.start_client()| or |vim.lsp.start()| on the field cmd + (`fun(dispatchers: vim.lsp.rpc.Dispatchers): vim.lsp.rpc.PublicClient`) + function intended to be passed to |vim.lsp.start_client()| or + |vim.lsp.start()| on the field cmd format_rpc_error({err}) *vim.lsp.rpc.format_rpc_error()* Constructs an error message from an LSP error object. Parameters: ~ - • {err} (table) The error object + • {err} (`table`) The error object Return: ~ - string::The formatted error message + (`string`) The formatted error message notify({method}, {params}) *vim.lsp.rpc.notify()* Sends a notification to the LSP server. Parameters: ~ - • {method} (string) The invoked LSP method - • {params} (table?) Parameters for the invoked LSP method + • {method} (`string`) The invoked LSP method + • {params} (`table?`) Parameters for the invoked LSP method Return: ~ - (boolean) `true` if notification could be sent, `false` if not + (`boolean`) `true` if notification could be sent, `false` if not *vim.lsp.rpc.request()* request({method}, {params}, {callback}, {notify_reply_callback}) Sends a request to the LSP server and runs {callback} upon response. Parameters: ~ - • {method} (string) The invoked LSP method - • {params} (table?) Parameters for the invoked LSP + • {method} (`string`) The invoked LSP method + • {params} (`table?`) Parameters for the invoked LSP method - • {callback} fun(err: lsp.ResponseError | nil, result: - any) Callback to invoke - • {notify_reply_callback} (function?) Callback to invoke as soon as a + • {callback} (`fun(err: lsp.ResponseError?, result: any)`) + Callback to invoke + • {notify_reply_callback} (`function?`) Callback to invoke as soon as a request is no longer pending Return: ~ - (boolean) success, integer|nil request_id true, message_id if request + (`boolean success, integer? request_id`) true, message_id if request could be sent, `false` if not *vim.lsp.rpc.rpc_response_error()* @@ -2148,12 +2156,12 @@ rpc_response_error({code}, {message}, {data}) Creates an RPC response object/table. Parameters: ~ - • {code} (integer) RPC error code defined by JSON RPC - • {message} (string|nil) arbitrary message to send to server - • {data} any|nil arbitrary data to send to server + • {code} (`integer`) RPC error code defined by JSON RPC + • {message} (`string?`) arbitrary message to send to server + • {data} (`any?`) arbitrary data to send to server Return: ~ - vim.lsp.rpc.Error + (`vim.lsp.rpc.Error`) *vim.lsp.rpc.start()* start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) @@ -2163,17 +2171,17 @@ start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) |vim.lsp.rpc.connect()| Parameters: ~ - • {cmd} (string) Command to start the LSP server. - • {cmd_args} string[] List of additional string arguments to - pass to {cmd}. - • {dispatchers} (table|nil) Dispatchers for LSP message types. + • {cmd} (`string`) Command to start the LSP server. + • {cmd_args} (`string[]`) List of additional string arguments + to pass to {cmd}. + • {dispatchers} (`table?`) Dispatchers for LSP message types. Valid dispatcher names are: • `"notification"` • `"server_request"` • `"on_error"` • `"on_exit"` - • {extra_spawn_params} (table|nil) Additional context for the LSP - server process. May contain: + • {extra_spawn_params} (`table?`) Additional context for the LSP server + process. May contain: • {cwd} (string) Working directory for the LSP server process • {detached?} (boolean) Detach the LSP server @@ -2183,7 +2191,7 @@ start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) variables for LSP server process Return: ~ - (table|nil) client RPC object, with these methods: + (`table?`) client RPC object, with these methods: • `notify()` |vim.lsp.rpc.notify()| • `request()` |vim.lsp.rpc.request()| • `is_closing()` returns a boolean indicating if the RPC is closing. @@ -2199,7 +2207,7 @@ make_client_capabilities() capabilities. Return: ~ - lsp.ClientCapabilities + (`lsp.ClientCapabilities`) Methods *vim.lsp.protocol.Methods* LSP method names. @@ -2212,10 +2220,10 @@ resolve_capabilities({server_capabilities}) Creates a normalized object describing LSP server capabilities. Parameters: ~ - • {server_capabilities} (table) Table of capabilities supported by the - server + • {server_capabilities} (`table`) Table of capabilities supported by + the server Return: ~ - lsp.ServerCapabilities|nil Normalized table of capabilities + (`lsp.ServerCapabilities?`) Normalized table of capabilities vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index e01e16b8f4..aadc73e95c 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -606,7 +606,7 @@ vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* Highlight the yanked text Parameters: ~ - • {opts} (table|nil) Optional parameters + • {opts} (`table?`) Optional parameters • higroup highlight group for yanked region (default "IncSearch") • timeout time in ms before highlight is cleared (default 150) @@ -631,14 +631,14 @@ vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts}) Apply highlight group to range of text. Parameters: ~ - • {bufnr} (integer) Buffer number to apply highlighting to - • {ns} (integer) Namespace to add highlight to - • {higroup} (string) Highlight group to use for highlighting - • {start} integer[]|string Start of region as a (line, column) tuple - or string accepted by |getpos()| - • {finish} integer[]|string End of region as a (line, column) tuple or - string accepted by |getpos()| - • {opts} (table|nil) Optional parameters + • {bufnr} (`integer`) Buffer number to apply highlighting to + • {ns} (`integer`) Namespace to add highlight to + • {higroup} (`string`) Highlight group to use for highlighting + • {start} (`integer[]|string`) Start of region as a (line, column) + tuple or string accepted by |getpos()| + • {finish} (`integer[]|string`) End of region as a (line, column) + tuple or string accepted by |getpos()| + • {opts} (`table?`) Optional parameters • regtype type of range (see |setreg()|, default charwise) • inclusive boolean indicating whether the range is end-inclusive (default false) @@ -660,10 +660,10 @@ vim.regex({re}) *vim.regex()* They can be controlled with flags, see |/magic| and |/ignorecase|. Parameters: ~ - • {re} (string) + • {re} (`string`) Return: ~ - vim.regex + (`vim.regex`) *regex:match_line()* vim.regex:match_line({bufnr}, {line_idx}, {start}, {end_}) @@ -673,18 +673,20 @@ vim.regex:match_line({bufnr}, {line_idx}, {start}, {end_}) will be relative {start}. Parameters: ~ - • {bufnr} (integer) - • {line_idx} (integer) - • {start} (integer|nil) - • {end_} (integer|nil) + • {bufnr} (`integer`) + • {line_idx} (`integer`) + • {start} (`integer?`) + • {end_} (`integer?`) vim.regex:match_str({str}) *regex:match_str()* Match the string against the regex. If the string should match the regex - precisely, surround the regex with `^` and `$` . If there was a match, the byte indices for the beginning and end of the - match are returned. When there is no match, `nil` is returned. Because any integer is "truthy", `regex:match_str()` can be directly used as a condition in an if-statement. + precisely, surround the regex with `^` and `$` . If there was a match, the + byte indices for the beginning and end of the match are returned. When + there is no match, `nil` is returned. Because any integer is "truthy", `regex:match_str()` can + be directly used as a condition in an if-statement. Parameters: ~ - • {str} (string) + • {str} (`string`) ============================================================================== @@ -710,12 +712,12 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* < Parameters: ~ - • {a} (string) First string to compare - • {b} (string) Second string to compare - • {opts} table<string,any> Optional parameters: - • `on_hunk` (callback): Invoked for each hunk in the diff. Return a - negative number to cancel the callback for any remaining - hunks. Args: + • {a} (`string`) First string to compare + • {b} (`string`) Second string to compare + • {opts} (`table<string,any>`) Optional parameters: + • `on_hunk` (callback): Invoked for each hunk in the diff. + Return a negative number to cancel the callback for any + remaining hunks. Args: • `start_a` (integer): Start line of hunk in {a}. • `count_a` (integer): Hunk size in {a}. • `start_b` (integer): Start line of hunk in {b}. @@ -751,7 +753,7 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* the internal diff library. Return: ~ - string|table|nil See {opts.result_type}. `nil` if {opts.on_hunk} is + (`string|table?`) See {opts.result_type}. `nil` if {opts.on_hunk} is given. @@ -766,7 +768,7 @@ vim.mpack.decode({str}) *vim.mpack.decode()* Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object. Parameters: ~ - • {str} (string) + • {str} (`string`) vim.mpack.encode({obj}) *vim.mpack.encode()* Encodes (or "packs") Lua object {obj} as msgpack in a Lua string. @@ -792,8 +794,8 @@ vim.json.decode({str}, {opts}) *vim.json.decode()* < Parameters: ~ - • {str} (string) Stringified JSON data. - • {opts} table<string,any>|nil Options table with keys: + • {str} (`string`) Stringified JSON data. + • {opts} (`table<string,any>?`) Options table with keys: • luanil: (table) Table with keys: • object: (boolean) When true, converts `null` in JSON objects to Lua `nil` instead of |vim.NIL|. @@ -801,16 +803,16 @@ vim.json.decode({str}, {opts}) *vim.json.decode()* to Lua `nil` instead of |vim.NIL|. Return: ~ - any + (`any`) vim.json.encode({obj}) *vim.json.encode()* Encodes (or "packs") Lua object {obj} as JSON in a Lua string. Parameters: ~ - • {obj} any + • {obj} (`any`) Return: ~ - (string) + (`string`) ============================================================================== @@ -820,19 +822,19 @@ vim.base64.decode({str}) *vim.base64.decode()* Decode a Base64 encoded string. Parameters: ~ - • {str} (string) Base64 encoded string + • {str} (`string`) Base64 encoded string Return: ~ - (string) Decoded string + (`string`) Decoded string vim.base64.encode({str}) *vim.base64.encode()* Encode {str} using Base64. Parameters: ~ - • {str} (string) String to encode + • {str} (`string`) String to encode Return: ~ - (string) Encoded string + (`string`) Encoded string ============================================================================== @@ -855,10 +857,11 @@ vim.spell.check({str}) *vim.spell.check()* < Parameters: ~ - • {str} (string) + • {str} (`string`) Return: ~ - `{[1]: string, [2]: string, [3]: string}[]` List of tuples with three items: + (`{[1]: string, [2]: string, [3]: string}[]`) List of tuples with + three items: • The badly spelled word. • The type of the spelling error: "bad" spelling mistake "rare" rare word "local" word only valid in another region "caps" word should @@ -942,13 +945,13 @@ vim.iconv({str}, {from}, {to}, {opts}) *vim.iconv()* ":Man 3 iconv". Parameters: ~ - • {str} (string) Text to convert - • {from} (number) Encoding of {str} - • {to} (number) Target encoding - • {opts} table<string,any>|nil + • {str} (`string`) Text to convert + • {from} (`number`) Encoding of {str} + • {to} (`number`) Target encoding + • {opts} (`table<string,any>?`) Return: ~ - (string|nil) Converted string if conversion succeeds, `nil` otherwise. + (`string?`) Converted string if conversion succeeds, `nil` otherwise. vim.in_fast_event() *vim.in_fast_event()* Returns true if the code is executing as part of a "fast" event handler, @@ -964,10 +967,10 @@ vim.rpcnotify({channel}, {method}, {args}, {...}) *vim.rpcnotify()* This function also works in a fast callback |lua-loop-callbacks|. Parameters: ~ - • {channel} (integer) - • {method} (string) - • {args} any[]|nil - • {...} any|nil + • {channel} (`integer`) + • {method} (`string`) + • {args} (`any[]?`) + • {...} (`any?`) vim.rpcrequest({channel}, {method}, {args}, {...}) *vim.rpcrequest()* Sends a request to {channel} to invoke {method} via |RPC| and blocks until @@ -977,17 +980,17 @@ vim.rpcrequest({channel}, {method}, {args}, {...}) *vim.rpcrequest()* special value Parameters: ~ - • {channel} (integer) - • {method} (string) - • {args} any[]|nil - • {...} any|nil + • {channel} (`integer`) + • {method} (`string`) + • {args} (`any[]?`) + • {...} (`any?`) vim.schedule({fn}) *vim.schedule()* Schedules {fn} to be invoked soon by the main event-loop. Useful to avoid |textlock| or other temporary restrictions. Parameters: ~ - • {fn} (function) + • {fn} (`function`) vim.str_byteindex({str}, {index}, {use_utf16}) *vim.str_byteindex()* Convert UTF-32 or UTF-16 {index} to byte index. If {use_utf16} is not @@ -998,9 +1001,9 @@ vim.str_byteindex({str}, {index}, {use_utf16}) *vim.str_byteindex()* sequence. Parameters: ~ - • {str} (string) - • {index} (number) - • {use_utf16} any|nil + • {str} (`string`) + • {index} (`number`) + • {use_utf16} (`any?`) vim.str_utf_end({str}, {index}) *vim.str_utf_end()* Gets the distance (in bytes) from the last byte of the codepoint @@ -1017,11 +1020,11 @@ vim.str_utf_end({str}, {index}) *vim.str_utf_end()* < Parameters: ~ - • {str} (string) - • {index} (number) + • {str} (`string`) + • {index} (`number`) Return: ~ - (number) + (`number`) vim.str_utf_pos({str}) *vim.str_utf_pos()* Gets a list of the starting byte positions of each UTF-8 codepoint in the @@ -1030,10 +1033,10 @@ vim.str_utf_pos({str}) *vim.str_utf_pos()* Embedded NUL bytes are treated as terminating the string. Parameters: ~ - • {str} (string) + • {str} (`string`) Return: ~ - (table) + (`table`) vim.str_utf_start({str}, {index}) *vim.str_utf_start()* Gets the distance (in bytes) from the starting byte of the codepoint @@ -1053,11 +1056,11 @@ vim.str_utf_start({str}, {index}) *vim.str_utf_start()* < Parameters: ~ - • {str} (string) - • {index} (number) + • {str} (`string`) + • {index} (`number`) Return: ~ - (number) + (`number`) vim.str_utfindex({str}, {index}) *vim.str_utfindex()* Convert byte index to UTF-32 and UTF-16 indices. If {index} is not @@ -1069,23 +1072,23 @@ vim.str_utfindex({str}, {index}) *vim.str_utfindex()* that sequence. Parameters: ~ - • {str} (string) - • {index} (number|nil) + • {str} (`string`) + • {index} (`number?`) Return (multiple): ~ - (integer) UTF-32 index - (integer) UTF-16 index + (`integer`) UTF-32 index + (`integer`) UTF-16 index vim.stricmp({a}, {b}) *vim.stricmp()* Compares strings case-insensitively. Parameters: ~ - • {a} (string) - • {b} (string) + • {a} (`string`) + • {b} (`string`) Return: ~ - 0|1|-1 if strings are equal, {a} is greater than {b} or {a} is lesser - than {b}, respectively. + (`0|1|-1`) if strings are equal, {a} is greater than {b} or {a} is + lesser than {b}, respectively. vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* Attach to ui events, similar to |nvim_ui_attach()| but receive events as @@ -1123,16 +1126,16 @@ vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* < Parameters: ~ - • {ns} (integer) - • {options} table<string, any> - • {callback} fun() + • {ns} (`integer`) + • {options} (`table<string, any>`) + • {callback} (`fun()`) vim.ui_detach({ns}) *vim.ui_detach()* Detach a callback previously attached with |vim.ui_attach()| for the given namespace {ns}. Parameters: ~ - • {ns} (integer) + • {ns} (`integer`) vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()* Wait for {time} in milliseconds until {callback} returns `true`. @@ -1167,16 +1170,16 @@ vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()* < Parameters: ~ - • {time} (integer) Number of milliseconds to wait - • {callback} fun():|nil boolean Optional callback. Waits until + • {time} (`integer`) Number of milliseconds to wait + • {callback} (`fun(): boolean?`) Optional callback. Waits until {callback} returns true - • {interval} (integer|nil) (Approximate) number of milliseconds to - wait between polls - • {fast_only} (boolean|nil) If true, only |api-fast| events will be + • {interval} (`integer?`) (Approximate) number of milliseconds to wait + between polls + • {fast_only} (`boolean?`) If true, only |api-fast| events will be processed. Return: ~ - boolean, nil|-1|-2 + (`boolean, -1|-2?`) • If {callback} returns `true` during the {time}: `true, nil` • If {callback} never returns `true` during the {time}: `false, -1` • If {callback} is interrupted during the {time}: `false, -2` @@ -1373,7 +1376,7 @@ Option:append({value}) *vim.opt:append()* < Parameters: ~ - • {value} (string) Value to append + • {value} (`string`) Value to append Option:get() *vim.opt:get()* Returns a Lua-representation of the option. Boolean, number and string @@ -1419,7 +1422,7 @@ Option:get() *vim.opt:get()* < Return: ~ - string|integer|boolean|nil value of option + (`string|integer|boolean?`) value of option Option:prepend({value}) *vim.opt:prepend()* Prepend a value to string-style options. See |:set^=| @@ -1430,7 +1433,7 @@ Option:prepend({value}) *vim.opt:prepend()* < Parameters: ~ - • {value} (string) Value to prepend + • {value} (`string`) Value to prepend Option:remove({value}) *vim.opt:remove()* Remove a value from string-style options. See |:set-=| @@ -1441,7 +1444,7 @@ Option:remove({value}) *vim.opt:remove()* < Parameters: ~ - • {value} (string) Value to remove + • {value} (`string`) Value to remove vim.bo *vim.bo* Get or set buffer-scoped |options| for the buffer with number {bufnr}. @@ -1468,7 +1471,7 @@ vim.env *vim.env* < Parameters: ~ - • {var} (string) + • {var} (`string`) vim.go *vim.go* Get or set global |options|. Like `:setglobal`. Invalid key is an error. @@ -1550,12 +1553,12 @@ vim.cmd *vim.cmd()* < Parameters: ~ - • {command} string|table Command(s) to execute. If a string, executes - multiple lines of Vim script at once. In this case, it is - an alias to |nvim_exec2()|, where `opts.output` is set to - false. Thus it works identical to |:source|. If a table, - executes a single command. In this case, it is an alias to - |nvim_cmd()| where `opts` is empty. + • {command} (`string|table`) Command(s) to execute. If a string, + executes multiple lines of Vim script at once. In this + case, it is an alias to |nvim_exec2()|, where `opts.output` + is set to false. Thus it works identical to |:source|. If a + table, executes a single command. In this case, it is an + alias to |nvim_cmd()| where `opts` is empty. See also: ~ • |ex-cmd-index| @@ -1567,33 +1570,34 @@ vim.defer_fn({fn}, {timeout}) *vim.defer_fn()* |vim.schedule_wrap()|ped automatically, so API functions are safe to call. Parameters: ~ - • {fn} (function) Callback to call once `timeout` expires - • {timeout} (integer) Number of milliseconds to wait before calling + • {fn} (`function`) Callback to call once `timeout` expires + • {timeout} (`integer`) Number of milliseconds to wait before calling `fn` Return: ~ - (table) timer luv timer object + (`table`) timer luv timer object *vim.deprecate()* vim.deprecate({name}, {alternative}, {version}, {plugin}, {backtrace}) Shows a deprecation message to the user. Parameters: ~ - • {name} string Deprecated feature (function, API, etc.). - • {alternative} (string|nil) Suggested alternative feature. - • {version} string Version when the deprecated function will be removed. - • {plugin} string|nil Name of the plugin that owns the deprecated + • {name} (`string`) Deprecated feature (function, API, etc.). + • {alternative} (`string?`) Suggested alternative feature. + • {version} (`string`) Version when the deprecated function will be + removed. + • {plugin} (`string?`) Name of the plugin that owns the deprecated feature. Defaults to "Nvim". - • {backtrace} boolean|nil Prints backtrace. Defaults to true. + • {backtrace} (`boolean?`) Prints backtrace. Defaults to true. Return: ~ - (string|nil) Deprecated message, or nil if no message was shown. + (`string?`) Deprecated message, or nil if no message was shown. vim.inspect *vim.inspect()* Gets a human-readable representation of the given object. Return: ~ - (string) + (`string`) See also: ~ • |vim.print()| @@ -1609,10 +1613,10 @@ vim.keycode({str}) *vim.keycode()* < Parameters: ~ - • {str} (string) String to be converted. + • {str} (`string`) String to be converted. Return: ~ - (string) + (`string`) See also: ~ • |nvim_replace_termcodes()| @@ -1631,9 +1635,9 @@ vim.notify({msg}, {level}, {opts}) *vim.notify()* writes to |:messages|. Parameters: ~ - • {msg} (string) Content of the notification to show to the user. - • {level} (integer|nil) One of the values from |vim.log.levels|. - • {opts} (table|nil) Optional parameters. Unused by default. + • {msg} (`string`) Content of the notification to show to the user. + • {level} (`integer?`) One of the values from |vim.log.levels|. + • {opts} (`table?`) Optional parameters. Unused by default. vim.notify_once({msg}, {level}, {opts}) *vim.notify_once()* Displays a notification only one time. @@ -1642,12 +1646,12 @@ vim.notify_once({msg}, {level}, {opts}) *vim.notify_once()* display a notification. Parameters: ~ - • {msg} (string) Content of the notification to show to the user. - • {level} (integer|nil) One of the values from |vim.log.levels|. - • {opts} (table|nil) Optional parameters. Unused by default. + • {msg} (`string`) Content of the notification to show to the user. + • {level} (`integer?`) One of the values from |vim.log.levels|. + • {opts} (`table?`) Optional parameters. Unused by default. Return: ~ - (boolean) true if message was displayed, else false + (`boolean`) true if message was displayed, else false vim.on_key({fn}, {ns_id}) *vim.on_key()* Adds Lua function {fn} with namespace id {ns_id} as a listener to every, @@ -1662,15 +1666,15 @@ vim.on_key({fn}, {ns_id}) *vim.on_key()* • {fn} will receive the keys after mappings have been evaluated Parameters: ~ - • {fn} fun(key: string) Function invoked on every key press. + • {fn} (`fun(key: string)`) Function invoked on every key press. |i_CTRL-V| Returning nil removes the callback associated with namespace {ns_id}. - • {ns_id} integer? Namespace ID. If nil or 0, generates and returns a - new |nvim_create_namespace()| id. + • {ns_id} (`integer?`) Namespace ID. If nil or 0, generates and returns + a new |nvim_create_namespace()| id. Return: ~ - (integer) Namespace id associated with {fn}. Or count of all callbacks - if on_key() is called without arguments. + (`integer`) Namespace id associated with {fn}. Or count of all + callbacks if on_key() is called without arguments. vim.paste({lines}, {phase}) *vim.paste()* Paste handler, invoked by |nvim_paste()| when a conforming UI (such as the @@ -1689,19 +1693,20 @@ vim.paste({lines}, {phase}) *vim.paste()* < Parameters: ~ - • {lines} string[] # |readfile()|-style list of lines to paste. + • {lines} (`string[]`) |readfile()|-style list of lines to paste. |channel-lines| - • {phase} paste_phase -1: "non-streaming" paste: the call contains all - lines. If paste is "streamed", `phase` indicates the stream state: + • {phase} (`-1|1|2|3`) -1: "non-streaming" paste: the call contains all + lines. If paste is "streamed", `phase` indicates + the stream state: • 1: starts the paste (exactly once) • 2: continues the paste (zero or more times) • 3: ends the paste (exactly once) Return: ~ - (boolean) result false if client should cancel the paste. + (`boolean`) result false if client should cancel the paste. See also: ~ - • |paste| @alias paste_phase -1 | 1 | 2 | 3 + • |paste| vim.print({...}) *vim.print()* "Pretty prints" the given arguments and returns them unmodified. @@ -1711,7 +1716,7 @@ vim.print({...}) *vim.print()* < Return: ~ - any given arguments. + (`any`) given arguments. See also: ~ • |vim.inspect()| @@ -1727,17 +1732,17 @@ vim.region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) returned as |v:maxcol| (big number). Parameters: ~ - • {bufnr} (integer) Buffer number, or 0 for current buffer - • {pos1} integer[]|string Start of region as a (line, column) + • {bufnr} (`integer`) Buffer number, or 0 for current buffer + • {pos1} (`integer[]|string`) Start of region as a (line, column) tuple or |getpos()|-compatible string - • {pos2} integer[]|string End of region as a (line, column) tuple - or |getpos()|-compatible string - • {regtype} (string) |setreg()|-style selection type - • {inclusive} (boolean) Controls whether the ending column is inclusive - (see also 'selection'). + • {pos2} (`integer[]|string`) End of region as a (line, column) + tuple or |getpos()|-compatible string + • {regtype} (`string`) |setreg()|-style selection type + • {inclusive} (`boolean`) Controls whether the ending column is + inclusive (see also 'selection'). Return: ~ - (table) region Dict of the form `{linenr = {startcol,endcol}}`. + (`table`) region Dict of the form `{linenr = {startcol,endcol}}`. `endcol` is exclusive, and whole lines are returned as `{startcol,endcol} = {0,-1}`. @@ -1754,10 +1759,10 @@ vim.schedule_wrap({fn}) *vim.schedule_wrap()* < Parameters: ~ - • {fn} (function) + • {fn} (`function`) Return: ~ - (function) + (`function`) See also: ~ • |lua-loop-callbacks| @@ -1787,8 +1792,8 @@ vim.system({cmd}, {opts}, {on_exit}) *vim.system()* throws an error if {cmd} cannot be run. Parameters: ~ - • {cmd} (string[]) Command to execute - • {opts} (SystemOpts|nil) Options: + • {cmd} (`string[]`) Command to execute + • {opts} (`vim.SystemOpts?`) Options: • cwd: (string) Set the current working directory for the sub-process. • env: table<string,string> Set environment variables for @@ -1818,12 +1823,13 @@ vim.system({cmd}, {opts}, {on_exit}) *vim.system()* process will still keep the parent's event loop alive unless the parent process calls |uv.unref()| on the child's process handle. - • {on_exit} (function|nil) Called when subprocess exits. When provided, - the command runs asynchronously. Receives SystemCompleted - object, see return of SystemObj:wait(). + • {on_exit} (`fun(out: vim.SystemCompleted)?`) Called when subprocess + exits. When provided, the command runs asynchronously. + Receives SystemCompleted object, see return of + SystemObj:wait(). Return: ~ - vim.SystemObj Object with the fields: + (`vim.SystemObj`) Object with the fields: • pid (integer) Process ID • wait (fun(timeout: integer|nil): SystemCompleted) Wait for the process to complete. Upon timeout the process is sent the KILL @@ -1850,12 +1856,12 @@ vim.inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()* Can also be pretty-printed with `:Inspect!`. *:Inspect!* Parameters: ~ - • {bufnr} (integer|nil) defaults to the current buffer - • {row} (integer|nil) row to inspect, 0-based. Defaults to the row - of the current cursor - • {col} (integer|nil) col to inspect, 0-based. Defaults to the col - of the current cursor - • {filter} (table|nil) a table with key-value pairs to filter the items + • {bufnr} (`integer?`) defaults to the current buffer + • {row} (`integer?`) row to inspect, 0-based. Defaults to the row of + the current cursor + • {col} (`integer?`) col to inspect, 0-based. Defaults to the col of + the current cursor + • {filter} (`table?`) a table with key-value pairs to filter the items • syntax (boolean): include syntax based highlight groups (defaults to true) • treesitter (boolean): include treesitter based highlight @@ -1867,7 +1873,7 @@ vim.inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()* (defaults to true) Return: ~ - (table) a table with the following key-value pairs. Items are in + (`table`) a table with the following key-value pairs. Items are in "traversal order": • treesitter: a list of treesitter captures • syntax: a list of syntax groups @@ -1883,12 +1889,12 @@ vim.show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()* Can also be shown with `:Inspect`. *:Inspect* Parameters: ~ - • {bufnr} (integer|nil) defaults to the current buffer - • {row} (integer|nil) row to inspect, 0-based. Defaults to the row - of the current cursor - • {col} (integer|nil) col to inspect, 0-based. Defaults to the col - of the current cursor - • {filter} (table|nil) see |vim.inspect_pos()| + • {bufnr} (`integer?`) defaults to the current buffer + • {row} (`integer?`) row to inspect, 0-based. Defaults to the row of + the current cursor + • {col} (`integer?`) col to inspect, 0-based. Defaults to the col of + the current cursor + • {filter} (`table?`) see |vim.inspect_pos()| @@ -1896,14 +1902,15 @@ vim.show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()* vim.deep_equal({a}, {b}) *vim.deep_equal()* Deep compare values for equality - Tables are compared recursively unless they both provide the `eq` metamethod. All other types are compared using the equality `==` operator. + Tables are compared recursively unless they both provide the `eq` metamethod. + All other types are compared using the equality `==` operator. Parameters: ~ - • {a} any First value - • {b} any Second value + • {a} (`any`) First value + • {b} (`any`) Second value Return: ~ - (boolean) `true` if values are equals, else `false` + (`boolean`) `true` if values are equals, else `false` vim.deepcopy({orig}, {noref}) *vim.deepcopy()* Returns a deep copy of the given object. Non-table objects are copied as @@ -1917,15 +1924,15 @@ vim.deepcopy({orig}, {noref}) *vim.deepcopy()* fields. Parameters: ~ - • {orig} (table) Table to copy - • {noref} (boolean|nil) When `false` (default) a contained table is - only copied once and all references point to this single - copy. When `true` every occurrence of a table results in a - new copy. This also means that a cyclic reference can cause + • {orig} (`table`) Table to copy + • {noref} (`boolean?`) When `false` (default) a contained table is only + copied once and all references point to this single copy. + When `true` every occurrence of a table results in a new + copy. This also means that a cyclic reference can cause `deepcopy()` to fail. Return: ~ - (table) Table of copied keys and (nested) values. + (`table`) Table of copied keys and (nested) values. vim.defaulttable({createfn}) *vim.defaulttable()* Creates a table whose missing keys are provided by {createfn} (like @@ -1938,21 +1945,21 @@ vim.defaulttable({createfn}) *vim.defaulttable()* < Parameters: ~ - • {createfn} function?(key:any):any Provides the value for a missing + • {createfn} (`fun(key:any):any?`) Provides the value for a missing `key`. Return: ~ - (table) Empty table with `__index` metamethod. + (`table`) Empty table with `__index` metamethod. vim.endswith({s}, {suffix}) *vim.endswith()* Tests if `s` ends with `suffix`. Parameters: ~ - • {s} (string) String - • {suffix} (string) Suffix to match + • {s} (`string`) String + • {suffix} (`string`) Suffix to match Return: ~ - (boolean) `true` if `suffix` is a suffix of `s` + (`boolean`) `true` if `suffix` is a suffix of `s` vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()* Gets an |iterator| that splits a string at each instance of a separator, @@ -1972,15 +1979,15 @@ vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()* < Parameters: ~ - • {s} (string) String to split - • {sep} (string) Separator or pattern - • {opts} (table|nil) Keyword arguments |kwargs|: + • {s} (`string`) String to split + • {sep} (`string`) Separator or pattern + • {opts} (`table?`) Keyword arguments |kwargs|: • plain: (boolean) Use `sep` literally (as in string.find). • trimempty: (boolean) Discard empty segments at start and end of the sequence. Return: ~ - (function) Iterator over the split components + (`function`) Iterator over the split components See also: ~ • |string.gmatch()| @@ -1993,20 +2000,20 @@ vim.is_callable({f}) *vim.is_callable()* Returns true if object `f` can be called as a function. Parameters: ~ - • {f} any Any object + • {f} (`any`) Any object Return: ~ - (boolean) `true` if `f` is callable, else `false` + (`boolean`) `true` if `f` is callable, else `false` vim.list_contains({t}, {value}) *vim.list_contains()* Checks if a list-like table (integer keys without gaps) contains `value`. Parameters: ~ - • {t} (table) Table to check (must be list-like, not validated) - • {value} any Value to compare + • {t} (`table`) Table to check (must be list-like, not validated) + • {value} (`any`) Value to compare Return: ~ - (boolean) `true` if `t` contains `value` + (`boolean`) `true` if `t` contains `value` See also: ~ • |vim.tbl_contains()| for checking values in general tables @@ -2017,13 +2024,13 @@ vim.list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()* NOTE: This mutates dst! Parameters: ~ - • {dst} (table) List which will be modified and appended to - • {src} (table) List from which values will be inserted - • {start} (integer|nil) Start index on src. Defaults to 1 - • {finish} (integer|nil) Final index on src. Defaults to `#src` + • {dst} (`table`) List which will be modified and appended to + • {src} (`table`) List from which values will be inserted + • {start} (`integer?`) Start index on src. Defaults to 1 + • {finish} (`integer?`) Final index on src. Defaults to `#src` Return: ~ - (table) dst + (`table`) dst See also: ~ • |vim.tbl_extend()| @@ -2033,21 +2040,21 @@ vim.list_slice({list}, {start}, {finish}) *vim.list_slice()* (inclusive) Parameters: ~ - • {list} (list) Table - • {start} (integer|nil) Start range of slice - • {finish} (integer|nil) End range of slice + • {list} (`list`) Table + • {start} (`integer?`) Start range of slice + • {finish} (`integer?`) End range of slice Return: ~ - (list) Copy of table sliced from start to finish (inclusive) + (`list`) Copy of table sliced from start to finish (inclusive) vim.pesc({s}) *vim.pesc()* Escapes magic chars in |lua-patterns|. Parameters: ~ - • {s} (string) String to escape + • {s} (`string`) String to escape Return: ~ - (string) %-escaped pattern string + (`string`) %-escaped pattern string See also: ~ • https://github.com/rxi/lume @@ -2078,10 +2085,10 @@ vim.ringbuf({size}) *vim.ringbuf()* • |Ringbuf:clear()| Parameters: ~ - • {size} (integer) + • {size} (`integer`) Return: ~ - (table) + (`table`) vim.Ringbuf:clear() *Ringbuf:clear()* Clear all items. @@ -2090,28 +2097,28 @@ vim.Ringbuf:peek() *Ringbuf:peek()* Returns the first unread item without removing it Return: ~ - any?|nil + (`any?`) vim.Ringbuf:pop() *Ringbuf:pop()* Removes and returns the first unread item Return: ~ - any?|nil + (`any?`) vim.Ringbuf:push({item}) *Ringbuf:push()* Adds an item, overriding the oldest item if the buffer is full. Parameters: ~ - • {item} any + • {item} (`any`) vim.spairs({t}) *vim.spairs()* Enumerates key-value pairs of a table, ordered by key. Parameters: ~ - • {t} (table) Dict-like table + • {t} (`table`) Dict-like table Return: ~ - (function) |for-in| iterator over sorted keys and their values + (`function`) |for-in| iterator over sorted keys and their values See also: ~ • Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua @@ -2128,13 +2135,13 @@ vim.split({s}, {sep}, {opts}) *vim.split()* < Parameters: ~ - • {s} (string) String to split - • {sep} (string) Separator or pattern - • {opts} (table|nil) Keyword arguments |kwargs| accepted by + • {s} (`string`) String to split + • {sep} (`string`) Separator or pattern + • {opts} (`table?`) Keyword arguments |kwargs| accepted by |vim.gsplit()| Return: ~ - string[] List of split components + (`string[]`) List of split components See also: ~ • |vim.gsplit()| @@ -2144,11 +2151,11 @@ vim.startswith({s}, {prefix}) *vim.startswith()* Tests if `s` starts with `prefix`. Parameters: ~ - • {s} (string) String - • {prefix} (string) Prefix to match + • {s} (`string`) String + • {prefix} (`string`) Prefix to match Return: ~ - (boolean) `true` if `prefix` is a prefix of `s` + (`boolean`) `true` if `prefix` is a prefix of `s` vim.tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()* Add the reverse lookup values to an existing table. For example: @@ -2157,10 +2164,10 @@ vim.tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()* Note that this modifies the input. Parameters: ~ - • {o} (table) Table to add the reverse to + • {o} (`table`) Table to add the reverse to Return: ~ - (table) o + (`table`) o vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()* Checks if a table contains a given value, specified either directly or via @@ -2174,14 +2181,14 @@ vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()* < Parameters: ~ - • {t} (table) Table to check - • {value} any Value to compare or predicate function reference - • {opts} (table|nil) Keyword arguments |kwargs|: + • {t} (`table`) Table to check + • {value} (`any`) Value to compare or predicate function reference + • {opts} (`table?`) Keyword arguments |kwargs|: • predicate: (boolean) `value` is a function reference to be checked (default false) Return: ~ - (boolean) `true` if `t` contains `value` + (`boolean`) `true` if `t` contains `value` See also: ~ • |vim.list_contains()| for checking values in list-like tables @@ -2193,10 +2200,10 @@ vim.tbl_count({t}) *vim.tbl_count()* < Parameters: ~ - • {t} (table) Table + • {t} (`table`) Table Return: ~ - (integer) Number of non-nil values in table + (`integer`) Number of non-nil values in table See also: ~ • https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua @@ -2205,15 +2212,15 @@ vim.tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()* Merges recursively two or more tables. Parameters: ~ - • {behavior} (string) Decides what to do if a key is found in more than - one map: + • {behavior} (`string`) Decides what to do if a key is found in more + than one map: • "error": raise an error • "keep": use value from the leftmost map • "force": use value from the rightmost map - • {...} (table) Two or more tables + • {...} (`table`) Two or more tables Return: ~ - (table) Merged table + (`table`) Merged table See also: ~ • |vim.tbl_extend()| @@ -2222,15 +2229,15 @@ vim.tbl_extend({behavior}, {...}) *vim.tbl_extend()* Merges two or more tables. Parameters: ~ - • {behavior} (string) Decides what to do if a key is found in more than - one map: + • {behavior} (`string`) Decides what to do if a key is found in more + than one map: • "error": raise an error • "keep": use value from the leftmost map • "force": use value from the rightmost map - • {...} (table) Two or more tables + • {...} (`table`) Two or more tables Return: ~ - (table) Merged table + (`table`) Merged table See also: ~ • |extend()| @@ -2239,21 +2246,21 @@ vim.tbl_filter({func}, {t}) *vim.tbl_filter()* Filter a table using a predicate function Parameters: ~ - • {func} (function) Function - • {t} (table) Table + • {func} (`function`) Function + • {t} (`table`) Table Return: ~ - (table) Table of filtered values + (`table`) Table of filtered values vim.tbl_flatten({t}) *vim.tbl_flatten()* Creates a copy of a list-like table such that any nested tables are "unrolled" and appended to the result. Parameters: ~ - • {t} (table) List-like table + • {t} (`table`) List-like table Return: ~ - (table) Flattened copy of the given list-like table + (`table`) Flattened copy of the given list-like table See also: ~ • From https://github.com/premake/premake-core/blob/master/src/base/table.lua @@ -2268,15 +2275,16 @@ vim.tbl_get({o}, {...}) *vim.tbl_get()* < Parameters: ~ - • {o} (table) Table to index - • {...} any Optional keys (0 or more, variadic) via which to index the - table + • {o} (`table`) Table to index + • {...} (`any`) Optional keys (0 or more, variadic) via which to index + the table Return: ~ - any Nested value indexed by key (if it exists), else nil + (`any`) Nested value indexed by key (if it exists), else nil vim.tbl_isarray({t}) *vim.tbl_isarray()* - Tests if `t` is an "array": a table indexed only by integers (potentially non-contiguous). + Tests if `t` is an "array": a table indexed only by integers (potentially + non-contiguous). If the indexes start from 1 and are contiguous then the array is also a list. |vim.tbl_islist()| @@ -2286,10 +2294,10 @@ vim.tbl_isarray({t}) *vim.tbl_isarray()* |rpcrequest()| or |vim.fn|. Parameters: ~ - • {t} (table) + • {t} (`table`) Return: ~ - (boolean) `true` if array-like table, else `false`. + (`boolean`) `true` if array-like table, else `false`. See also: ~ • https://github.com/openresty/luajit2#tableisarray @@ -2298,27 +2306,27 @@ vim.tbl_isempty({t}) *vim.tbl_isempty()* Checks if a table is empty. Parameters: ~ - • {t} (table) Table to check + • {t} (`table`) Table to check Return: ~ - (boolean) `true` if `t` is empty + (`boolean`) `true` if `t` is empty See also: ~ • https://github.com/premake/premake-core/blob/master/src/base/table.lua vim.tbl_islist({t}) *vim.tbl_islist()* - Tests if `t` is a "list": a table indexed only by contiguous integers starting from 1 (what |lua-length| calls a "regular - array"). + Tests if `t` is a "list": a table indexed only by contiguous integers + starting from 1 (what |lua-length| calls a "regular array"). Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|. Parameters: ~ - • {t} (table) + • {t} (`table`) Return: ~ - (boolean) `true` if list-like table, else `false`. + (`boolean`) `true` if list-like table, else `false`. See also: ~ • |vim.tbl_isarray()| @@ -2328,10 +2336,10 @@ vim.tbl_keys({t}) *vim.tbl_keys()* return table of keys is not guaranteed. Parameters: ~ - • {t} (table) Table + • {t} (`table`) Table Return: ~ - (list) List of keys + (`list`) List of keys See also: ~ • From https://github.com/premake/premake-core/blob/master/src/base/table.lua @@ -2340,30 +2348,30 @@ vim.tbl_map({func}, {t}) *vim.tbl_map()* Apply a function to all values of a table. Parameters: ~ - • {func} (function) Function - • {t} (table) Table + • {func} (`function`) Function + • {t} (`table`) Table Return: ~ - (table) Table of transformed values + (`table`) Table of transformed values vim.tbl_values({t}) *vim.tbl_values()* Return a list of all values used in a table. However, the order of the return table of values is not guaranteed. Parameters: ~ - • {t} (table) Table + • {t} (`table`) Table Return: ~ - (list) List of values + (`list`) List of values vim.trim({s}) *vim.trim()* Trim whitespace (Lua pattern "%s") from both sides of a string. Parameters: ~ - • {s} (string) String to trim + • {s} (`string`) String to trim Return: ~ - (string) String with whitespace removed from its beginning and end + (`string`) String with whitespace removed from its beginning and end See also: ~ • |lua-patterns| @@ -2403,7 +2411,7 @@ vim.validate({opt}) *vim.validate()* < Parameters: ~ - • {opt} (table) Names of parameters to validate. Each key is a + • {opt} (`table`) Names of parameters to validate. Each key is a parameter name; each value is a tuple in one of these forms: 1. (arg_value, type_name, optional) • arg_value: argument value @@ -2440,9 +2448,9 @@ vim.loader.find({modname}, {opts}) *vim.loader.find()* Finds Lua modules for the given module name. Parameters: ~ - • {modname} (string) Module name, or `"*"` to find the top-level + • {modname} (`string`) Module name, or `"*"` to find the top-level modules instead - • {opts} (table|nil) Options for finding a module: + • {opts} (`table?`) Options for finding a module: • rtp: (boolean) Search for modname in the runtime path (defaults to `true`) • paths: (string[]) Extra paths to search for modname @@ -2455,7 +2463,7 @@ vim.loader.find({modname}, {opts}) *vim.loader.find()* first one (defaults to `false`) Return: ~ - (list) A list of results with the following properties: + (`list`) A list of results with the following properties: • modpath: (string) the path to the module • modname: (string) the name of the module • stat: (table|nil) the fs_stat of the module path. Won't be returned @@ -2465,7 +2473,7 @@ vim.loader.reset({path}) *vim.loader.reset()* Resets the cache for the path, or all the paths if path is nil. Parameters: ~ - • {path} string? path to reset + • {path} (`string?`) path to reset ============================================================================== @@ -2475,57 +2483,57 @@ vim.uri_decode({str}) *vim.uri_decode()* URI-decodes a string containing percent escapes. Parameters: ~ - • {str} (string) string to decode + • {str} (`string`) string to decode Return: ~ - (string) decoded string + (`string`) decoded string vim.uri_encode({str}, {rfc}) *vim.uri_encode()* URI-encodes a string using percent escapes. Parameters: ~ - • {str} (string) string to encode - • {rfc} "rfc2396" | "rfc2732" | "rfc3986" | nil + • {str} (`string`) string to encode + • {rfc} (`"rfc2396"|"rfc2732"|"rfc3986"?`) Return: ~ - (string) encoded string + (`string`) encoded string vim.uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()* Gets a URI from a bufnr. Parameters: ~ - • {bufnr} (integer) + • {bufnr} (`integer`) Return: ~ - (string) URI + (`string`) URI vim.uri_from_fname({path}) *vim.uri_from_fname()* Gets a URI from a file path. Parameters: ~ - • {path} (string) Path to file + • {path} (`string`) Path to file Return: ~ - (string) URI + (`string`) URI vim.uri_to_bufnr({uri}) *vim.uri_to_bufnr()* Gets the buffer for a uri. Creates a new unloaded buffer if no buffer for the uri already exists. Parameters: ~ - • {uri} (string) + • {uri} (`string`) Return: ~ - (integer) bufnr + (`integer`) bufnr vim.uri_to_fname({uri}) *vim.uri_to_fname()* Gets a filename from a URI. Parameters: ~ - • {uri} (string) + • {uri} (`string`) Return: ~ - (string) filename or unchanged URI for non-file URIs + (`string`) filename or unchanged URI for non-file URIs ============================================================================== @@ -2542,7 +2550,7 @@ vim.ui.input({opts}, {on_confirm}) *vim.ui.input()* < Parameters: ~ - • {opts} (table) Additional options. See |input()| + • {opts} (`table`) Additional options. See |input()| • prompt (string|nil) Text of the prompt • default (string|nil) Default reply to the input • completion (string|nil) Specifies type of completion @@ -2551,7 +2559,7 @@ vim.ui.input({opts}, {on_confirm}) *vim.ui.input()* "-complete=" argument. See |:command-completion| • highlight (function) Function that will be used for highlighting user inputs. - • {on_confirm} (function) ((input|nil) -> ()) Called once the user + • {on_confirm} (`function`) ((input|nil) -> ()) Called once the user confirms or abort the input. `input` is what the user typed (it might be an empty string if nothing was entered), or `nil` if the user aborted the dialog. @@ -2570,11 +2578,11 @@ vim.ui.open({path}) *vim.ui.open()* < Parameters: ~ - • {path} (string) Path or URL to open + • {path} (`string`) Path or URL to open Return (multiple): ~ - vim.SystemCompleted|nil Command result, or nil if not found. - (string|nil) Error message on failure + (`vim.SystemCompleted?`) Command result, or nil if not found. + (`string?`) Error message on failure See also: ~ • |vim.system()| @@ -2599,8 +2607,8 @@ vim.ui.select({items}, {opts}, {on_choice}) *vim.ui.select()* < Parameters: ~ - • {items} (table) Arbitrary items - • {opts} (table) Additional options + • {items} (`table`) Arbitrary items + • {opts} (`table`) Additional options • prompt (string|nil) Text of the prompt. Defaults to `Select one of:` • format_item (function item -> text) Function to format @@ -2610,7 +2618,7 @@ vim.ui.select({items}, {opts}, {on_choice}) *vim.ui.select()* item shape. Plugins reimplementing `vim.ui.select` may wish to use this to infer the structure or semantics of `items`, or the context in which select() was called. - • {on_choice} (function) ((item|nil, idx|nil) -> ()) Called once the + • {on_choice} (`function`) ((item|nil, idx|nil) -> ()) Called once the user made a choice. `idx` is the 1-based index of `item` within `items`. `nil` if the user aborted the dialog. @@ -2700,7 +2708,7 @@ vim.filetype.add({filetypes}) *vim.filetype.add()* < Parameters: ~ - • {filetypes} (table) A table containing new filetype maps (see + • {filetypes} (`table`) A table containing new filetype maps (see example). *vim.filetype.get_option()* @@ -2720,11 +2728,11 @@ vim.filetype.get_option({filetype}, {option}) may not reflect later changes. Parameters: ~ - • {filetype} (string) Filetype - • {option} (string) Option name + • {filetype} (`string`) Filetype + • {option} (`string`) Option name Return: ~ - string|boolean|integer: Option value + (`string|boolean|integer`) Option value vim.filetype.match({args}) *vim.filetype.match()* Perform filetype detection. @@ -2756,7 +2764,7 @@ vim.filetype.match({args}) *vim.filetype.match()* < Parameters: ~ - • {args} (table) Table specifying which matching strategy to use. + • {args} (`table`) Table specifying which matching strategy to use. Accepted keys are: • buf (number): Buffer number to use for matching. Mutually exclusive with {contents} @@ -2772,8 +2780,8 @@ vim.filetype.match({args}) *vim.filetype.match()* Mutually exclusive with {buf}. Return (multiple): ~ - (string|nil) If a match was found, the matched filetype. - (function|nil) A function that modifies buffer state when called (for + (`string?`) If a match was found, the matched filetype. + (`function?`) A function that modifies buffer state when called (for example, to set some filetype specific buffer variables). The function accepts a buffer number as its only argument. @@ -2789,7 +2797,7 @@ vim.keymap.del({modes}, {lhs}, {opts}) *vim.keymap.del()* < Parameters: ~ - • {opts} (table|nil) A table of optional arguments: + • {opts} (`table?`) A table of optional arguments: • "buffer": (integer|boolean) Remove a mapping from the given buffer. When `0` or `true`, use the current buffer. @@ -2813,12 +2821,12 @@ vim.keymap.set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* < Parameters: ~ - • {mode} string|table Mode short-name, see |nvim_set_keymap()|. Can + • {mode} (`string|table`) Mode short-name, see |nvim_set_keymap()|. Can also be list of modes to create mapping on multiple modes. - • {lhs} (string) Left-hand side |{lhs}| of the mapping. - • {rhs} string|function Right-hand side |{rhs}| of the mapping, can be - a Lua function. - • {opts} (table|nil) Table of |:map-arguments|. + • {lhs} (`string`) Left-hand side |{lhs}| of the mapping. + • {rhs} (`string|function`) Right-hand side |{rhs}| of the mapping, + can be a Lua function. + • {opts} (`table?`) Table of |:map-arguments|. • Same as |nvim_set_keymap()| {opts}, except: • "replace_keycodes" defaults to `true` if "expr" is `true`. • "noremap": inverse of "remap" (see below). @@ -2843,26 +2851,26 @@ vim.fs.basename({file}) *vim.fs.basename()* Return the basename of the given path Parameters: ~ - • {file} (string) Path + • {file} (`string`) Path Return: ~ - (string|nil) Basename of {file} + (`string?`) Basename of {file} vim.fs.dir({path}, {opts}) *vim.fs.dir()* Return an iterator over the items located in {path} Parameters: ~ - • {path} (string) An absolute or relative path to the directory to + • {path} (`string`) An absolute or relative path to the directory to iterate over. The path is first normalized |vim.fs.normalize()|. - • {opts} (table|nil) Optional keyword arguments: + • {opts} (`table?`) Optional keyword arguments: • depth: integer|nil How deep the traverse (default 1) • skip: (fun(dir_name: string): boolean)|nil Predicate to control traversal. Return false to stop searching the current directory. Only useful when depth > 1 Return: ~ - Iterator over items in {path}. Each iteration yields two values: + (`Iterator`) over items in {path}. Each iteration yields two values: "name" and "type". "name" is the basename of the item relative to {path}. "type" is one of the following: "file", "directory", "link", "fifo", "socket", "char", "block", "unknown". @@ -2871,10 +2879,10 @@ vim.fs.dirname({file}) *vim.fs.dirname()* Return the parent directory of the given path Parameters: ~ - • {file} (string) Path + • {file} (`string`) Path Return: ~ - (string|nil) Parent directory of {file} + (`string?`) Parent directory of {file} vim.fs.find({names}, {opts}) *vim.fs.find()* Find files or directories (or other items as specified by `opts.type`) in @@ -2910,7 +2918,7 @@ vim.fs.find({names}, {opts}) *vim.fs.find()* < Parameters: ~ - • {names} (string|string[]|fun(name: string, path: string): boolean) + • {names} (`string|string[]|fun(name: string, path: string): boolean`) Names of the items to find. Must be base names, paths and globs are not supported when {names} is a string or a table. If {names} is a function, it is called for each traversed @@ -2918,7 +2926,7 @@ vim.fs.find({names}, {opts}) *vim.fs.find()* • name: base name of the current item • path: full path of the current item The function should return `true` if the given item is considered a match. - • {opts} (table) Optional keyword arguments: + • {opts} (`table`) Optional keyword arguments: • path (string): Path to begin searching from. If omitted, the |current-directory| is used. • upward (boolean, default false): If true, search upward @@ -2933,17 +2941,18 @@ vim.fs.find({names}, {opts}) *vim.fs.find()* number of matches. Return: ~ - (string[]) Normalized paths |vim.fs.normalize()| of all matching items + (`string[]`) Normalized paths |vim.fs.normalize()| of all matching + items vim.fs.joinpath({...}) *vim.fs.joinpath()* Concatenate directories and/or file paths into a single path with normalization (e.g., `"foo/"` and `"bar"` get joined to `"foo/bar"`) Parameters: ~ - • {...} (string) + • {...} (`string`) Return: ~ - (string) + (`string`) vim.fs.normalize({path}, {opts}) *vim.fs.normalize()* Normalize a path to a standard format. A tilde (~) character at the @@ -2963,13 +2972,13 @@ vim.fs.normalize({path}, {opts}) *vim.fs.normalize()* < Parameters: ~ - • {path} (string) Path to normalize - • {opts} (table|nil) Options: + • {path} (`string`) Path to normalize + • {opts} (`table?`) Options: • expand_env: boolean Expand environment variables (default: true) Return: ~ - (string) Normalized path + (`string`) Normalized path vim.fs.parents({start}) *vim.fs.parents()* Iterate over all the parents of the given path. @@ -2989,12 +2998,12 @@ vim.fs.parents({start}) *vim.fs.parents()* < Parameters: ~ - • {start} (string) Initial path. + • {start} (`string`) Initial path. Return (multiple): ~ - fun(_, dir: string): string? Iterator - nil - (string|nil) + (`fun(_, dir: string): string?`) Iterator + (`nil`) + (`string?`) ============================================================================== @@ -3018,10 +3027,11 @@ vim.glob.to_lpeg({pattern}) *vim.glob.to_lpeg()* `example.0`) Parameters: ~ - • {pattern} (string) The raw glob pattern + • {pattern} (`string`) The raw glob pattern Return: ~ - vim.lpeg.Pattern pattern An |lua-lpeg| representation of the pattern + (`vim.lpeg.Pattern`) pattern An |lua-lpeg| representation of the + pattern ============================================================================== @@ -3033,10 +3043,10 @@ vim.secure.read({path}) *vim.secure.read()* $XDG_STATE_HOME/nvim/trust. Parameters: ~ - • {path} (string) Path to a file to read. + • {path} (`string`) Path to a file to read. Return: ~ - (string|nil) The contents of the given file if it exists and is + (`string?`) The contents of the given file if it exists and is trusted, or nil otherwise. See also: ~ @@ -3048,7 +3058,7 @@ vim.secure.trust({opts}) *vim.secure.trust()* The trust database is located at |$XDG_STATE_HOME|/nvim/trust. Parameters: ~ - • {opts} (table) + • {opts} (`table`) • action (string): "allow" to add a file to the trust database and trust it, "deny" to add a file to the trust database and deny it, "remove" to remove file from the trust database @@ -3059,8 +3069,9 @@ vim.secure.trust({opts}) *vim.secure.trust()* exclusive with {path}. Return (multiple): ~ - (boolean) success true if operation was successful - (string) msg full path if operation was successful, else error message + (`boolean`) success true if operation was successful + (`string`) msg full path if operation was successful, else error + message ============================================================================== @@ -3143,50 +3154,51 @@ vim.version.cmp({v1}, {v2}) *vim.version.cmp()* otherwise-equivalent versions. Parameters: ~ - • {v1} Version|number[] Version object. - • {v2} Version|number[] Version to compare with `v1` . + • {v1} (`Version|number[]`) Version object. + • {v2} (`Version|number[]`) Version to compare with `v1` . Return: ~ - (integer) -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`. + (`integer`) -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`. vim.version.eq({v1}, {v2}) *vim.version.eq()* - Returns `true` if the given versions are equal. See |vim.version.cmp()| for usage. + Returns `true` if the given versions are equal. See |vim.version.cmp()| for + usage. Parameters: ~ - • {v1} Version|number[] - • {v2} Version|number[] + • {v1} (`Version|number[]`) + • {v2} (`Version|number[]`) Return: ~ - (boolean) + (`boolean`) vim.version.gt({v1}, {v2}) *vim.version.gt()* Returns `true` if `v1 > v2` . See |vim.version.cmp()| for usage. Parameters: ~ - • {v1} Version|number[] - • {v2} Version|number[] + • {v1} (`Version|number[]`) + • {v2} (`Version|number[]`) Return: ~ - (boolean) + (`boolean`) vim.version.last({versions}) *vim.version.last()* TODO: generalize this, move to func.lua Parameters: ~ - • {versions} Version [] + • {versions} (`Version[]`) Return: ~ - Version ?|nil + (`Version?`) vim.version.lt({v1}, {v2}) *vim.version.lt()* Returns `true` if `v1 < v2` . See |vim.version.cmp()| for usage. Parameters: ~ - • {v1} Version|number[] - • {v2} Version|number[] + • {v1} (`Version|number[]`) + • {v2} (`Version|number[]`) Return: ~ - (boolean) + (`boolean`) vim.version.parse({version}, {opts}) *vim.version.parse()* Parses a semantic version string and returns a version object which can be @@ -3196,15 +3208,15 @@ vim.version.parse({version}, {opts}) *vim.version.parse()* < Parameters: ~ - • {version} (string) Version string to parse. - • {opts} (table|nil) Optional keyword arguments: + • {version} (`string`) Version string to parse. + • {opts} (`table?`) Optional keyword arguments: • strict (boolean): Default false. If `true`, no coercion is attempted on input not conforming to semver v2.0.0. If `false`, `parse()` attempts to coerce input such as "1.0", "0-x", "tmux 3.2a" into valid versions. Return: ~ - (table|nil) parsed_version Version object or `nil` if input is invalid. + (`table?`) parsed_version Version object or `nil` if input is invalid. See also: ~ • # https://semver.org/spec/v2.0.0.html @@ -3234,7 +3246,7 @@ vim.version.range({spec}) *vim.version.range()* < Parameters: ~ - • {spec} (string) Version range "spec" + • {spec} (`string`) Version range "spec" See also: ~ • # https://github.com/npm/node-semver#ranges @@ -3319,13 +3331,13 @@ filter({f}, {src}, {...}) *vim.iter.filter()* < Parameters: ~ - • {f} function(...):bool Filter function. Accepts the current - iterator or table values as arguments and returns true if those - values should be kept in the final table - • {src} table|function Table or iterator function to filter + • {f} (`fun(...):bool`) Filter function. Accepts the current iterator + or table values as arguments and returns true if those values + should be kept in the final table + • {src} (`table|function`) Table or iterator function to filter Return: ~ - (table) + (`table`) See also: ~ • |Iter:filter()| @@ -3334,7 +3346,7 @@ Iter:all({pred}) *Iter:all()* Returns true if all items in the iterator match the given predicate. Parameters: ~ - • {pred} function(...):bool Predicate function. Takes all values + • {pred} (`fun(...):bool`) Predicate function. Takes all values returned from the previous stage in the pipeline as arguments and returns true if the predicate matches. @@ -3343,7 +3355,7 @@ Iter:any({pred}) *Iter:any()* predicate. Parameters: ~ - • {pred} function(...):bool Predicate function. Takes all values + • {pred} (`fun(...):bool`) Predicate function. Takes all values returned from the previous stage in the pipeline as arguments and returns true if the predicate matches. @@ -3355,7 +3367,7 @@ Iter:each({f}) *Iter:each()* |Iter:map()|. Parameters: ~ - • {f} function(...) Function to execute for each item in the pipeline. + • {f} (`fun(...)`) Function to execute for each item in the pipeline. Takes all of the values returned by the previous stage in the pipeline as arguments. @@ -3382,7 +3394,7 @@ Iter:enumerate() *Iter:enumerate()* < Return: ~ - Iter + (`Iter`) Iter:filter({f}) *Iter:filter()* Filters an iterator pipeline. @@ -3392,12 +3404,12 @@ Iter:filter({f}) *Iter:filter()* < Parameters: ~ - • {f} function(...):bool Takes all values returned from the previous + • {f} (`fun(...):bool`) Takes all values returned from the previous stage in the pipeline and returns false or nil if the current iterator element should be removed. Return: ~ - Iter + (`Iter`) Iter:find({f}) *Iter:find()* Find the first value in the iterator that satisfies the given predicate. @@ -3420,7 +3432,29 @@ Iter:find({f}) *Iter:find()* < Return: ~ - any + (`any`) + +Iter:flatten({depth}) *Iter:flatten()* + Flattens a |list-iterator|, un-nesting nested values up to the given + {depth}. Errors if it attempts to flatten a dict-like value. + + Examples: >lua + vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable() + -- { 1, 2, { 3 } } + + vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable() + -- { 1, { a = 2 }, 3 } + + vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable() + -- error: attempt to flatten a dict-like table +< + + Parameters: ~ + • {depth} (`number?`) Depth to which |list-iterator| should be + flattened (defaults to 1) + + Return: ~ + (`Iter`) Iter:fold({init}, {f}) *Iter:fold()* Folds ("reduces") an iterator into a single value. @@ -3438,11 +3472,11 @@ Iter:fold({init}, {f}) *Iter:fold()* < Parameters: ~ - • {init} any Initial value of the accumulator. - • {f} function(acc:any, ...):A Accumulation function. + • {init} (`any`) Initial value of the accumulator. + • {f} (`fun(acc:any, ...):any`) Accumulation function. Return: ~ - any + (`any`) Iter:join({delim}) *Iter:join()* Collect the iterator into a delimited string. @@ -3452,10 +3486,10 @@ Iter:join({delim}) *Iter:join()* Consumes the iterator. Parameters: ~ - • {delim} (string) Delimiter + • {delim} (`string`) Delimiter Return: ~ - (string) + (`string`) Iter:last() *Iter:last()* Drains the iterator and returns the last item. @@ -3471,7 +3505,7 @@ Iter:last() *Iter:last()* < Return: ~ - any + (`any`) Iter:map({f}) *Iter:map()* Maps the items of an iterator pipeline to the values returned by `f`. @@ -3489,13 +3523,13 @@ Iter:map({f}) *Iter:map()* < Parameters: ~ - • {f} function(...):any Mapping function. Takes all values returned - from the previous stage in the pipeline as arguments and returns - one or more new values, which are used in the next pipeline - stage. Nil return values are filtered from the output. + • {f} (`fun(...):any`) Mapping function. Takes all values returned from + the previous stage in the pipeline as arguments and returns one + or more new values, which are used in the next pipeline stage. + Nil return values are filtered from the output. Return: ~ - Iter + (`Iter`) Iter:next() *Iter:next()* Gets the next value from the iterator. @@ -3511,7 +3545,7 @@ Iter:next() *Iter:next()* < Return: ~ - any + (`any`) Iter:nextback() *Iter:nextback()* "Pops" a value from a |list-iterator| (gets the last value and decrements @@ -3526,7 +3560,7 @@ Iter:nextback() *Iter:nextback()* < Return: ~ - any + (`any`) Iter:nth({n}) *Iter:nth()* Gets the nth value of an iterator (and advances to it). @@ -3540,10 +3574,10 @@ Iter:nth({n}) *Iter:nth()* < Parameters: ~ - • {n} (number) The index of the value to return. + • {n} (`number`) The index of the value to return. Return: ~ - any + (`any`) Iter:nthback({n}) *Iter:nthback()* Gets the nth value from the end of a |list-iterator| (and advances to it). @@ -3557,10 +3591,10 @@ Iter:nthback({n}) *Iter:nthback()* < Parameters: ~ - • {n} (number) The index of the value to return. + • {n} (`number`) The index of the value to return. Return: ~ - any + (`any`) Iter:peek() *Iter:peek()* Gets the next value in a |list-iterator| without consuming it. @@ -3576,7 +3610,7 @@ Iter:peek() *Iter:peek()* < Return: ~ - any + (`any`) Iter:peekback() *Iter:peekback()* Gets the last value of a |list-iterator| without consuming it. @@ -3594,7 +3628,7 @@ Iter:peekback() *Iter:peekback()* < Return: ~ - any + (`any`) Iter:rev() *Iter:rev()* Reverses a |list-iterator| pipeline. @@ -3606,7 +3640,7 @@ Iter:rev() *Iter:rev()* < Return: ~ - Iter + (`Iter`) Iter:rfind({f}) *Iter:rfind()* Gets the first value in a |list-iterator| that satisfies a predicate, @@ -3624,7 +3658,7 @@ Iter:rfind({f}) *Iter:rfind()* < Return: ~ - any + (`any`) See also: ~ • Iter.find @@ -3639,10 +3673,10 @@ Iter:skip({n}) *Iter:skip()* < Parameters: ~ - • {n} (number) Number of values to skip. + • {n} (`number`) Number of values to skip. Return: ~ - Iter + (`Iter`) Iter:skipback({n}) *Iter:skipback()* Skips `n` values backwards from the end of a |list-iterator| pipeline. @@ -3656,10 +3690,10 @@ Iter:skipback({n}) *Iter:skipback()* < Parameters: ~ - • {n} (number) Number of values to skip. + • {n} (`number`) Number of values to skip. Return: ~ - Iter + (`Iter`) Iter:slice({first}, {last}) *Iter:slice()* Sets the start and end of a |list-iterator| pipeline. @@ -3667,11 +3701,11 @@ Iter:slice({first}, {last}) *Iter:slice()* Equivalent to `:skip(first - 1):skipback(len - last + 1)`. Parameters: ~ - • {first} (number) - • {last} (number) + • {first} (`number`) + • {last} (`number`) Return: ~ - Iter + (`Iter`) Iter:take({n}) *Iter:take()* Transforms an iterator to yield only the first n values. @@ -3687,10 +3721,10 @@ Iter:take({n}) *Iter:take()* < Parameters: ~ - • {n} (integer) + • {n} (`integer`) Return: ~ - Iter + (`Iter`) Iter:totable() *Iter:totable()* Collect the iterator into a table. @@ -3716,7 +3750,7 @@ Iter:totable() *Iter:totable()* |Iter:fold()|. Return: ~ - (table) + (`table`) map({f}, {src}, {...}) *vim.iter.map()* Maps a table or other |iterable|. >lua @@ -3725,13 +3759,13 @@ map({f}, {src}, {...}) *vim.iter.map()* < Parameters: ~ - • {f} function(...):?any Map function. Accepts the current iterator + • {f} (`fun(...): any?`) Map function. Accepts the current iterator or table values as arguments and returns one or more new values. Nil values are removed from the final table. - • {src} table|function Table or iterator function to filter + • {src} (`table|function`) Table or iterator function to filter Return: ~ - (table) + (`table`) See also: ~ • |Iter:map()| @@ -3743,10 +3777,10 @@ totable({f}, {...}) *vim.iter.totable()* < Parameters: ~ - • {f} (function) Iterator function + • {f} (`function`) Iterator function Return: ~ - (table) + (`table`) ============================================================================== @@ -3756,18 +3790,19 @@ vim.snippet.active() *vim.snippet.active()* Returns `true` if there's an active snippet in the current buffer. Return: ~ - (boolean) + (`boolean`) vim.snippet.exit() *vim.snippet.exit()* Exits the current snippet. vim.snippet.expand({input}) *vim.snippet.expand()* - Expands the given snippet text. Refer to https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax for the specification of valid input. + Expands the given snippet text. Refer to https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax for + the specification of valid input. Tabstops are highlighted with hl-SnippetTabstop. Parameters: ~ - • {input} (string) + • {input} (`string`) vim.snippet.jump({direction}) *vim.snippet.jump()* Jumps within the active snippet in the given direction. If the jump isn't @@ -3784,7 +3819,7 @@ vim.snippet.jump({direction}) *vim.snippet.jump()* < Parameters: ~ - • {direction} (vim.snippet.Direction) Navigation direction. -1 for + • {direction} (`vim.snippet.Direction`) Navigation direction. -1 for previous, 1 for next. vim.snippet.jumpable({direction}) *vim.snippet.jumpable()* @@ -3801,11 +3836,11 @@ vim.snippet.jumpable({direction}) *vim.snippet.jumpable()* < Parameters: ~ - • {direction} (vim.snippet.Direction) Navigation direction. -1 for + • {direction} (`vim.snippet.Direction`) Navigation direction. -1 for previous, 1 for next. Return: ~ - (boolean) + (`boolean`) ============================================================================== @@ -3815,18 +3850,18 @@ vim.text.hexdecode({enc}) *vim.text.hexdecode()* Hex decode a string. Parameters: ~ - • {enc} (string) String to decode + • {enc} (`string`) String to decode Return: ~ - (string) Decoded string + (`string`) Decoded string vim.text.hexencode({str}) *vim.text.hexencode()* Hex encode a string. Parameters: ~ - • {str} (string) String to encode + • {str} (`string`) String to encode Return: ~ - (string) Hex encoded string + (`string`) Hex encoded string vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index d3ace5f33b..98b782a105 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -284,6 +284,9 @@ The following new APIs and features were added. • |vim.deepcopy()| has a `noref` argument to avoid hashing table values. +• Terminal buffers emit a |TermRequest| autocommand event when the child + process emits an OSC or DCS control sequence. + ============================================================================== CHANGED FEATURES *news-changed* diff --git a/runtime/doc/pi_netrw.txt b/runtime/doc/pi_netrw.txt index 85ac290361..1020b703a9 100644 --- a/runtime/doc/pi_netrw.txt +++ b/runtime/doc/pi_netrw.txt @@ -1621,10 +1621,8 @@ A further approach is to delete files which match a pattern. This will cause the matching files to be marked. Then, press "D". -If your vim has 7.4 with patch#1107, then |g:netrw_localrmdir| no longer -is used to remove directories; instead, vim's |delete()| is used with -the "d" option. Please note that only empty directories may be deleted -with the "D" mapping. Regular files are deleted with |delete()|, too. +Please note that only empty directories may be deleted with the "D" mapping. +Regular files are deleted with |delete()|, too. The |g:netrw_rm_cmd|, |g:netrw_rmf_cmd|, and |g:netrw_rmdir_cmd| variables are used to control the attempts to remove remote files and directories. The @@ -1643,8 +1641,7 @@ to remove it again using the g:netrw_rmf_cmd variable. Its default value is: |g:netrw_rmf_cmd|: ssh HOSTNAME rm -f Related topics: |netrw-d| -Associated setting variable: |g:netrw_localrmdir| |g:netrw_rm_cmd| - |g:netrw_rmdir_cmd| |g:netrw_ssh_cmd| +Associated setting variable: |g:netrw_rm_cmd| |g:netrw_ssh_cmd| *netrw-explore* *netrw-hexplore* *netrw-nexplore* *netrw-pexplore* @@ -1687,7 +1684,11 @@ DIRECTORY EXPLORATION COMMANDS {{{2 to 2; edits will thus preferentially be made in window#2. The [N] specifies a |g:netrw_winsize| just for the new :Lexplore - window. + window. That means that + if [N] < 0 : use |N| columns for the Lexplore window + if [N] = 0 : a normal split is made + if [N] > 0 : use N% of the current window will be used for the + new window Those who like this method often also like tree style displays; see |g:netrw_liststyle|. @@ -2848,14 +2849,6 @@ your browsing preferences. (see also: |netrw-settings|) =" /c move" Windows Options for |g:netrw_localmovecmd| - *g:netrw_localrmdir* ="rmdir" Linux/Unix/MacOS/Cygwin - =expand("$COMSPEC") Windows - Remove directory command (rmdir) - This variable is only used if your vim is - earlier than 7.4 or if your vim doesn't - have patch#1107. Otherwise, |delete()| - is used with the "d" option. - *g:netrw_maxfilenamelen* =32 by default, selected so as to make long listings fit on 80 column displays. If your screen is wider, and you have file @@ -3766,7 +3759,7 @@ Example: Clear netrw's marked file list via a mapping on gu > Netrw uses several system level commands to do things (see |g:netrw_localcopycmd|, |g:netrw_localmovecmd|, - |g:netrw_localrmdir|, |g:netrw_mkdir_cmd|). + |g:netrw_mkdir_cmd|). You may need to adjust the default commands for one or more of these commands by setting them properly in your .vimrc. Another @@ -3892,8 +3885,13 @@ netrw: ============================================================================== 12. History *netrw-history* {{{1 - v172: Apr 22, 2023 * removed g:netrw_localrmdiropt - removed g:netrw_localrmdir + v172: Sep 02, 2021 * (Bram Moolenaar) Changed "l:go" to "go" + * (Bram Moolenaar) no need for "b" in + netrw-safe guioptions + Nov 15, 2021 * removed netrw_localrm and netrw_localrmdir + references + Aug 18, 2022 * (Miguel Barro) improving compatability with + powershell v171: Oct 09, 2020 * included code in s:NetrwOptionsSafe() to allow |'bh'| to be set to delete when rather than hide when g:netrw_fastbrowse @@ -3981,7 +3979,6 @@ netrw: |g:netrw_localcopydircmdopt| |g:netrw_localmkdiropt| |g:netrw_localmovecmdopt| - g:netrw_localrmdiropt Nov 21, 2016 * (mattn) provided a patch for preview; swapped winwidth() with winheight() Nov 22, 2016 * (glacambre) reported that files containing @@ -4041,7 +4038,7 @@ netrw: refreshes. However, inside a |:map-<expr>|, tab and window changes are disallowed. Fixed. (affects netrw's s:LocalBrowseRefresh()) - * |g:netrw_localrmdir| not used any more, but + * g:netrw_localrmdir not used any more, but the relevant patch that causes |delete()| to take over was #1107 (not #1109). * |expand()| is now used on |g:netrw_home|; diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index b4c444bbfc..14dedbcbd9 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -567,10 +567,10 @@ foldexpr({lnum}) *vim.treesitter.foldexpr()* < Parameters: ~ - • {lnum} (integer|nil) Line number to calculate fold level for + • {lnum} (`integer?`) Line number to calculate fold level for Return: ~ - (string) + (`string`) foldtext() *vim.treesitter.foldtext()* Returns the highlighted content of the first line of the fold or falls @@ -580,17 +580,17 @@ foldtext() *vim.treesitter.foldtext()* < Return: ~ - `{ [1]: string, [2]: string[] }[]` | string + (`{ [1]: string, [2]: string[] }[]|string`) *vim.treesitter.get_captures_at_cursor()* get_captures_at_cursor({winnr}) Returns a list of highlight capture names under the cursor Parameters: ~ - • {winnr} (integer|nil) Window handle or 0 for current window (default) + • {winnr} (`integer?`) Window handle or 0 for current window (default) Return: ~ - string[] List of capture names + (`string[]`) List of capture names *vim.treesitter.get_captures_at_pos()* get_captures_at_pos({bufnr}, {row}, {col}) @@ -601,12 +601,13 @@ get_captures_at_pos({bufnr}, {row}, {col}) if none are defined). Parameters: ~ - • {bufnr} (integer) Buffer number (0 for current buffer) - • {row} (integer) Position row - • {col} (integer) Position column + • {bufnr} (`integer`) Buffer number (0 for current buffer) + • {row} (`integer`) Position row + • {col} (`integer`) Position column Return: ~ - table[] List of captures `{ capture = "name", metadata = { ... } }` + (`table[]`) List of captures `{ capture = "name", metadata = { ... } + }` get_node({opts}) *vim.treesitter.get_node()* Returns the smallest named node at the given position @@ -618,7 +619,7 @@ get_node({opts}) *vim.treesitter.get_node()* < Parameters: ~ - • {opts} (table|nil) Optional keyword arguments: + • {opts} (`table?`) Optional keyword arguments: • bufnr integer|nil Buffer number (nil or 0 for current buffer) • pos table|nil 0-indexed (row, col) tuple. Defaults to cursor @@ -630,35 +631,35 @@ get_node({opts}) *vim.treesitter.get_node()* true) Return: ~ - |TSNode| | nil Node at the given position + (`TSNode?`) Node at the given position get_node_range({node_or_range}) *vim.treesitter.get_node_range()* Returns the node's range or an unpacked range table Parameters: ~ - • {node_or_range} (|TSNode| | table) Node or table of positions + • {node_or_range} (`TSNode|table`) Node or table of positions Return (multiple): ~ - (integer) start_row - (integer) start_col - (integer) end_row - (integer) end_col + (`integer`) start_row + (`integer`) start_col + (`integer`) end_row + (`integer`) end_col *vim.treesitter.get_node_text()* get_node_text({node}, {source}, {opts}) Gets the text corresponding to a given node Parameters: ~ - • {node} |TSNode| - • {source} (integer|string) Buffer or string from which the {node} is + • {node} (`TSNode`) + • {source} (`integer|string`) Buffer or string from which the {node} is extracted - • {opts} (table|nil) Optional parameters. + • {opts} (`table?`) Optional parameters. • metadata (table) Metadata of a specific capture. This would be set to `metadata[capture_id]` when using |vim.treesitter.query.add_directive()|. Return: ~ - (string) + (`string`) get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()* Returns the parser for a specific buffer and attaches it to the buffer @@ -666,39 +667,39 @@ get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()* If needed, this will create the parser. Parameters: ~ - • {bufnr} (integer|nil) Buffer the parser should be tied to (default: + • {bufnr} (`integer?`) Buffer the parser should be tied to (default: current buffer) - • {lang} (string|nil) Filetype of this parser (default: buffer + • {lang} (`string?`) Filetype of this parser (default: buffer filetype) - • {opts} (table|nil) Options to pass to the created language tree + • {opts} (`table?`) Options to pass to the created language tree Return: ~ - |LanguageTree| object to use for parsing + (`LanguageTree`) object to use for parsing get_range({node}, {source}, {metadata}) *vim.treesitter.get_range()* Get the range of a |TSNode|. Can also supply {source} and {metadata} to get the range with directives applied. Parameters: ~ - • {node} |TSNode| - • {source} integer|string|nil Buffer or string from which the {node} + • {node} (`TSNode`) + • {source} (`integer|string?`) Buffer or string from which the {node} is extracted - • {metadata} TSMetadata|nil + • {metadata} (`TSMetadata?`) Return: ~ - (table) + (`Range6`) *vim.treesitter.get_string_parser()* get_string_parser({str}, {lang}, {opts}) Returns a string parser Parameters: ~ - • {str} (string) Text to parse - • {lang} (string) Language of this string - • {opts} (table|nil) Options to pass to the created language tree + • {str} (`string`) Text to parse + • {lang} (`string`) Language of this string + • {opts} (`table?`) Options to pass to the created language tree Return: ~ - |LanguageTree| object to use for parsing + (`LanguageTree`) object to use for parsing inspect_tree({opts}) *vim.treesitter.inspect_tree()* Open a window that displays a textual representation of the nodes in the @@ -712,7 +713,7 @@ inspect_tree({opts}) *vim.treesitter.inspect_tree()* Can also be shown with `:InspectTree`. *:InspectTree* Parameters: ~ - • {opts} (table|nil) Optional options table with the following possible + • {opts} (`table?`) Optional options table with the following possible keys: • lang (string|nil): The language of the source buffer. If omitted, the filetype of the source buffer is used. @@ -732,33 +733,33 @@ is_ancestor({dest}, {source}) *vim.treesitter.is_ancestor()* Determines whether a node is the ancestor of another Parameters: ~ - • {dest} |TSNode| Possible ancestor - • {source} |TSNode| Possible descendant + • {dest} (`TSNode`) Possible ancestor + • {source} (`TSNode`) Possible descendant Return: ~ - (boolean) True if {dest} is an ancestor of {source} + (`boolean`) True if {dest} is an ancestor of {source} *vim.treesitter.is_in_node_range()* is_in_node_range({node}, {line}, {col}) Determines whether (line, col) position is in node range Parameters: ~ - • {node} |TSNode| defining the range - • {line} (integer) Line (0-based) - • {col} (integer) Column (0-based) + • {node} (`TSNode`) defining the range + • {line} (`integer`) Line (0-based) + • {col} (`integer`) Column (0-based) Return: ~ - (boolean) True if the position is in node range + (`boolean`) True if the position is in node range node_contains({node}, {range}) *vim.treesitter.node_contains()* Determines if a node contains a range Parameters: ~ - • {node} |TSNode| - • {range} (table) + • {node} (`TSNode`) + • {range} (`table`) Return: ~ - (boolean) True if the {node} contains the {range} + (`boolean`) True if the {node} contains the {range} start({bufnr}, {lang}) *vim.treesitter.start()* Starts treesitter highlighting for a buffer @@ -779,16 +780,15 @@ start({bufnr}, {lang}) *vim.treesitter.start()* < Parameters: ~ - • {bufnr} (integer|nil) Buffer to be highlighted (default: current + • {bufnr} (`integer?`) Buffer to be highlighted (default: current buffer) - • {lang} (string|nil) Language of the parser (default: buffer - filetype) + • {lang} (`string?`) Language of the parser (default: buffer filetype) stop({bufnr}) *vim.treesitter.stop()* Stops treesitter highlighting for a buffer Parameters: ~ - • {bufnr} (integer|nil) Buffer to stop highlighting (default: current + • {bufnr} (`integer?`) Buffer to stop highlighting (default: current buffer) @@ -802,8 +802,8 @@ add({lang}, {opts}) *vim.treesitter.language.add()* {path} Parameters: ~ - • {lang} (string) Name of the parser (alphanumerical and `_` only) - • {opts} (table|nil) Options: + • {lang} (`string`) Name of the parser (alphanumerical and `_` only) + • {opts} (`table?`) Options: • filetype (string|string[]) Default filetype the parser should be associated with. Defaults to {lang}. • path (string|nil) Optional path the parser is located at @@ -814,17 +814,17 @@ get_filetypes({lang}) *vim.treesitter.language.get_filetypes()* Get the filetypes associated with the parser named {lang}. Parameters: ~ - • {lang} (string) Name of parser + • {lang} (`string`) Name of parser Return: ~ - string[] filetypes + (`string[]`) filetypes get_lang({filetype}) *vim.treesitter.language.get_lang()* Parameters: ~ - • {filetype} (string) + • {filetype} (`string`) Return: ~ - (string|nil) + (`string?`) inspect({lang}) *vim.treesitter.language.inspect()* Inspects the provided language. @@ -833,10 +833,10 @@ inspect({lang}) *vim.treesitter.language.inspect()* names, ... Parameters: ~ - • {lang} (string) Language + • {lang} (`string`) Language Return: ~ - (table) + (`table`) register({lang}, {filetype}) *vim.treesitter.language.register()* Register a parser named {lang} to be used for {filetype}(s). @@ -845,8 +845,8 @@ register({lang}, {filetype}) *vim.treesitter.language.register()* mappings from other filetypes to {lang} will be preserved. Parameters: ~ - • {lang} (string) Name of parser - • {filetype} string|string[] Filetype(s) to associate with lang + • {lang} (`string`) Name of parser + • {filetype} (`string|string[]`) Filetype(s) to associate with lang ============================================================================== @@ -862,9 +862,8 @@ add_directive({name}, {handler}, {force}) `metadata[capture_id].key = value` Parameters: ~ - • {name} (string) Name of the directive, without leading # - • {handler} function(match:table<string,|TSNode|>, pattern:string, - bufnr:integer, predicate:string[], metadata:table) + • {name} (`string`) Name of the directive, without leading # + • {handler} (`function`) • match: see |treesitter-query| • node-level data are accessible via `match[capture_id]` @@ -872,19 +871,18 @@ add_directive({name}, {handler}, {force}) • predicate: list of strings containing the full directive being called, e.g. `(node (#set! conceal "-"))` would get the predicate `{ "#set!", "conceal", "-" }` - • {force} (boolean|nil) + • {force} (`boolean?`) *vim.treesitter.query.add_predicate()* add_predicate({name}, {handler}, {force}) Adds a new predicate to be used in queries Parameters: ~ - • {name} (string) Name of the predicate, without leading # - • {handler} function(match:table<string,|TSNode|>, pattern:string, - bufnr:integer, predicate:string[]) + • {name} (`string`) Name of the predicate, without leading # + • {handler} (`function`) • see |vim.treesitter.query.add_directive()| for argument meanings - • {force} (boolean|nil) + • {force} (`boolean?`) edit({lang}) *vim.treesitter.query.edit()* Opens a live editor to query the buffer you started from. @@ -897,31 +895,32 @@ edit({lang}) *vim.treesitter.query.edit()* `$VIMRUNTIME/queries/`. Parameters: ~ - • {lang} (string|nil) language to open the query editor for. If - omitted, inferred from the current buffer's filetype. + • {lang} (`string?`) language to open the query editor for. If omitted, + inferred from the current buffer's filetype. get({lang}, {query_name}) *vim.treesitter.query.get()* Returns the runtime query {query_name} for {lang}. Parameters: ~ - • {lang} (string) Language to use for the query - • {query_name} (string) Name of the query (e.g. "highlights") + • {lang} (`string`) Language to use for the query + • {query_name} (`string`) Name of the query (e.g. "highlights") Return: ~ - Query|nil Parsed query + (`Query?`) Parsed query *vim.treesitter.query.get_files()* get_files({lang}, {query_name}, {is_included}) Gets the list of files used to make up a query Parameters: ~ - • {lang} (string) Language to get query for - • {query_name} (string) Name of the query to load (e.g., "highlights") - • {is_included} (boolean|nil) Internal parameter, most of the time left + • {lang} (`string`) Language to get query for + • {query_name} (`string`) Name of the query to load (e.g., + "highlights") + • {is_included} (`boolean?`) Internal parameter, most of the time left as `nil` Return: ~ - string[] query_files List of files to load for given query and + (`string[]`) query_files List of files to load for given query and language lint({buf}, {opts}) *vim.treesitter.query.lint()* @@ -936,11 +935,12 @@ lint({buf}, {opts}) *vim.treesitter.query.lint()* The found diagnostics are reported using |diagnostic-api|. By default, the parser used for verification is determined by the containing folder of the - query file, e.g., if the path ends in `/lua/highlights.scm` , the parser for the `lua` language will be used. + query file, e.g., if the path ends in `/lua/highlights.scm` , the parser + for the `lua` language will be used. Parameters: ~ - • {buf} (integer) Buffer handle - • {opts} (QueryLinterOpts|nil) Optional keyword arguments: + • {buf} (`integer`) Buffer handle + • {opts} (`table?`) Optional keyword arguments: • langs (string|string[]|nil) Language(s) to use for checking the query. If multiple languages are specified, queries are validated for all of them @@ -950,13 +950,13 @@ list_directives() *vim.treesitter.query.list_directives()* Lists the currently available directives to use in queries. Return: ~ - string[] List of supported directives. + (`string[]`) List of supported directives. list_predicates() *vim.treesitter.query.list_predicates()* Lists the currently available predicates to use in queries. Return: ~ - string[] List of supported predicates. + (`string[]`) List of supported predicates. omnifunc({findstart}, {base}) *vim.treesitter.query.omnifunc()* Omnifunc for completing node names and predicates in treesitter queries. @@ -969,8 +969,9 @@ parse({lang}, {query}) *vim.treesitter.query.parse()* Parse {query} as a string. (If the query is in a file, the caller should read the contents into a string before calling). - Returns a `Query` (see |lua-treesitter-query|) object which can be used to search nodes in - the syntax tree for the patterns defined in {query} using `iter_*` methods below. + Returns a `Query` (see |lua-treesitter-query|) object which can be used to + search nodes in the syntax tree for the patterns defined in {query} using `iter_*` methods + below. Exposes `info` and `captures` with additional context about {query}. • `captures` contains the list of unique capture names defined in {query}. @@ -978,11 +979,11 @@ parse({lang}, {query}) *vim.treesitter.query.parse()* • `info.patterns` contains information about predicates. Parameters: ~ - • {lang} (string) Language to use for the query - • {query} (string) Query in s-expr syntax + • {lang} (`string`) Language to use for the query + • {query} (`string`) Query in s-expr syntax Return: ~ - Query Parsed query + (`Query`) Parsed query *Query:iter_captures()* Query:iter_captures({node}, {source}, {start}, {stop}) @@ -1008,14 +1009,14 @@ Query:iter_captures({node}, {source}, {start}, {stop}) < Parameters: ~ - • {node} |TSNode| under which the search will occur - • {source} (integer|string) Source buffer or string to extract text + • {node} (`TSNode`) under which the search will occur + • {source} (`integer|string`) Source buffer or string to extract text from - • {start} (integer) Starting line for the search - • {stop} (integer) Stopping line for the search (end-exclusive) + • {start} (`integer`) Starting line for the search + • {stop} (`integer`) Stopping line for the search (end-exclusive) Return: ~ - (fun(end_line: integer|nil): integer, TSNode, TSMetadata): capture id, + (`fun(end_line: integer?): integer, TSNode, TSMetadata`) capture id, capture node, metadata *Query:iter_matches()* @@ -1042,18 +1043,18 @@ Query:iter_matches({node}, {source}, {start}, {stop}, {opts}) < Parameters: ~ - • {node} |TSNode| under which the search will occur - • {source} (integer|string) Source buffer or string to search - • {start} (integer) Starting line for the search - • {stop} (integer) Stopping line for the search (end-exclusive) - • {opts} (table|nil) Options: + • {node} (`TSNode`) under which the search will occur + • {source} (`integer|string`) Source buffer or string to search + • {start} (`integer`) Starting line for the search + • {stop} (`integer`) Stopping line for the search (end-exclusive) + • {opts} (`table?`) Options: • max_start_depth (integer) if non-zero, sets the maximum start depth for each match. This is used to prevent traversing too deep into a tree. Requires treesitter >= 0.20.9. Return: ~ - (fun(): integer, table<integer,TSNode>, table): pattern id, match, + (`fun(): integer, table<integer,TSNode>, table`) pattern id, match, metadata set({lang}, {query_name}, {text}) *vim.treesitter.query.set()* @@ -1063,9 +1064,9 @@ set({lang}, {query_name}, {text}) *vim.treesitter.query.set()* by plugins. Parameters: ~ - • {lang} (string) Language to use for the query - • {query_name} (string) Name of the query (e.g., "highlights") - • {text} (string) Query text (unparsed). + • {lang} (`string`) Language to use for the query + • {query_name} (`string`) Name of the query (e.g., "highlights") + • {text} (`string`) Query text (unparsed). ============================================================================== @@ -1078,7 +1079,8 @@ inject other languages, recursively. For example a Lua buffer containing some Vimscript commands needs multiple parsers to fully understand its contents. -To create a LanguageTree (parser object) for a given buffer and language, use: >lua +To create a LanguageTree (parser object) for a given buffer and language, +use: >lua local parser = vim.treesitter.get_parser(bufnr, lang) < @@ -1114,10 +1116,10 @@ LanguageTree:contains({range}) *LanguageTree:contains()* Determines whether {range} is contained in the |LanguageTree|. Parameters: ~ - • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }` Return: ~ - (boolean) + (`boolean`) LanguageTree:destroy() *LanguageTree:destroy()* Destroys this |LanguageTree| and all its children. @@ -1133,32 +1135,33 @@ LanguageTree:for_each_tree({fn}) *LanguageTree:for_each_tree()* Note: This includes the invoking tree's child trees as well. Parameters: ~ - • {fn} fun(tree: TSTree, ltree: LanguageTree) + • {fn} (`fun(tree: TSTree, ltree: LanguageTree)`) LanguageTree:included_regions() *LanguageTree:included_regions()* - Gets the set of included regions managed by this LanguageTree . This can be different from the regions set by injection query, because a - partial |LanguageTree:parse()| drops the regions outside the requested - range. + Gets the set of included regions managed by this LanguageTree . This can be + different from the regions set by injection query, because a partial + |LanguageTree:parse()| drops the regions outside the requested range. Return: ~ - table<integer, Range6[]> + (`table<integer, Range6[]>`) LanguageTree:invalidate({reload}) *LanguageTree:invalidate()* Invalidates this parser and all its children Parameters: ~ - • {reload} (boolean|nil) + • {reload} (`boolean?`) LanguageTree:is_valid({exclude_children}) *LanguageTree:is_valid()* - Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()| reflects the latest state of the - source. If invalid, user should call |LanguageTree:parse()|. + Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()| + reflects the latest state of the source. If invalid, user should call + |LanguageTree:parse()|. Parameters: ~ - • {exclude_children} (boolean|nil) whether to ignore the validity of + • {exclude_children} (`boolean?`) whether to ignore the validity of children (default `false`) Return: ~ - (boolean) + (`boolean`) LanguageTree:lang() *LanguageTree:lang()* Gets the language of this tree node. @@ -1168,23 +1171,23 @@ LanguageTree:language_for_range({range}) Gets the appropriate language that contains {range}. Parameters: ~ - • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }` Return: ~ - |LanguageTree| Managing {range} + (`LanguageTree`) Managing {range} *LanguageTree:named_node_for_range()* LanguageTree:named_node_for_range({range}, {opts}) Gets the smallest named node that contains {range}. Parameters: ~ - • {range} (table) `{ start_line, start_col, end_line, end_col }` - • {opts} (table|nil) Optional keyword arguments: + • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }` + • {opts} (`table?`) Optional keyword arguments: • ignore_injections boolean Ignore injected languages (default true) Return: ~ - |TSNode| | nil Found node + (`TSNode?`) Found node LanguageTree:parse({range}) *LanguageTree:parse()* Recursively parse all regions in the language tree using @@ -1197,23 +1200,24 @@ LanguageTree:parse({range}) *LanguageTree:parse()* if {range} is `true`). Parameters: ~ - • {range} boolean|Range|nil: Parse this range in the parser's source. + • {range} (`boolean|Range?`) Parse this range in the parser's source. Set to `true` to run a complete parse of the source (Note: Can be slow!) Set to `false|nil` to only parse regions with empty ranges (typically only the root tree without injections). Return: ~ - table<integer, TSTree> + (`table<integer, TSTree>`) *LanguageTree:register_cbs()* LanguageTree:register_cbs({cbs}, {recursive}) Registers callbacks for the |LanguageTree|. Parameters: ~ - • {cbs} (table) An |nvim_buf_attach()|-like table argument with + • {cbs} (`table`) An |nvim_buf_attach()|-like table argument with the following handlers: - • `on_bytes` : see |nvim_buf_attach()|, but this will be called after the parsers callback. + • `on_bytes` : see |nvim_buf_attach()|, but this will be + called after the parsers callback. • `on_changedtree` : a callback that will be called every time the tree has syntactical changes. It will be passed two arguments: a table of the ranges (as node @@ -1225,7 +1229,7 @@ LanguageTree:register_cbs({cbs}, {recursive}) • `on_detach` : emitted when the buffer is detached, see |nvim_buf_detach_event|. Takes one argument, the number of the buffer. - • {recursive} (boolean|nil) Apply callbacks recursively for all + • {recursive} (`boolean?`) Apply callbacks recursively for all children. Any new children will also inherit the callbacks. @@ -1237,21 +1241,22 @@ LanguageTree:tree_for_range({range}, {opts}) Gets the tree that contains {range}. Parameters: ~ - • {range} (table) `{ start_line, start_col, end_line, end_col }` - • {opts} (table|nil) Optional keyword arguments: + • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }` + • {opts} (`table?`) Optional keyword arguments: • ignore_injections boolean Ignore injected languages (default true) Return: ~ - TSTree|nil + (`TSTree?`) LanguageTree:trees() *LanguageTree:trees()* Returns all trees of the regions parsed by this parser. Does not include child languages. The result is list-like if - • this LanguageTree is the root, in which case the result is empty or a singleton list; or + • this LanguageTree is the root, in which case the result is empty or a + singleton list; or • the root LanguageTree is fully parsed. Return: ~ - table<integer, TSTree> + (`table<integer, TSTree>`) vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/vvars.txt b/runtime/doc/vvars.txt index 7e96d356d0..e71e31abf8 100644 --- a/runtime/doc/vvars.txt +++ b/runtime/doc/vvars.txt @@ -647,9 +647,16 @@ v:t_number Value of |Number| type. Read-only. See: |type()| *v:t_string* *t_string-variable* v:t_string Value of |String| type. Read-only. See: |type()| + *v:termrequest* *termrequest-variable* +v:termrequest + The value of the most recent OSC or DCS control sequence + sent from a process running in the embedded |terminal|. + This can be read in a |TermRequest| event handler to respond + to queries from embedded applications. + *v:termresponse* *termresponse-variable* v:termresponse - The value of the most recent OSC or DCS escape sequence + The value of the most recent OSC or DCS control sequence received by Nvim from the terminal. This can be read in a |TermResponse| event handler after querying the terminal using another escape sequence. diff --git a/runtime/lua/provider/python/health.lua b/runtime/lua/provider/python/health.lua index 7fc4006fc8..6d3a4d5c50 100644 --- a/runtime/lua/provider/python/health.lua +++ b/runtime/lua/provider/python/health.lua @@ -17,10 +17,9 @@ end -- Resolves Python executable path by invoking and checking `sys.executable`. local function python_exepath(invocation) - local python = vim.fn.fnameescape(invocation) - local out = vim.fn.system(python .. ' -c "import sys; sys.stdout.write(sys.executable)"') - assert(vim.v.shell_error == 0, out) - return vim.fs.normalize(vim.trim(out)) + local p = vim.system({ invocation, '-c', 'import sys; sys.stdout.write(sys.executable)' }):wait() + assert(p.code == 0, p.stderr) + return vim.fs.normalize(vim.trim(p.stdout)) end -- Check if pyenv is available and a valid pyenv root can be found, then return @@ -35,7 +34,7 @@ local function check_for_pyenv() health.info('pyenv: Path: ' .. pyenv_path) - local pyenv_root = os.getenv('PYENV_ROOT') and vim.fn.resolve('$PYENV_ROOT') or '' + local pyenv_root = vim.fn.resolve(os.getenv('PYENV_ROOT') or '') if pyenv_root == '' then pyenv_root = vim.fn.system({ pyenv_path, 'root' }) diff --git a/runtime/lua/vim/_editor.lua b/runtime/lua/vim/_editor.lua index cde61697b6..4fe601dfd5 100644 --- a/runtime/lua/vim/_editor.lua +++ b/runtime/lua/vim/_editor.lua @@ -95,7 +95,7 @@ vim.log = { --- throws an error if {cmd} cannot be run. --- --- @param cmd (string[]) Command to execute ---- @param opts (SystemOpts|nil) Options: +--- @param opts vim.SystemOpts? Options: --- - cwd: (string) Set the current working directory for the sub-process. --- - env: table<string,string> Set environment variables for the new process. Inherits the --- current environment with `NVIM` set to |v:servername|. @@ -118,7 +118,7 @@ vim.log = { --- parent exits. Note that the child process will still keep the parent's event loop alive --- unless the parent process calls |uv.unref()| on the child's process handle. --- ---- @param on_exit (function|nil) Called when subprocess exits. When provided, the command runs +--- @param on_exit? fun(out: vim.SystemCompleted) Called when subprocess exits. When provided, the command runs --- asynchronously. Receives SystemCompleted object, see return of SystemObj:wait(). --- --- @return vim.SystemObj Object with the fields: @@ -219,10 +219,9 @@ do --- ``` --- ---@see |paste| - ---@alias paste_phase -1 | 1 | 2 | 3 --- ---@param lines string[] # |readfile()|-style list of lines to paste. |channel-lines| - ---@param phase paste_phase -1: "non-streaming" paste: the call contains all lines. + ---@param phase (-1|1|2|3) -1: "non-streaming" paste: the call contains all lines. --- If paste is "streamed", `phase` indicates the stream state: --- - 1: starts the paste (exactly once) --- - 2: continues the paste (zero or more times) diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua index e85f81f5f9..3f06d4fd43 100644 --- a/runtime/lua/vim/_meta/api.lua +++ b/runtime/lua/vim/_meta/api.lua @@ -155,7 +155,8 @@ function vim.api.nvim_buf_add_highlight(buffer, ns_id, hl_group, line, col_start --- will be `nvim_buf_changedtick_event`. Not for Lua --- callbacks. --- @param opts vim.api.keyset.buf_attach Optional parameters. ---- • on_lines: Lua callback invoked on change. Return `true` to detach. Args: +--- • on_lines: Lua callback invoked on change. Return `true` to +--- detach. Args: --- • the string "lines" --- • buffer handle --- • b:changedtick @@ -168,7 +169,8 @@ function vim.api.nvim_buf_add_highlight(buffer, ns_id, hl_group, line, col_start --- --- • on_bytes: Lua callback invoked on change. This --- callback receives more granular information about the ---- change compared to on_lines. Return `true` to detach. Args: +--- change compared to on_lines. Return `true` to +--- detach. Args: --- • the string "bytes" --- • buffer handle --- • b:changedtick @@ -530,7 +532,8 @@ function vim.api.nvim_buf_line_count(buffer) end --- wrapped lines. --- • hl_mode : control how highlights are combined with the --- highlights of the text. Currently only affects virt_text ---- highlights, but might affect `hl_group` in later versions. +--- highlights, but might affect `hl_group` in +--- later versions. --- • "replace": only show the virt_text color. This is the --- default. --- • "combine": combine with background text color. @@ -740,7 +743,8 @@ function vim.api.nvim_chan_send(chan, data) end --- • NOTE: Cannot be used with {pattern} --- --- • group: (string|int) The augroup name or id. ---- • NOTE: If not passed, will only delete autocmds not in any group. +--- • NOTE: If not passed, will only delete autocmds not in any +--- group. function vim.api.nvim_clear_autocmds(opts) end --- Executes an Ex command. @@ -808,7 +812,8 @@ function vim.api.nvim_complete_set(index, opts) end --- @return integer function vim.api.nvim_create_augroup(name, opts) end ---- Creates an `autocommand` event handler, defined by `callback` (Lua function or Vimscript function name string) or `command` (Ex command string). +--- Creates an `autocommand` event handler, defined by `callback` (Lua function +--- or Vimscript function name string) or `command` (Ex command string). --- Example using Lua callback: --- --- ```lua @@ -1525,8 +1530,8 @@ function vim.api.nvim_open_term(buffer, opts) end --- • height: Window height (in character cells). Minimum of 1. --- • bufpos: Places float relative to buffer text (only when --- relative="win"). Takes a tuple of zero-indexed [line, ---- column]. `row` and `col` if given are applied relative to this position, else they ---- default to: +--- column]. `row` and `col` if given are +--- applied relative to this position, else they default to: --- • `row=1` and `col=0` if `anchor` is "NW" or "NE" --- • `row=0` and `col=0` if `anchor` is "SW" or "SE" (thus --- like a tooltip near the buffer text). @@ -1541,8 +1546,9 @@ function vim.api.nvim_open_term(buffer, opts) end --- • external: GUI should display the window as an external --- top-level window. Currently accepts no other positioning --- configuration together with this. ---- • zindex: Stacking order. floats with higher `zindex` go on top on floats with lower indices. Must be larger ---- than zero. The following screen elements have hard-coded +--- • zindex: Stacking order. floats with higher `zindex` go on +--- top on floats with lower indices. Must be larger than +--- zero. The following screen elements have hard-coded --- z-indices: --- • 100: insert completion popupmenu --- • 200: message scrollback @@ -1661,7 +1667,8 @@ function vim.api.nvim_parse_expression(expr, flags, highlight) end --- @param data string Multiline input. May be binary (containing NUL bytes). --- @param crlf boolean Also break lines at CR and CRLF. --- @param phase integer -1: paste in a single call (i.e. without streaming). To ---- "stream" a paste, call `nvim_paste` sequentially with these `phase` values: +--- "stream" a paste, call `nvim_paste` sequentially +--- with these `phase` values: --- • 1: starts the paste (exactly once) --- • 2: continues the paste (zero or more times) --- • 3: ends the paste (exactly once) diff --git a/runtime/lua/vim/_meta/vvars.lua b/runtime/lua/vim/_meta/vvars.lua index e3b89aeff7..ca87fb9d15 100644 --- a/runtime/lua/vim/_meta/vvars.lua +++ b/runtime/lua/vim/_meta/vvars.lua @@ -687,11 +687,18 @@ vim.v.t_number = ... --- @type integer vim.v.t_string = ... ---- The value of the most recent OSC or DCS escape sequence +--- The value of the most recent OSC or DCS control sequence +--- sent from a process running in the embedded `terminal`. +--- This can be read in a `TermRequest` event handler to respond +--- to queries from embedded applications. +--- @type string +vim.v.termrequest = ... + +--- The value of the most recent OSC or DCS control sequence --- received by Nvim from the terminal. This can be read in a --- `TermResponse` event handler after querying the terminal using --- another escape sequence. ---- @type any +--- @type string vim.v.termresponse = ... --- Must be set before using `test_garbagecollect_now()`. diff --git a/runtime/lua/vim/_system.lua b/runtime/lua/vim/_system.lua index 9279febddf..9e935b7e95 100644 --- a/runtime/lua/vim/_system.lua +++ b/runtime/lua/vim/_system.lua @@ -1,6 +1,6 @@ local uv = vim.uv ---- @class SystemOpts +--- @class vim.SystemOpts --- @field stdin? string|string[]|true --- @field stdout? fun(err:string?, data: string?)|false --- @field stderr? fun(err:string?, data: string?)|false @@ -302,7 +302,7 @@ end --- Run a system command --- --- @param cmd string[] ---- @param opts? SystemOpts +--- @param opts? vim.SystemOpts --- @param on_exit? fun(out: vim.SystemCompleted) --- @return vim.SystemObj function M.run(cmd, opts, on_exit) diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 9141b1e4c6..8cd5f19569 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -2165,7 +2165,7 @@ end --- } --- ``` --- ----@param filetypes vim.filetype.add.filetypes A table containing new filetype maps (see example). +---@param filetypes vim.filetype.add.filetypes (table) A table containing new filetype maps (see example). function M.add(filetypes) for k, v in pairs(filetypes.extension or {}) do extension[k] = v @@ -2300,7 +2300,7 @@ end --- vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) --- ``` --- ----@param args vim.filetype.match.args Table specifying which matching strategy to use. +---@param args vim.filetype.match.args (table) Table specifying which matching strategy to use. --- Accepted keys are: --- * buf (number): Buffer number to use for matching. Mutually exclusive with --- {contents} diff --git a/runtime/lua/vim/health.lua b/runtime/lua/vim/health.lua index d9265f6bd6..f6f7abef8f 100644 --- a/runtime/lua/vim/health.lua +++ b/runtime/lua/vim/health.lua @@ -315,7 +315,7 @@ end --- Run a system command and timeout after 30 seconds. --- --- @param cmd table List of command arguments to execute ---- @param args ?table Optional arguments: +--- @param args? table Optional arguments: --- - stdin (string): Data to write to the job's stdin --- - stderr (boolean): Append stderr to stdout --- - ignore_error (boolean): If true, ignore error output diff --git a/runtime/lua/vim/iter.lua b/runtime/lua/vim/iter.lua index b658dde099..a63d5ba565 100644 --- a/runtime/lua/vim/iter.lua +++ b/runtime/lua/vim/iter.lua @@ -112,6 +112,35 @@ local function sanitize(t) return t end +--- Flattens a single list-like table. Errors if it attempts to flatten a +--- dict-like table +---@param v table table which should be flattened +---@param max_depth number depth to which the table should be flattened +---@param depth number current iteration depth +---@param result table output table that contains flattened result +---@return table|nil flattened table if it can be flattened, otherwise nil +local function flatten(v, max_depth, depth, result) + if depth < max_depth and type(v) == 'table' then + local i = 0 + for _ in pairs(v) do + i = i + 1 + + if v[i] == nil then + -- short-circuit: this is not a list like table + return nil + end + + if flatten(v[i], max_depth, depth + 1, result) == nil then + return nil + end + end + else + result[#result + 1] = v + end + + return result +end + --- Determine if the current iterator stage should continue. --- --- If any arguments are passed to this function, then return those arguments @@ -152,9 +181,9 @@ end --- local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded) --- ``` --- ----@param f function(...):bool Takes all values returned from the previous stage ---- in the pipeline and returns false or nil if the ---- current iterator element should be removed. +---@param f fun(...):bool Takes all values returned from the previous stage +--- in the pipeline and returns false or nil if the +--- current iterator element should be removed. ---@return Iter function Iter.filter(self, f) return self:map(function(...) @@ -179,6 +208,54 @@ function ListIter.filter(self, f) return self end +--- Flattens a |list-iterator|, un-nesting nested values up to the given {depth}. +--- Errors if it attempts to flatten a dict-like value. +--- +--- Examples: +--- +--- ```lua +--- vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable() +--- -- { 1, 2, { 3 } } +--- +--- vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable() +--- -- { 1, { a = 2 }, 3 } +--- +--- vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable() +--- -- error: attempt to flatten a dict-like table +--- ``` +--- +---@param depth? number Depth to which |list-iterator| should be flattened +--- (defaults to 1) +---@return Iter +function Iter.flatten(self, depth) -- luacheck: no unused args + error('flatten() requires a list-like table') +end + +---@private +function ListIter.flatten(self, depth) + depth = depth or 1 + local inc = self._head < self._tail and 1 or -1 + local target = {} + + for i = self._head, self._tail - inc, inc do + local flattened = flatten(self._table[i], depth, 0, {}) + + -- exit early if we try to flatten a dict-like table + if flattened == nil then + error('flatten() requires a list-like table') + end + + for _, v in pairs(flattened) do + target[#target + 1] = v + end + end + + self._head = 1 + self._tail = #target + 1 + self._table = target + return self +end + --- Maps the items of an iterator pipeline to the values returned by `f`. --- --- If the map function returns nil, the value is filtered from the iterator. @@ -195,11 +272,11 @@ end --- -- { 6, 12 } --- ``` --- ----@param f function(...):any Mapping function. Takes all values returned from ---- the previous stage in the pipeline as arguments ---- and returns one or more new values, which are used ---- in the next pipeline stage. Nil return values ---- are filtered from the output. +---@param f fun(...):any Mapping function. Takes all values returned from +--- the previous stage in the pipeline as arguments +--- and returns one or more new values, which are used +--- in the next pipeline stage. Nil return values +--- are filtered from the output. ---@return Iter function Iter.map(self, f) -- Implementation note: the reader may be forgiven for observing that this @@ -263,9 +340,9 @@ end --- --- For functions with side effects. To modify the values in the iterator, use |Iter:map()|. --- ----@param f function(...) Function to execute for each item in the pipeline. ---- Takes all of the values returned by the previous stage ---- in the pipeline as arguments. +---@param f fun(...) Function to execute for each item in the pipeline. +--- Takes all of the values returned by the previous stage +--- in the pipeline as arguments. function Iter.each(self, f) local function fn(...) if select(1, ...) ~= nil then @@ -387,7 +464,7 @@ end ---@generic A --- ---@param init A Initial value of the accumulator. ----@param f function(acc:A, ...):A Accumulation function. +---@param f fun(acc:A, ...):A Accumulation function. ---@return A function Iter.fold(self, init, f) local acc = init @@ -461,9 +538,8 @@ end --- ``` --- ---@return Iter -function Iter.rev(self) +function Iter.rev(self) -- luacheck: no unused args error('rev() requires a list-like table') - return self end ---@private @@ -733,7 +809,6 @@ end ---@diagnostic disable-next-line: unused-local function Iter.skipback(self, n) -- luacheck: no unused args error('skipback() requires a list-like table') - return self end ---@private @@ -800,7 +875,6 @@ end ---@diagnostic disable-next-line: unused-local function Iter.slice(self, first, last) -- luacheck: no unused args error('slice() requires a list-like table') - return self end ---@private @@ -810,9 +884,9 @@ end --- Returns true if any of the items in the iterator match the given predicate. --- ----@param pred function(...):bool Predicate function. Takes all values returned from the previous ---- stage in the pipeline as arguments and returns true if the ---- predicate matches. +---@param pred fun(...):bool Predicate function. Takes all values returned from the previous +--- stage in the pipeline as arguments and returns true if the +--- predicate matches. function Iter.any(self, pred) local any = false @@ -834,9 +908,9 @@ end --- Returns true if all items in the iterator match the given predicate. --- ----@param pred function(...):bool Predicate function. Takes all values returned from the previous ---- stage in the pipeline as arguments and returns true if the ---- predicate matches. +---@param pred fun(...):bool Predicate function. Takes all values returned from the previous +--- stage in the pipeline as arguments and returns true if the +--- predicate matches. function Iter.all(self, pred) local all = true @@ -1032,9 +1106,9 @@ end --- ---@see |Iter:filter()| --- ----@param f function(...):bool Filter function. Accepts the current iterator or table values as ---- arguments and returns true if those values should be kept in the ---- final table +---@param f fun(...):bool Filter function. Accepts the current iterator or table values as +--- arguments and returns true if those values should be kept in the +--- final table ---@param src table|function Table or iterator function to filter ---@return table function M.filter(f, src, ...) @@ -1050,9 +1124,9 @@ end --- ---@see |Iter:map()| --- ----@param f function(...):?any Map function. Accepts the current iterator or table values as ---- arguments and returns one or more new values. Nil values are removed ---- from the final table. +---@param f fun(...): any? Map function. Accepts the current iterator or table values as +--- arguments and returns one or more new values. Nil values are removed +--- from the final table. ---@param src table|function Table or iterator function to filter ---@return table function M.map(f, src, ...) diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index c03a17fa59..daf09b6430 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -516,7 +516,7 @@ end --- --- Displays call hierarchy in the quickfix window. --- ----@param direction `"from"` for incoming calls and `"to"` for outgoing calls +---@param direction 'from'|'to' `"from"` for incoming calls and `"to"` for outgoing calls ---@return function --- `CallHierarchyIncomingCall[]` if {direction} is `"from"`, --- `CallHierarchyOutgoingCall[]` if {direction} is `"to"`, diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 44465f6cff..a2cc81781a 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -790,7 +790,7 @@ end --- Note that if the input is of type `MarkupContent` and its kind is `plaintext`, --- then the corresponding value is returned without further modifications. --- ----@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) +---@param input (lsp.MarkedString | lsp.MarkedString[] | lsp.MarkupContent) ---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}. ---@return string[] extended with lines of converted markdown. ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover @@ -2115,8 +2115,8 @@ end --- Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. --- ---@param buf integer buffer number (0 for current) ----@param row 0-indexed line ----@param col 0-indexed byte offset in line +---@param row integer 0-indexed line +---@param col integer 0-indexed byte offset in line ---@param offset_encoding string utf-8|utf-16|utf-32 defaults to `offset_encoding` of first client of `buf` ---@return integer `offset_encoding` index of the character in line {row} column {col} in buffer {buf} function M.character_offset(buf, row, col, offset_encoding) diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index 24bc97bf8e..e76d148b1b 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -875,7 +875,7 @@ end --- a.b.c = 1 --- ``` --- ----@param createfn function?(key:any):any Provides the value for a missing `key`. +---@param createfn? fun(key:any):any Provides the value for a missing `key`. ---@return table # Empty table with `__index` metamethod. function vim.defaulttable(createfn) createfn = createfn or function(_) diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua index 8cbbffcd60..cc8fe319e8 100644 --- a/runtime/lua/vim/treesitter/query.lua +++ b/runtime/lua/vim/treesitter/query.lua @@ -793,7 +793,7 @@ end --- of the query file, e.g., if the path ends in `/lua/highlights.scm`, the parser for the --- `lua` language will be used. ---@param buf (integer) Buffer handle ----@param opts (QueryLinterOpts|nil) Optional keyword arguments: +---@param opts? QueryLinterOpts (table) Optional keyword arguments: --- - langs (string|string[]|nil) Language(s) to use for checking the query. --- If multiple languages are specified, queries are validated for all of them --- - clear (boolean) if `true`, just clear current lint errors diff --git a/runtime/plugin/tarPlugin.vim b/runtime/plugin/tarPlugin.vim index 384a3ed823..26a994aee5 100644 --- a/runtime/plugin/tarPlugin.vim +++ b/runtime/plugin/tarPlugin.vim @@ -45,7 +45,7 @@ augroup tar au BufReadCmd *.tar.xz call tar#Browse(expand("<amatch>")) au BufReadCmd *.txz call tar#Browse(expand("<amatch>")) au BufReadCmd *.tar.zst call tar#Browse(expand("<amatch>")) - au BufReadCmd *.tzs call tar#Browse(expand("<amatch>")) + au BufReadCmd *.tzst call tar#Browse(expand("<amatch>")) augroup END " --------------------------------------------------------------------- diff --git a/scripts/gen_vimdoc.py b/scripts/gen_vimdoc.py index 804f0fd198..01532cc3d3 100755 --- a/scripts/gen_vimdoc.py +++ b/scripts/gen_vimdoc.py @@ -34,7 +34,7 @@ The generated :help text for each function is formatted as follows: - Each function documentation is separated by a single line. """ -from __future__ import annotations +from __future__ import annotations # PEP-563, python 3.7+ import argparse import collections @@ -47,9 +47,12 @@ import subprocess import sys import textwrap from pathlib import Path -from typing import Any, Callable, Dict, List, Literal, Tuple +from typing import Any, Callable, Dict, List, Tuple from xml.dom import minidom +if sys.version_info >= (3, 8): + from typing import Literal + import msgpack Element = minidom.Element @@ -165,7 +168,7 @@ class Config: CONFIG: Dict[str, Config] = { 'api': Config( - mode = 'c', + mode='c', filename = 'api.txt', # Section ordering. section_order=[x for x in [ @@ -576,7 +579,7 @@ def is_inline(n): return True -def doc_wrap(text, prefix='', width=70, func=False, indent=None): +def doc_wrap(text, prefix='', width=70, func=False, indent=None) -> str: """Wraps text to `width`. First line is prefixed with `prefix`, subsequent lines are aligned. @@ -651,13 +654,19 @@ def update_params_map(parent, ret_map, width=text_width - indentation): return ret_map -def render_node(n, text, prefix='', indent='', width=text_width - indentation, - fmt_vimhelp=False): +def render_node(n: Element, text: str, prefix='', *, + indent: str = '', + width: int = (text_width - indentation), + fmt_vimhelp: bool = False): """Renders a node as Vim help text, recursively traversing all descendants.""" def ind(s): return s if fmt_vimhelp else '' + # Get the current column offset from the last line of `text` + # (needed to appropriately wrap multiple and contiguous inline elements) + col_offset: int = len_lastline(text) + text = '' # space_preceding = (len(text) > 0 and ' ' == text[-1][-1]) # text += (int(not space_preceding) * ' ') @@ -682,7 +691,14 @@ def render_node(n, text, prefix='', indent='', width=text_width - indentation, text += '\n{}\n<'.format(textwrap.indent(o, ' ' * 4)) elif is_inline(n): - text = doc_wrap(get_text(n), prefix=prefix, indent=indent, width=width) + o = get_text(n).strip() + if o: + DEL = chr(127) # a dummy character to pad for proper line wrap + assert len(DEL) == 1 + dummy_padding = DEL * max(0, col_offset - len(prefix)) + text += doc_wrap(dummy_padding + o, + prefix=prefix, indent=indent, width=width + ).replace(DEL, "") elif n.nodeName == 'verbatim': # TODO: currently we don't use this. The "[verbatim]" hint is there as # a reminder that we must decide how to format this if we do use it. @@ -701,12 +717,14 @@ def render_node(n, text, prefix='', indent='', width=text_width - indentation, elif n.nodeName in ('para', 'heading'): did_prefix = False for c in n.childNodes: + c_text = render_node(c, text, prefix=(prefix if not did_prefix else ''), indent=indent, width=width) if (is_inline(c) - and '' != get_text(c).strip() + and '' != c_text.strip() and text - and ' ' != text[-1]): + and text[-1] not in (' ', '(', '|') + and not c_text.startswith(')')): text += ' ' - text += render_node(c, text, prefix=(prefix if not did_prefix else ''), indent=indent, width=width) + text += c_text did_prefix = True elif n.nodeName == 'itemizedlist': for c in n.childNodes: @@ -824,15 +842,17 @@ def para_as_map(parent: Element, raise RuntimeError('unhandled simplesect: {}\n{}'.format( child.nodeName, child.toprettyxml(indent=' ', newl='\n'))) else: + child_text = render_node(child, text, indent=indent, width=width) if (prev is not None and is_inline(self_or_child(prev)) and is_inline(self_or_child(child)) and '' != get_text(self_or_child(child)).strip() and text - and ' ' != text[-1]): + and text[-1] not in (' ', '(', '|') + and not child_text.startswith(')')): text += ' ' - text += render_node(child, text, indent=indent, width=width) + text += child_text prev = child chunks['text'] += text diff --git a/scripts/lua2dox.lua b/scripts/lua2dox.lua index c4ad7fbb03..abc9e5b338 100644 --- a/scripts/lua2dox.lua +++ b/scripts/lua2dox.lua @@ -55,17 +55,7 @@ The effect is that you will get the function documented, but not with the parame local TYPES = { 'integer', 'number', 'string', 'table', 'list', 'boolean', 'function' } -local TAGGED_TYPES = { 'TSNode', 'LanguageTree' } - --- Document these as 'table' -local ALIAS_TYPES = { - 'Range', - 'Range4', - 'Range6', - 'TSMetadata', - 'vim.filetype.add.filetypes', - 'vim.filetype.match.args', -} +local luacats_parser = require('src/nvim/generators/luacats_grammar') local debug_outfile = nil --- @type string? local debug_output = {} @@ -161,6 +151,91 @@ local function removeCommentFromLine(line) return line:sub(1, pos_comment - 1), line:sub(pos_comment) end +--- @param parsed luacats.Return +--- @return string +local function get_return_type(parsed) + local elems = {} --- @type string[] + for _, v in ipairs(parsed) do + local e = v.type --- @type string + if v.name then + e = e .. ' ' .. v.name --- @type string + end + elems[#elems + 1] = e + end + return '(' .. table.concat(elems, ', ') .. ')' +end + +--- @param name string +--- @return string +local function process_name(name, optional) + if optional then + name = name:sub(1, -2) --- @type string + end + return name +end + +--- @param ty string +--- @param generics table<string,string> +--- @return string +local function process_type(ty, generics, optional) + -- replace generic types + for k, v in pairs(generics) do + ty = ty:gsub(k, v) --- @type string + end + + -- strip parens + ty = ty:gsub('^%((.*)%)$', '%1') + + if optional and not ty:find('nil') then + ty = ty .. '?' + end + + -- remove whitespace in unions + ty = ty:gsub('%s*|%s*', '|') + + -- replace '|nil' with '?' + ty = ty:gsub('|nil', '?') + ty = ty:gsub('nil|(.*)', '%1?') + + return '(`' .. ty .. '`)' +end + +--- @param parsed luacats.Param +--- @param generics table<string,string> +--- @return string +local function process_param(parsed, generics) + local name, ty = parsed.name, parsed.type + local optional = vim.endswith(name, '?') + + return table.concat({ + '/// @param', + process_name(name, optional), + process_type(ty, generics, optional), + parsed.desc, + }, ' ') +end + +--- @param parsed luacats.Return +--- @param generics table<string,string> +--- @return string +local function process_return(parsed, generics) + local ty, name --- @type string, string + if #parsed == 1 then + ty, name = parsed[1].type, parsed[1].name or '' + else + ty, name = get_return_type(parsed), '' + end + + local optional = vim.endswith(name, '?') + + return table.concat({ + '/// @return', + process_type(ty, generics, optional), + process_name(name, optional), + parsed.desc, + }, ' ') +end + --- Processes "@…" directives in a docstring line. --- --- @param line string @@ -175,93 +250,54 @@ local function process_magic(line, generics) return '/// ' .. line end - local magic = line:sub(2) - local magic_split = vim.split(magic, ' ', { plain = true }) + local magic_split = vim.split(line, ' ', { plain = true }) local directive = magic_split[1] if vim.list_contains({ - 'cast', - 'diagnostic', - 'overload', - 'meta', - 'type', + '@cast', + '@diagnostic', + '@overload', + '@meta', + '@type', }, directive) then -- Ignore LSP directives return '// gg:"' .. line .. '"' - end - - if directive == 'defgroup' or directive == 'addtogroup' then + elseif directive == '@defgroup' or directive == '@addtogroup' then -- Can't use '.' in defgroup, so convert to '--' - return '/// @' .. magic:gsub('%.', '-dot-') - end - - if directive == 'generic' then - local generic_name, generic_type = line:match('@generic%s*(%w+)%s*:?%s*(.*)') - if generic_type == '' then - generic_type = 'any' - end - generics[generic_name] = generic_type - return + return '/// ' .. line:gsub('%.', '-dot-') end - local type_index = 2 - - if directive == 'param' then + -- preprocess line before parsing + if directive == '@param' or directive == '@return' then for _, type in ipairs(TYPES) do - magic = magic:gsub('^param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. ')%)', 'param %1 %2') - magic = magic:gsub('^param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. '|nil)%)', 'param %1 %2') - end - magic_split = vim.split(magic, ' ', { plain = true }) - type_index = 3 - elseif directive == 'return' then - for _, type in ipairs(TYPES) do - magic = magic:gsub('^return%s+.*%((' .. type .. ')%)', 'return %1') - magic = magic:gsub('^return%s+.*%((' .. type .. '|nil)%)', 'return %1') - end - -- Remove first "#" comment char, if any. https://github.com/LuaLS/lua-language-server/wiki/Annotations#return - magic = magic:gsub('# ', '', 1) - -- handle the return of vim.spell.check - magic = magic:gsub('({.*}%[%])', '`%1`') - magic_split = vim.split(magic, ' ', { plain = true }) - end - - local ty = magic_split[type_index] - - if ty then - -- fix optional parameters - if magic_split[2]:find('%?$') then - if not ty:find('nil') then - ty = ty .. '|nil' - end - magic_split[2] = magic_split[2]:sub(1, -2) - end + line = line:gsub('^@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. ')%)', '@param %1 %2') + line = line:gsub('^@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. '|nil)%)', '@param %1 %2') - -- replace generic types - for k, v in pairs(generics) do - ty = ty:gsub(k, v) --- @type string + line = line:gsub('^@return%s+.*%((' .. type .. ')%)', '@return %1') + line = line:gsub('^@return%s+.*%((' .. type .. '|nil)%)', '@return %1') end + end - for _, type in ipairs(TAGGED_TYPES) do - ty = ty:gsub(type, '|%1|') - end + local parsed = luacats_parser:match(line) - for _, type in ipairs(ALIAS_TYPES) do - ty = ty:gsub('^' .. type .. '$', 'table') --- @type string - end + if not parsed then + return '/// ' .. line + end - -- surround some types by () - for _, type in ipairs(TYPES) do - ty = ty:gsub('^(' .. type .. '|nil):?$', '(%1)'):gsub('^(' .. type .. '):?$', '(%1)') - end + local kind = parsed.kind - magic_split[type_index] = ty + if kind == 'generic' then + generics[parsed.name] = parsed.type or 'any' + return + elseif kind == 'param' then + return process_param(parsed --[[@as luacats.Param]], generics) + elseif kind == 'return' then + return process_return(parsed --[[@as luacats.Return]], generics) end - magic = table.concat(magic_split, ' ') - - return '/// @' .. magic + error(string.format('unhandled parsed line %q: %s', line, parsed)) end --- @param line string diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt index 53ff761b16..8e52542446 100644 --- a/src/nvim/CMakeLists.txt +++ b/src/nvim/CMakeLists.txt @@ -925,6 +925,8 @@ add_custom_command( ${API_SOURCES} ${LUA_SOURCES} ${VIMDOC_FILES} + ${PROJECT_SOURCE_DIR}/scripts/gen_vimdoc.py + ${PROJECT_SOURCE_DIR}/scripts/lua2dox.lua WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} ) diff --git a/src/nvim/auevents.lua b/src/nvim/auevents.lua index 11d1597236..b931907fe3 100644 --- a/src/nvim/auevents.lua +++ b/src/nvim/auevents.lua @@ -109,6 +109,7 @@ return { 'TermEnter', -- after entering Terminal mode 'TermLeave', -- after leaving Terminal mode 'TermOpen', -- after opening a terminal buffer + 'TermRequest', -- after an unhandled OSC sequence is emitted 'TermResponse', -- after setting "v:termresponse" 'TextChanged', -- text was modified 'TextChangedI', -- text was modified in Insert mode(no popup) @@ -166,6 +167,7 @@ return { TabNewEntered = true, TermClose = true, TermOpen = true, + TermRequest = true, UIEnter = true, UILeave = true, }, diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c index 5cb9a519ea..7c64c717e8 100644 --- a/src/nvim/autocmd.c +++ b/src/nvim/autocmd.c @@ -705,7 +705,7 @@ char *au_event_disable(char *what) } else { STRCAT(new_ei, what); } - set_string_option_direct(kOptEventignore, new_ei, OPT_FREE, SID_NONE); + set_string_option_direct(kOptEventignore, new_ei, 0, SID_NONE); xfree(new_ei); return save_ei; } @@ -713,7 +713,7 @@ char *au_event_disable(char *what) void au_event_restore(char *old_ei) { if (old_ei != NULL) { - set_string_option_direct(kOptEventignore, old_ei, OPT_FREE, SID_NONE); + set_string_option_direct(kOptEventignore, old_ei, 0, SID_NONE); xfree(old_ei); } } diff --git a/src/nvim/diff.c b/src/nvim/diff.c index 3e62555fac..f8aed21556 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -1430,7 +1430,7 @@ void diff_win_options(win_T *wp, bool addbuf) } wp->w_p_fdm_save = xstrdup(wp->w_p_fdm); } - set_string_option_direct_in_win(wp, kOptFoldmethod, "diff", OPT_LOCAL | OPT_FREE, 0); + set_string_option_direct_in_win(wp, kOptFoldmethod, "diff", OPT_LOCAL, 0); if (!wp->w_p_diff) { wp->w_p_fen_save = wp->w_p_fen; diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 5069f00df0..451e258356 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -185,6 +185,7 @@ static struct vimvar { VV(VV_VERSION, "version", VAR_NUMBER, VV_COMPAT + VV_RO), VV(VV_LNUM, "lnum", VAR_NUMBER, VV_RO_SBX), VV(VV_TERMRESPONSE, "termresponse", VAR_STRING, VV_RO), + VV(VV_TERMREQUEST, "termrequest", VAR_STRING, VV_RO), VV(VV_FNAME, "fname", VAR_STRING, VV_RO), VV(VV_LANG, "lang", VAR_STRING, VV_RO), VV(VV_LC_TIME, "lc_time", VAR_STRING, VV_RO), diff --git a/src/nvim/eval.h b/src/nvim/eval.h index c46a895c06..abe2685424 100644 --- a/src/nvim/eval.h +++ b/src/nvim/eval.h @@ -86,6 +86,7 @@ typedef enum { VV_THIS_SESSION, VV_VERSION, VV_LNUM, + VV_TERMREQUEST, VV_TERMRESPONSE, VV_FNAME, VV_LANG, diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 4d86b4d478..7abc8354aa 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -4266,7 +4266,7 @@ skip: // Show 'inccommand' preview if there are matched lines. if (cmdpreview_ns > 0 && !aborting()) { if (got_quit || profile_passed_limit(timeout)) { // Too slow, disable. - set_string_option_direct(kOptInccommand, "", OPT_FREE, SID_NONE); + set_string_option_direct(kOptInccommand, "", 0, SID_NONE); } else if (*p_icm != NUL && pat != NULL) { if (pre_hl_id == 0) { pre_hl_id = syn_check_group(S_LEN("Substitute")); @@ -4546,7 +4546,7 @@ bool prepare_tagpreview(bool undo_sync) RESET_BINDING(curwin); // don't take over 'scrollbind' and 'cursorbind' curwin->w_p_diff = false; // no 'diff' - set_string_option_direct(kOptFoldcolumn, "0", OPT_FREE, SID_NONE); // no 'foldcolumn' + set_string_option_direct(kOptFoldcolumn, "0", 0, SID_NONE); // no 'foldcolumn' return true; } @@ -4565,7 +4565,7 @@ static int show_sub(exarg_T *eap, pos_T old_cusr, PreviewLines *preview_lines, i buf_T *cmdpreview_buf = NULL; // disable file info message - set_string_option_direct(kOptShortmess, "F", OPT_FREE, SID_NONE); + set_string_option_direct(kOptShortmess, "F", 0, SID_NONE); // Update the topline to ensure that main window is on the correct line update_topline(curwin); @@ -4666,7 +4666,7 @@ static int show_sub(exarg_T *eap, pos_T old_cusr, PreviewLines *preview_lines, i xfree(str); - set_string_option_direct(kOptShortmess, save_shm_p, OPT_FREE, SID_NONE); + set_string_option_direct(kOptShortmess, save_shm_p, 0, SID_NONE); xfree(save_shm_p); return preview ? 2 : 1; diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 0b6efdaab6..49c5f4e610 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -2654,7 +2654,7 @@ static void apply_cmdmod(cmdmod_T *cmod) // Set 'eventignore' to "all". // First save the existing option value for restoring it later. cmod->cmod_save_ei = xstrdup(p_ei); - set_string_option_direct(kOptEventignore, "all", OPT_FREE, SID_NONE); + set_string_option_direct(kOptEventignore, "all", 0, SID_NONE); } } @@ -2674,7 +2674,7 @@ void undo_cmdmod(cmdmod_T *cmod) if (cmod->cmod_save_ei != NULL) { // Restore 'eventignore' to the value before ":noautocmd". - set_string_option_direct(kOptEventignore, cmod->cmod_save_ei, OPT_FREE, SID_NONE); + set_string_option_direct(kOptEventignore, cmod->cmod_save_ei, 0, SID_NONE); free_string_option(cmod->cmod_save_ei); cmod->cmod_save_ei = NULL; } diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index b15dc2653d..2f2cb3f9e8 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -905,7 +905,7 @@ static uint8_t *command_line_enter(int firstc, int count, int indent, bool clear need_wait_return = false; } - set_string_option_direct(kOptInccommand, s->save_p_icm, OPT_FREE, SID_NONE); + set_string_option_direct(kOptInccommand, s->save_p_icm, 0, SID_NONE); State = s->save_State; if (cmdpreview != save_cmdpreview) { cmdpreview = save_cmdpreview; // restore preview state diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index 008cd9c222..85656650b6 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -1611,7 +1611,7 @@ failed: save_file_ff(curbuf); // If editing a new file: set 'fenc' for the current buffer. // Also for ":read ++edit file". - set_string_option_direct(kOptFileencoding, fenc, OPT_FREE | OPT_LOCAL, 0); + set_string_option_direct(kOptFileencoding, fenc, OPT_LOCAL, 0); } if (fenc_alloced) { xfree(fenc); @@ -1959,7 +1959,7 @@ void set_forced_fenc(exarg_T *eap) } char *fenc = enc_canonize(eap->cmd + eap->force_enc); - set_string_option_direct(kOptFileencoding, fenc, OPT_FREE|OPT_LOCAL, 0); + set_string_option_direct(kOptFileencoding, fenc, OPT_LOCAL, 0); xfree(fenc); } diff --git a/src/nvim/generators/luacats_grammar.lua b/src/nvim/generators/luacats_grammar.lua new file mode 100644 index 0000000000..dcccd028ce --- /dev/null +++ b/src/nvim/generators/luacats_grammar.lua @@ -0,0 +1,136 @@ +--[[! +LPEG grammar for LuaCATS + +Currently only partially supports: +- @param +- @return +]] + +local lpeg = vim.lpeg +local P, R, S = lpeg.P, lpeg.R, lpeg.S +local Ct, Cg = lpeg.Ct, lpeg.Cg + +--- @param x vim.lpeg.Pattern +local function rep(x) + return x ^ 0 +end + +--- @param x vim.lpeg.Pattern +local function rep1(x) + return x ^ 1 +end + +--- @param x vim.lpeg.Pattern +local function opt(x) + return x ^ -1 +end + +local nl = P('\r\n') + P('\n') +local ws = rep1(S(' \t') + nl) +local fill = opt(ws) + +local any = P(1) -- (consume one character) +local letter = R('az', 'AZ') + S('_$') +local num = R('09') +local ident = letter * rep(letter + num + S '-.') +local string_single = P "'" * rep(any - P "'") * P "'" +local string_double = P '"' * rep(any - P '"') * P '"' + +local literal = (string_single + string_double + (opt(P '-') * num) + P 'false' + P 'true') + +local lname = (ident + P '...') * opt(P '?') + +--- @param x string +local function Pf(x) + return fill * P(x) * fill +end + +--- @param x string +local function Sf(x) + return fill * S(x) * fill +end + +--- @param x vim.lpeg.Pattern +local function comma(x) + return x * rep(Pf ',' * x) +end + +--- @param x vim.lpeg.Pattern +local function parenOpt(x) + return (Pf('(') * x ^ -1 * fill * P(')')) + x ^ -1 +end + +--- @type table<string,vim.lpeg.Pattern> +local v = setmetatable({}, { + __index = function(_, k) + return lpeg.V(k) + end, +}) + +local desc_delim = Sf '#:' + ws + +--- @class luacats.Param +--- @field kind 'param' +--- @field name string +--- @field type string +--- @field desc? string + +--- @class luacats.Return +--- @field kind 'return' +--- @field [integer] { type: string, name?: string} +--- @field desc? string + +--- @class luacats.Generic +--- @field kind 'generic' +--- @field name string +--- @field type? string + +--- @alias luacats.grammar.result +--- | luacats.Param +--- | luacats.Return +--- | luacats.Generic + +--- @class luacats.grammar +--- @field match fun(self, input: string): luacats.grammar.result? + +local grammar = P { + rep1(P('@') * v.ats), + + ats = (v.at_param + v.at_return + v.at_generic), + + at_param = Ct( + Cg(P('param'), 'kind') + * ws + * Cg(lname, 'name') + * ws + * Cg(v.ltype, 'type') + * opt(desc_delim * Cg(rep(any), 'desc')) + ), + + at_return = Ct( + Cg(P('return'), 'kind') + * ws + * parenOpt(comma(Ct(Cg(v.ltype, 'type') * opt(ws * Cg(ident, 'name'))))) + * opt(desc_delim * Cg(rep(any), 'desc')) + ), + + at_generic = Ct( + Cg(P('generic'), 'kind') * ws * Cg(ident, 'name') * opt(Pf ':' * Cg(v.ltype, 'type')) + ), + + ltype = v.ty_union + Pf '(' * v.ty_union * fill * P ')', + + ty_union = v.ty_opt * rep(Pf '|' * v.ty_opt), + ty = v.ty_fun + ident + v.ty_table + literal, + ty_param = Pf '<' * comma(v.ltype) * fill * P '>', + ty_opt = v.ty * opt(v.ty_param) * opt(P '[]') * opt(P '?'), + + table_key = (Pf '[' * literal * Pf ']') + lname, + table_elem = v.table_key * Pf ':' * v.ltype, + ty_table = Pf '{' * comma(v.table_elem) * Pf '}', + + fun_param = lname * opt(Pf ':' * v.ltype), + ty_fun = Pf 'fun(' * rep(comma(v.fun_param)) * fill * P ')' * opt(Pf ':' * v.ltype), +} + +return grammar --[[@as luacats.grammar]] diff --git a/src/nvim/help.c b/src/nvim/help.c index f1ca249d5d..ff919f2fb9 100644 --- a/src/nvim/help.c +++ b/src/nvim/help.c @@ -607,7 +607,7 @@ void cleanup_help_tags(int num_file, char **file) void prepare_help_buffer(void) { curbuf->b_help = true; - set_string_option_direct(kOptBuftype, "help", OPT_FREE|OPT_LOCAL, 0); + set_string_option_direct(kOptBuftype, "help", OPT_LOCAL, 0); // Always set these options after jumping to a help tag, because the // user may have an autocommand that gets in the way. @@ -616,13 +616,13 @@ void prepare_help_buffer(void) // Only set it when needed, buf_init_chartab() is some work. char *p = "!-~,^*,^|,^\",192-255"; if (strcmp(curbuf->b_p_isk, p) != 0) { - set_string_option_direct(kOptIskeyword, p, OPT_FREE|OPT_LOCAL, 0); + set_string_option_direct(kOptIskeyword, p, OPT_LOCAL, 0); check_buf_options(curbuf); buf_init_chartab(curbuf, false); } // Don't use the global foldmethod. - set_string_option_direct(kOptFoldmethod, "manual", OPT_FREE|OPT_LOCAL, 0); + set_string_option_direct(kOptFoldmethod, "manual", OPT_LOCAL, 0); curbuf->b_p_ts = 8; // 'tabstop' is 8. curwin->w_p_list = false; // No list mode. diff --git a/src/nvim/indent.c b/src/nvim/indent.c index 802bffdbaf..4022bca5ac 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -1075,7 +1075,7 @@ void ex_retab(exarg_T *eap) colnr_T *old_vts_ary = curbuf->b_p_vts_array; if (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1) { - set_string_option_direct(kOptVartabstop, new_ts_str, OPT_FREE | OPT_LOCAL, 0); + set_string_option_direct(kOptVartabstop, new_ts_str, OPT_LOCAL, 0); curbuf->b_p_vts_array = new_vts_array; xfree(old_vts_ary); } else { diff --git a/src/nvim/main.c b/src/nvim/main.c index 264593ffe8..e41501c562 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -1542,7 +1542,7 @@ static void handle_quickfix(mparm_T *paramp) { if (paramp->edit_type == EDIT_QF) { if (paramp->use_ef != NULL) { - set_string_option_direct(kOptErrorfile, paramp->use_ef, OPT_FREE, SID_CARG); + set_string_option_direct(kOptErrorfile, paramp->use_ef, 0, SID_CARG); } vim_snprintf(IObuff, IOSIZE, "cfile %s", p_ef); if (qf_init(NULL, p_ef, p_efm, true, IObuff, p_menc) < 0) { diff --git a/src/nvim/option.c b/src/nvim/option.c index a46e6fed34..1561361771 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -370,9 +370,6 @@ void set_init_1(bool clean_arg) check_win_options(curwin); check_options(); - // Set all options to their default value - set_options_default(OPT_FREE); - // set 'laststatus' last_status(false); @@ -433,7 +430,7 @@ static void set_option_default(const OptIndex opt_idx, int opt_flags) if (opt->indir != PV_NONE) { set_string_option_direct(opt_idx, opt->def_val, opt_flags, 0); } else { - if ((opt_flags & OPT_FREE) && (flags & P_ALLOCED)) { + if (flags & P_ALLOCED) { free_string_option(*(char **)(varp)); } *(char **)varp = opt->def_val; @@ -482,7 +479,7 @@ static void set_option_default(const OptIndex opt_idx, int opt_flags) /// Set all options (except terminal options) to their default value. /// -/// @param opt_flags OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL +/// @param opt_flags Option flags. static void set_options_default(int opt_flags) { for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { @@ -1431,7 +1428,7 @@ int do_set(char *arg, int opt_flags) if (*arg == '&') { arg++; // Only for :set command set global value of local options. - set_options_default(OPT_FREE | opt_flags); + set_options_default(opt_flags); didset_options(); didset_options2(); ui_refresh_options(); @@ -6216,7 +6213,7 @@ void set_fileformat(int eol_style, int opt_flags) // p is NULL if "eol_style" is EOL_UNKNOWN. if (p != NULL) { - set_string_option_direct(kOptFileformat, p, OPT_FREE | opt_flags, 0); + set_string_option_direct(kOptFileformat, p, opt_flags, 0); } // This may cause the buffer to become (un)modified. diff --git a/src/nvim/option.h b/src/nvim/option.h index 76c76a7245..f122d5c344 100644 --- a/src/nvim/option.h +++ b/src/nvim/option.h @@ -79,16 +79,14 @@ enum { /// When OPT_GLOBAL and OPT_LOCAL are both missing, set both local and global /// values, get local value. typedef enum { - // TODO(famiu): See if `OPT_FREE` is really necessary and remove it if not. - OPT_FREE = 0x01, ///< Free old value if it was allocated. - OPT_GLOBAL = 0x02, ///< Use global value. - OPT_LOCAL = 0x04, ///< Use local value. - OPT_MODELINE = 0x08, ///< Option in modeline. - OPT_WINONLY = 0x10, ///< Only set window-local options. - OPT_NOWIN = 0x20, ///< Don’t set window-local options. - OPT_ONECOLUMN = 0x40, ///< list options one per line - OPT_NO_REDRAW = 0x80, ///< ignore redraw flags on option - OPT_SKIPRTP = 0x100, ///< "skiprtp" in 'sessionoptions' + OPT_GLOBAL = 0x01, ///< Use global value. + OPT_LOCAL = 0x02, ///< Use local value. + OPT_MODELINE = 0x04, ///< Option in modeline. + OPT_WINONLY = 0x08, ///< Only set window-local options. + OPT_NOWIN = 0x10, ///< Don’t set window-local options. + OPT_ONECOLUMN = 0x20, ///< list options one per line + OPT_NO_REDRAW = 0x40, ///< ignore redraw flags on option + OPT_SKIPRTP = 0x80, ///< "skiprtp" in 'sessionoptions' } OptionSetFlags; /// Return value from get_option_attrs(). diff --git a/src/nvim/optionstr.c b/src/nvim/optionstr.c index a1f2d69761..3930e53a90 100644 --- a/src/nvim/optionstr.c +++ b/src/nvim/optionstr.c @@ -289,7 +289,7 @@ static void set_string_option_global(vimoption_T *opt, char **varp) /// "set_sid" is SID_NONE don't set the scriptID. Otherwise set the scriptID to /// "set_sid". /// -/// @param opt_flags OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL. +/// @param opt_flags Option flags. /// /// TODO(famiu): Remove this and its win/buf variants. void set_string_option_direct(OptIndex opt_idx, const char *val, int opt_flags, scid_T set_sid) @@ -306,7 +306,7 @@ void set_string_option_direct(OptIndex opt_idx, const char *val, int opt_flags, char *s = xstrdup(val); char **varp = (char **)get_varp_scope(opt, both ? OPT_LOCAL : opt_flags); - if ((opt_flags & OPT_FREE) && (opt->flags & P_ALLOCED)) { + if (opt->flags & P_ALLOCED) { free_string_option(*varp); } *varp = s; diff --git a/src/nvim/popupmenu.c b/src/nvim/popupmenu.c index a5669d6202..220214c887 100644 --- a/src/nvim/popupmenu.c +++ b/src/nvim/popupmenu.c @@ -58,7 +58,8 @@ static bool pum_rl; // true when popupmenu is drawn 'rightleft' static int pum_anchor_grid; // grid where position is defined static int pum_row; // top row of pum -static int pum_col; // left column of pum +static int pum_col; // left column of pum, right column if 'rightleft' +static int pum_left_col; // left column of pum, before padding or scrollbar static bool pum_above; // pum is drawn above cursor line static bool pum_is_visible = false; @@ -464,14 +465,14 @@ void pum_redraw(void) grid_assign_handle(&pum_grid); - bool moved = ui_comp_put_grid(&pum_grid, pum_row, pum_col - col_off, + pum_left_col = pum_col - col_off; + bool moved = ui_comp_put_grid(&pum_grid, pum_row, pum_left_col, pum_height, grid_width, false, true); bool invalid_grid = moved || pum_invalid; pum_invalid = false; must_redraw_pum = false; - if (!pum_grid.chars - || pum_grid.rows != pum_height || pum_grid.cols != grid_width) { + if (!pum_grid.chars || pum_grid.rows != pum_height || pum_grid.cols != grid_width) { grid_alloc(&pum_grid, pum_height, grid_width, !invalid_grid, false); ui_call_grid_resize(pum_grid.handle, pum_grid.cols, pum_grid.rows); } else if (invalid_grid) { @@ -480,9 +481,8 @@ void pum_redraw(void) if (ui_has(kUIMultigrid)) { const char *anchor = pum_above ? "SW" : "NW"; int row_off = pum_above ? -pum_height : 0; - ui_call_win_float_pos(pum_grid.handle, -1, cstr_as_string((char *)anchor), - pum_anchor_grid, pum_row - row_off, pum_col - col_off, - false, pum_grid.zindex); + ui_call_win_float_pos(pum_grid.handle, -1, cstr_as_string((char *)anchor), pum_anchor_grid, + pum_row - row_off, pum_left_col, false, pum_grid.zindex); } // Never display more than we have @@ -697,7 +697,7 @@ static win_T *pum_create_float_preview(bool enter) return NULL; } buf_T *buf = find_buffer_by_handle(b, &err); - set_string_option_direct_in_buf(buf, kOptBufhidden, "wipe", OPT_FREE | OPT_LOCAL, 0); + set_string_option_direct_in_buf(buf, kOptBufhidden, "wipe", OPT_LOCAL, 0); wp->w_float_is_info = true; wp->w_p_diff = false; buf->b_p_bl = false; @@ -1160,7 +1160,14 @@ static void pum_position_at_mouse(int min_width) max_col = MAX(Columns - wp->w_wincol, wp->w_grid.cols); } } - pum_anchor_grid = mouse_grid; + if (pum_grid.handle != 0 && mouse_grid == pum_grid.handle) { + // Repositioning the menu by right-clicking on itself + mouse_grid = pum_anchor_grid; + mouse_row += pum_row; + mouse_col += pum_left_col; + } else { + pum_anchor_grid = mouse_grid; + } if (max_row - mouse_row > pum_size) { // Enough space below the mouse row. pum_above = false; diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index 3683679daa..6dc45cffcf 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -5091,7 +5091,7 @@ void ex_cfile(exarg_T *eap) } } if (*eap->arg != NUL) { - set_string_option_direct(kOptErrorfile, eap->arg, OPT_FREE, 0); + set_string_option_direct(kOptErrorfile, eap->arg, 0, 0); } char *enc = (*curbuf->b_p_menc != NUL) ? curbuf->b_p_menc : p_menc; diff --git a/src/nvim/statusline.c b/src/nvim/statusline.c index 1fd10f0b6b..95d23d76f0 100644 --- a/src/nvim/statusline.c +++ b/src/nvim/statusline.c @@ -2174,7 +2174,7 @@ int build_stl_str_hl(win_T *wp, char *out, size_t outlen, char *fmt, OptIndex op // matter? // if (called_emsg > called_emsg_before) if (opt_idx != kOptInvalid && did_emsg > did_emsg_before) { - set_string_option_direct(opt_idx, "", OPT_FREE | opt_scope, SID_ERROR); + set_string_option_direct(opt_idx, "", opt_scope, SID_ERROR); } // A user function may reset KeyTyped, restore it. diff --git a/src/nvim/terminal.c b/src/nvim/terminal.c index c6a2cb3354..8b29fcfa42 100644 --- a/src/nvim/terminal.c +++ b/src/nvim/terminal.c @@ -169,6 +169,56 @@ static VTermScreenCallbacks vterm_screen_callbacks = { static Set(ptr_t) invalidated_terminals = SET_INIT; +static void emit_term_request(void **argv) +{ + char *payload = argv[0]; + size_t payload_length = (size_t)argv[1]; + Terminal *rv = argv[2]; + + buf_T *buf = handle_get_buffer(rv->buf_handle); + String termrequest = { .data = payload, .size = payload_length }; + Object data = STRING_OBJ(termrequest); + set_vim_var_string(VV_TERMREQUEST, payload, (ptrdiff_t)payload_length); + apply_autocmds_group(EVENT_TERMREQUEST, NULL, NULL, false, AUGROUP_ALL, buf, NULL, &data); + xfree(payload); +} + +static int on_osc(int command, VTermStringFragment frag, void *user) +{ + if (frag.str == NULL) { + return 0; + } + + StringBuilder request = KV_INITIAL_VALUE; + kv_printf(request, "\x1b]%d;", command); + kv_concat_len(request, frag.str, frag.len); + multiqueue_put(main_loop.events, emit_term_request, request.items, (void *)request.size, user); + return 1; +} + +static int on_dcs(const char *command, size_t commandlen, VTermStringFragment frag, void *user) +{ + if ((command == NULL) || (frag.str == NULL)) { + return 0; + } + + StringBuilder request = KV_INITIAL_VALUE; + kv_printf(request, "\x1bP%*s", (int)commandlen, command); + kv_concat_len(request, frag.str, frag.len); + multiqueue_put(main_loop.events, emit_term_request, request.items, (void *)request.size, user); + return 1; +} + +static VTermStateFallbacks vterm_fallbacks = { + .control = NULL, + .csi = NULL, + .osc = on_osc, + .dcs = on_dcs, + .apc = NULL, + .pm = NULL, + .sos = NULL, +}; + void terminal_init(void) { time_watcher_init(&main_loop, &refresh_timer, NULL); @@ -222,6 +272,7 @@ void terminal_open(Terminal **termpp, buf_T *buf, TerminalOptions opts) vterm_screen_enable_reflow(rv->vts, true); // delete empty lines at the end of the buffer vterm_screen_set_callbacks(rv->vts, &vterm_screen_callbacks, rv); + vterm_screen_set_unrecognised_fallbacks(rv->vts, &vterm_fallbacks, rv); vterm_screen_set_damage_merge(rv->vts, VTERM_DAMAGE_SCROLL); vterm_screen_reset(rv->vts, 1); vterm_output_set_callback(rv->vt, term_output_callback, rv); diff --git a/src/nvim/vvars.lua b/src/nvim/vvars.lua index d1b5e13401..6410df1a57 100644 --- a/src/nvim/vvars.lua +++ b/src/nvim/vvars.lua @@ -770,13 +770,23 @@ M.vars = { desc = 'Value of |String| type. Read-only. See: |type()|', }, termresponse = { + type = 'string', desc = [=[ - The value of the most recent OSC or DCS escape sequence + The value of the most recent OSC or DCS control sequence received by Nvim from the terminal. This can be read in a |TermResponse| event handler after querying the terminal using another escape sequence. ]=], }, + termrequest = { + type = 'string', + desc = [=[ + The value of the most recent OSC or DCS control sequence + sent from a process running in the embedded |terminal|. + This can be read in a |TermRequest| event handler to respond + to queries from embedded applications. + ]=], + }, testing = { desc = [=[ Must be set before using `test_garbagecollect_now()`. diff --git a/test/functional/lua/iter_spec.lua b/test/functional/lua/iter_spec.lua index fdf573669a..8d6cf1264b 100644 --- a/test/functional/lua/iter_spec.lua +++ b/test/functional/lua/iter_spec.lua @@ -462,6 +462,38 @@ describe('vim.iter', function() ) end) + it('flatten()', function() + local t = { { 1, { 2 } }, { { { { 3 } } }, { 4 } }, { 5 } } + + eq(t, vim.iter(t):flatten(-1):totable()) + eq(t, vim.iter(t):flatten(0):totable()) + eq({ 1, { 2 }, { { { 3 } } }, { 4 }, 5 }, vim.iter(t):flatten():totable()) + eq({ 1, 2, { { 3 } }, 4, 5 }, vim.iter(t):flatten(2):totable()) + eq({ 1, 2, { 3 }, 4, 5 }, vim.iter(t):flatten(3):totable()) + eq({ 1, 2, 3, 4, 5 }, vim.iter(t):flatten(4):totable()) + + local m = { a = 1, b = { 2, 3 }, d = { 4 } } + local it = vim.iter(m) + + local flat_err = 'flatten%(%) requires a list%-like table' + matches(flat_err, pcall_err(it.flatten, it)) + + -- cases from the documentation + local simple_example = { 1, { 2 }, { { 3 } } } + eq({ 1, 2, { 3 } }, vim.iter(simple_example):flatten():totable()) + + local not_list_like = vim.iter({ [2] = 2 }) + matches(flat_err, pcall_err(not_list_like.flatten, not_list_like)) + + local also_not_list_like = vim.iter({ nil, 2 }) + matches(flat_err, pcall_err(not_list_like.flatten, also_not_list_like)) + + local nested_non_lists = vim.iter({ 1, { { a = 2 } }, { { nil } }, { 3 } }) + eq({ 1, { a = 2 }, { nil }, 3 }, nested_non_lists:flatten():totable()) + -- only error if we're going deep enough to flatten a dict-like table + matches(flat_err, pcall_err(nested_non_lists.flatten, nested_non_lists, math.huge)) + end) + it('handles map-like tables', function() local it = vim.iter({ a = 1, b = 2, c = 3 }):map(function(k, v) if v % 2 ~= 0 then diff --git a/test/functional/luacats_grammar_spec.lua b/test/functional/luacats_grammar_spec.lua new file mode 100644 index 0000000000..5671848709 --- /dev/null +++ b/test/functional/luacats_grammar_spec.lua @@ -0,0 +1,133 @@ +local helpers = require('test.functional.helpers')(after_each) +local eq = helpers.eq + +local grammar = require('src/nvim/generators/luacats_grammar') + +describe('luacats grammar', function() + --- @param text string + --- @param exp table<string,string> + local function test(text, exp) + it(string.format('can parse %q', text), function() + eq(exp, grammar:match(text)) + end) + end + + test('@param hello vim.type', { + kind = 'param', + name = 'hello', + type = 'vim.type', + }) + + test('@param hello vim.type this is a description', { + kind = 'param', + name = 'hello', + type = 'vim.type', + desc = 'this is a description', + }) + + test('@param hello vim.type|string this is a description', { + kind = 'param', + name = 'hello', + type = 'vim.type|string', + desc = 'this is a description', + }) + + test('@param hello vim.type?|string? this is a description', { + kind = 'param', + name = 'hello', + type = 'vim.type?|string?', + desc = 'this is a description', + }) + + test('@return string hello this is a description', { + kind = 'return', + { + name = 'hello', + type = 'string', + }, + desc = 'this is a description', + }) + + test('@return fun() hello this is a description', { + kind = 'return', + { + name = 'hello', + type = 'fun()', + }, + desc = 'this is a description', + }) + + test('@return fun(a: string[]): string hello this is a description', { + kind = 'return', + { + name = 'hello', + type = 'fun(a: string[]): string', + }, + desc = 'this is a description', + }) + + test('@return fun(a: table<string,any>): string hello this is a description', { + kind = 'return', + { + name = 'hello', + type = 'fun(a: table<string,any>): string', + }, + desc = 'this is a description', + }) + + test('@param ... string desc', { + kind = 'param', + name = '...', + type = 'string', + desc = 'desc', + }) + + test('@param level (integer|string) desc', { + kind = 'param', + name = 'level', + type = '(integer|string)', + desc = 'desc', + }) + + test('@return (string command) the command and arguments', { + kind = 'return', + { + name = 'command', + type = 'string', + }, + desc = 'the command and arguments', + }) + + test('@return (string command, string[] args) the command and arguments', { + kind = 'return', + { + name = 'command', + type = 'string', + }, + { + name = 'args', + type = 'string[]', + }, + desc = 'the command and arguments', + }) + + test('@param rfc "rfc2396" | "rfc2732" | "rfc3986" | nil', { + kind = 'param', + name = 'rfc', + type = '"rfc2396" | "rfc2732" | "rfc3986" | nil', + }) + + test('@param offset_encoding "utf-8" | "utf-16" | "utf-32" | nil', { + kind = 'param', + name = 'offset_encoding', + type = '"utf-8" | "utf-16" | "utf-32" | nil', + }) + + -- handle a : after the param type + test('@param a b: desc', { + kind = 'param', + name = 'a', + type = 'b', + desc = 'desc', + }) +end) diff --git a/test/functional/terminal/buffer_spec.lua b/test/functional/terminal/buffer_spec.lua index 480ca96289..497d7668e8 100644 --- a/test/functional/terminal/buffer_spec.lua +++ b/test/functional/terminal/buffer_spec.lua @@ -317,6 +317,25 @@ describe(':terminal buffer', function() pcall_err(command, 'write test/functional/fixtures/tty-test.c') ) end) + + it('emits TermRequest events #26972', function() + command('split') + command('enew') + local term = meths.open_term(0, {}) + local termbuf = meths.get_current_buf().id + + -- Test that autocommand buffer is associated with the terminal buffer, not the current buffer + command('au TermRequest * let g:termbuf = +expand("<abuf>")') + command('wincmd p') + + -- cwd will be inserted in a file URI, which cannot contain backs + local cwd = funcs.getcwd():gsub('\\', '/') + local parent = cwd:match('^(.+/)') + local expected = '\027]7;file://host' .. parent + meths.chan_send(term, string.format('%s\027\\', expected)) + eq(expected, eval('v:termrequest')) + eq(termbuf, eval('g:termbuf')) + end) end) describe('No heap-buffer-overflow when using', function() diff --git a/test/functional/terminal/tui_spec.lua b/test/functional/terminal/tui_spec.lua index f6ee0f9c77..e65e57bc7f 100644 --- a/test/functional/terminal/tui_spec.lua +++ b/test/functional/terminal/tui_spec.lua @@ -28,6 +28,7 @@ local new_pipename = helpers.new_pipename local spawn_argv = helpers.spawn_argv local set_session = helpers.set_session local write_file = helpers.write_file +local eval = helpers.eval if helpers.skip(is_os('win')) then return @@ -2736,6 +2737,42 @@ describe('TUI', function() unchanged = true, } end) + + it('queries the terminal for truecolor support', function() + clear() + exec_lua([[ + vim.api.nvim_create_autocmd('TermRequest', { + callback = function(args) + local req = args.data + local payload = req:match('^\027P%+q([%x;]+)$') + if payload then + vim.g.xtgettcap = true + return true + end + end, + }) + ]]) + screen = thelpers.setup_child_nvim({ + '-u', + 'NONE', + '-i', + 'NONE', + }, { + env = { + VIMRUNTIME = os.getenv('VIMRUNTIME'), + + -- Force COLORTERM to be unset and use a TERM that does not contain Tc or RGB in terminfo. + -- This will force the nested nvim instance to query with XTGETTCAP + COLORTERM = '', + TERM = 'xterm-256colors', + }, + }) + + retry(nil, 1000, function() + eq(true, eval("get(g:, 'xtgettcap', v:false)")) + eq(1, eval('&termguicolors')) + end) + end) end) describe('TUI bg color', function() @@ -2743,6 +2780,18 @@ describe('TUI bg color', function() local function setup_bg_test() clear() + exec_lua([[ + vim.api.nvim_create_autocmd('TermRequest', { + callback = function(args) + local req = args.data + if req == '\027]11;?' then + vim.g.oscrequest = true + return true + end + end, + }) + ]]) + screen = thelpers.setup_child_nvim({ '-u', 'NONE', @@ -2759,6 +2808,12 @@ describe('TUI bg color', function() before_each(setup_bg_test) + it('queries the terminal for background color', function() + retry(nil, 1000, function() + eq(true, eval("get(g:, 'oscrequest', v:false)")) + end) + end) + it('triggers OptionSet event on unsplit terminal-response', function() screen:expect([[ {1: } | diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua index 67a5f2ef77..da0a68edcb 100644 --- a/test/functional/ui/popupmenu_spec.lua +++ b/test/functional/ui/popupmenu_spec.lua @@ -3771,6 +3771,67 @@ describe('builtin popupmenu', function() ]]) end if multigrid then + meths.input_mouse('right', 'press', '', 2, 0, 18) + screen:expect { + grid = [[ + ## grid 1 + [2:--------------------------------]|*5 + [3:--------------------------------]| + ## grid 2 + ^popup menu test | + {1:~ }|*4 + ## grid 3 + :let g:menustr = 'bar' | + ## grid 4 + {n: foo }| + {n: bar }| + {n: baz }| + ]], + float_pos = { + [4] = { { id = -1 }, 'NW', 2, 1, 17, false, 250 }, + }, + } + else + feed('<RightMouse><18,0>') + screen:expect([[ + ^popup menu test | + {1:~ }{n: foo }{1: }| + {1:~ }{n: bar }{1: }| + {1:~ }{n: baz }{1: }| + {1:~ }| + :let g:menustr = 'bar' | + ]]) + end + if multigrid then + meths.input_mouse('right', 'press', '', 4, 1, 3) + screen:expect({ + grid = [[ + ## grid 1 + [2:--------------------------------]|*5 + [3:--------------------------------]| + ## grid 2 + ^popup menu test | + {1:~ }|*4 + ## grid 3 + :let g:menustr = 'bar' | + ## grid 4 + {n: foo }| + {n: bar }| + {n: baz }| + ]], + float_pos = { [4] = { { id = -1 }, 'NW', 2, 3, 19, false, 250 } }, + }) + else + feed('<RightMouse><20,2>') + screen:expect([[ + ^popup menu test | + {1:~ }|*2 + {1:~ }{n: foo }{1: }| + {1:~ }{n: bar }{1: }| + :let g:menustr = 'b{n: baz } | + ]]) + end + if multigrid then meths.input_mouse('left', 'press', '', 4, 2, 2) screen:expect({ grid = [[ @@ -3785,7 +3846,7 @@ describe('builtin popupmenu', function() ]], }) else - feed('<LeftMouse><22,5>') + feed('<LeftMouse><21,5>') screen:expect([[ ^popup menu test | {1:~ }|*4 @@ -4022,7 +4083,7 @@ describe('builtin popupmenu', function() ]], }) else - feed('<LeftMouse><22,3>') + feed('<LeftMouse><21,3>') screen:expect([[ popup menu test | {1:~ }| |