diff options
author | Josh Rahm <rahm@google.com> | 2022-10-11 19:00:52 +0000 |
---|---|---|
committer | Josh Rahm <rahm@google.com> | 2022-10-11 19:00:52 +0000 |
commit | 21e2e46242033c7aaa6ccfb23e256680816c063c (patch) | |
tree | f089522cfb145d6e9c8a86a01d8e454ce5501e20 /runtime | |
parent | 179d3ed87b17988f5fe00d8b99f2611a28212be7 (diff) | |
parent | 760b399f6c0c6470daa0663752bd22886997f9e6 (diff) | |
download | rneovim-floattitle.tar.gz rneovim-floattitle.tar.bz2 rneovim-floattitle.zip |
Merge remote-tracking branch 'upstream/master' into floattitlefloattitle
Diffstat (limited to 'runtime')
190 files changed, 10606 insertions, 6613 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e0a0b34d28..6b926e9fc1 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -75,8 +75,10 @@ add_custom_command(OUTPUT ${GENERATED_HELP_TAGS} ) +# TODO: This doesn't work. wait for "nvim -l" to land? add_custom_target(doc_html - COMMAND make html + COMMAND "${PROJECT_BINARY_DIR}/bin/nvim" + -V1 -es --clean -c "lua require('scripts.gen_help_html').gen('./build/runtime/doc', './build/doc_html', nil, 'todo_commit_id')" -c "0cq" DEPENDS ${GENERATED_HELP_TAGS} WORKING_DIRECTORY "${GENERATED_RUNTIME_DIR}/doc" @@ -123,7 +125,7 @@ foreach(PROG ${RUNTIME_PROGRAMS}) endforeach() globrecurse_wrapper(RUNTIME_FILES ${CMAKE_CURRENT_SOURCE_DIR} - *.vim *.lua *.dict *.py *.rb *.ps *.spl *.tutor *.tutor.json) + *.vim *.lua *.scm *.dict *.py *.rb *.ps *.spl *.tutor *.tutor.json) foreach(F ${RUNTIME_FILES}) get_filename_component(BASEDIR ${F} DIRECTORY) diff --git a/runtime/autoload/dist/ft.vim b/runtime/autoload/dist/ft.vim index 77140d62b1..7333e5a7e7 100644 --- a/runtime/autoload/dist/ft.vim +++ b/runtime/autoload/dist/ft.vim @@ -468,7 +468,7 @@ endfunc " Returns true if file content looks like LambdaProlog module func IsLProlog() - " skip apparent comments and blank lines, what looks like + " skip apparent comments and blank lines, what looks like " LambdaProlog comment may be RAPID header let l = nextnonblank(1) while l > 0 && l < line('$') && getline(l) =~ '^\s*%' " LambdaProlog comment @@ -877,6 +877,23 @@ func dist#ft#FTsig() endif endfunc +" This function checks the first 100 lines of files matching "*.sil" to +" resolve detection between Swift Intermediate Language and SILE. +func dist#ft#FTsil() + for lnum in range(1, [line('$'), 100]->min()) + let line = getline(lnum) + if line =~ '^\s*[\\%]' + setf sile + return + elseif line =~ '^\s*\S' + setf sil + return + endif + endfor + " no clue, default to "sil" + setf sil +endfunc + func dist#ft#FTsys() if exists("g:filetype_sys") exe "setf " .. g:filetype_sys diff --git a/runtime/autoload/man.vim b/runtime/autoload/man.vim deleted file mode 100644 index b8a73a64c9..0000000000 --- a/runtime/autoload/man.vim +++ /dev/null @@ -1,529 +0,0 @@ -" Maintainer: Anmol Sethi <hi@nhooyr.io> - -if exists('s:loaded_man') - finish -endif -let s:loaded_man = 1 - -let s:find_arg = '-w' -let s:localfile_arg = v:true " Always use -l if possible. #6683 - -function! man#init() abort - try - " Check for -l support. - call s:get_page(s:get_path('', 'man')) - catch /command error .*/ - let s:localfile_arg = v:false - endtry -endfunction - -function! man#open_page(count, mods, ...) abort - if a:0 > 2 - call s:error('too many arguments') - return - elseif a:0 == 0 - let ref = &filetype ==# 'man' ? expand('<cWORD>') : expand('<cword>') - if empty(ref) - call s:error('no identifier under cursor') - return - endif - elseif a:0 ==# 1 - let ref = a:1 - else - " Combine the name and sect into a manpage reference so that all - " verification/extraction can be kept in a single function. - " If a:2 is a reference as well, that is fine because it is the only - " reference that will match. - let ref = a:2.'('.a:1.')' - endif - try - let [sect, name] = s:extract_sect_and_name_ref(ref) - if a:count >= 0 - let sect = string(a:count) - endif - let path = s:verify_exists(sect, name) - let [sect, name] = s:extract_sect_and_name_path(path) - catch - call s:error(v:exception) - return - endtry - - let [l:buf, l:save_tfu] = [bufnr(), &tagfunc] - try - setlocal tagfunc=man#goto_tag - let l:target = l:name . '(' . l:sect . ')' - if a:mods !~# 'tab' && s:find_man() - execute 'silent keepalt tag' l:target - else - execute 'silent keepalt' a:mods 'stag' l:target - endif - call s:set_options(v:false) - finally - call setbufvar(l:buf, '&tagfunc', l:save_tfu) - endtry - - let b:man_sect = sect -endfunction - -" Called when a man:// buffer is opened. -function! man#read_page(ref) abort - try - let [sect, name] = s:extract_sect_and_name_ref(a:ref) - let path = s:verify_exists(sect, name) - let [sect, name] = s:extract_sect_and_name_path(path) - let page = s:get_page(path) - catch - call s:error(v:exception) - return - endtry - let b:man_sect = sect - call s:put_page(page) -endfunction - -" Handler for s:system() function. -function! s:system_handler(jobid, data, event) dict abort - if a:event is# 'stdout' || a:event is# 'stderr' - let self[a:event] .= join(a:data, "\n") - else - let self.exit_code = a:data - endif -endfunction - -" Run a system command and timeout after 30 seconds. -function! s:system(cmd, ...) abort - let opts = { - \ 'stdout': '', - \ 'stderr': '', - \ 'exit_code': 0, - \ 'on_stdout': function('s:system_handler'), - \ 'on_stderr': function('s:system_handler'), - \ 'on_exit': function('s:system_handler'), - \ } - let jobid = jobstart(a:cmd, opts) - - if jobid < 1 - throw printf('command error %d: %s', jobid, join(a:cmd)) - endif - - let res = jobwait([jobid], 30000) - if res[0] == -1 - try - call jobstop(jobid) - throw printf('command timed out: %s', join(a:cmd)) - catch /^Vim(call):E900:/ - endtry - elseif res[0] == -2 - throw printf('command interrupted: %s', join(a:cmd)) - endif - if opts.exit_code != 0 - throw printf("command error (%d) %s: %s", jobid, join(a:cmd), substitute(opts.stderr, '\_s\+$', '', &gdefault ? '' : 'g')) - endif - - return opts.stdout -endfunction - -function! s:set_options(pager) abort - setlocal noswapfile buftype=nofile bufhidden=hide - setlocal nomodified readonly nomodifiable - let b:pager = a:pager - setlocal filetype=man -endfunction - -function! s:get_page(path) abort - " Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065). - " Soft-wrap: ftplugin/man.vim sets wrap/breakindent/…. - " Hard-wrap: driven by `man`. - let manwidth = !get(g:, 'man_hardwrap', 1) ? 999 : (empty($MANWIDTH) ? winwidth(0) : $MANWIDTH) - " Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db). - " http://comments.gmane.org/gmane.editors.vim.devel/29085 - " Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces. - let cmd = ['env', 'MANPAGER=cat', 'MANWIDTH='.manwidth, 'MAN_KEEP_FORMATTING=1', 'man'] - return s:system(cmd + (s:localfile_arg ? ['-l', a:path] : [a:path])) -endfunction - -function! s:put_page(page) abort - setlocal modifiable noreadonly noswapfile - silent keepjumps %delete _ - silent put =a:page - while getline(1) =~# '^\s*$' - silent keepjumps 1delete _ - endwhile - " XXX: nroff justifies text by filling it with whitespace. That interacts - " badly with our use of $MANWIDTH=999. Hack around this by using a fixed - " size for those whitespace regions. - silent! keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g - 1 - lua require("man").highlight_man_page() - call s:set_options(v:false) -endfunction - -function! man#show_toc() abort - let bufname = bufname('%') - let info = getloclist(0, {'winid': 1}) - if !empty(info) && getwinvar(info.winid, 'qf_toc') ==# bufname - lopen - return - endif - - let toc = [] - let lnum = 2 - let last_line = line('$') - 1 - while lnum && lnum < last_line - let text = getline(lnum) - if text =~# '^\%( \{3\}\)\=\S.*$' - " if text is a section title - call add(toc, {'bufnr': bufnr('%'), 'lnum': lnum, 'text': text}) - elseif text =~# '^\s\+\%(+\|-\)\S\+' - " if text is a flag title. we strip whitespaces and prepend two - " spaces to have a consistent format in the loclist. - let text = ' ' .. substitute(text, '^\s*\(.\{-}\)\s*$', '\1', '') - call add(toc, {'bufnr': bufnr('%'), 'lnum': lnum, 'text': text}) - endif - let lnum = nextnonblank(lnum + 1) - endwhile - - call setloclist(0, toc, ' ') - call setloclist(0, [], 'a', {'title': 'Man TOC'}) - lopen - let w:qf_toc = bufname -endfunction - -" attempt to extract the name and sect out of 'name(sect)' -" otherwise just return the largest string of valid characters in ref -function! s:extract_sect_and_name_ref(ref) abort - if a:ref[0] ==# '-' " try ':Man -pandoc' with this disabled. - throw 'manpage name cannot start with ''-''' - endif - let ref = matchstr(a:ref, '[^()]\+([^()]\+)') - if empty(ref) - let name = matchstr(a:ref, '[^()]\+') - if empty(name) - throw 'manpage reference cannot contain only parentheses' - endif - return ['', s:spaces_to_underscores(name)] - endif - let left = split(ref, '(') - " see ':Man 3X curses' on why tolower. - " TODO(nhooyr) Not sure if this is portable across OSs - " but I have not seen a single uppercase section. - return [tolower(split(left[1], ')')[0]), s:spaces_to_underscores(left[0])] -endfunction - -" replace spaces in a man page name with underscores -" intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)'; -" while editing SQL source code, it's nice to visually select 'CREATE TABLE' -" and hit 'K', which requires this transformation -function! s:spaces_to_underscores(str) - return substitute(a:str, ' ', '_', 'g') -endfunction - -function! s:get_path(sect, name) abort - " Some man implementations (OpenBSD) return all available paths from the - " search command. Previously, this function would simply select the first one. - " - " However, some searches will report matches that are incorrect: - " man -w strlen may return string.3 followed by strlen.3, and therefore - " selecting the first would get us the wrong page. Thus, we must find the - " first matching one. - " - " There's yet another special case here. Consider the following: - " If you run man -w strlen and string.3 comes up first, this is a problem. We - " should search for a matching named one in the results list. - " However, if you search for man -w clock_gettime, you will *only* get - " clock_getres.2, which is the right page. Searching the resuls for - " clock_gettime will no longer work. In this case, we should just use the - " first one that was found in the correct section. - " - " Finally, we can avoid relying on -S or -s here since they are very - " inconsistently supported. Instead, call -w with a section and a name. - if empty(a:sect) - let results = split(s:system(['man', s:find_arg, a:name])) - else - let results = split(s:system(['man', s:find_arg, a:sect, a:name])) - endif - - if empty(results) - return '' - endif - - " find any that match the specified name - let namematches = filter(copy(results), 'fnamemodify(v:val, ":t") =~ a:name') - let sectmatches = [] - - if !empty(namematches) && !empty(a:sect) - let sectmatches = filter(copy(namematches), 'fnamemodify(v:val, ":e") == a:sect') - endif - - return substitute(get(sectmatches, 0, get(namematches, 0, results[0])), '\n\+$', '', '') -endfunction - -" s:verify_exists attempts to find the path to a manpage -" based on the passed section and name. -" -" 1. If the passed section is empty, b:man_default_sects is used. -" 2. If manpage could not be found with the given sect and name, -" then another attempt is made with b:man_default_sects. -" 3. If it still could not be found, then we try again without a section. -" 4. If still not found but $MANSECT is set, then we try again with $MANSECT -" unset. -" -" This function is careful to avoid duplicating a search if a previous -" step has already done it. i.e if we use b:man_default_sects in step 1, -" then we don't do it again in step 2. -function! s:verify_exists(sect, name) abort - let sect = a:sect - - if empty(sect) - " no section specified, so search with b:man_default_sects - if exists('b:man_default_sects') - let sects = split(b:man_default_sects, ',') - for sec in sects - try - let res = s:get_path(sec, a:name) - if !empty(res) - return res - endif - catch /^command error (/ - endtry - endfor - endif - else - " try with specified section - try - let res = s:get_path(sect, a:name) - if !empty(res) - return res - endif - catch /^command error (/ - endtry - - " try again with b:man_default_sects - if exists('b:man_default_sects') - let sects = split(b:man_default_sects, ',') - for sec in sects - try - let res = s:get_path(sec, a:name) - if !empty(res) - return res - endif - catch /^command error (/ - endtry - endfor - endif - endif - - " if none of the above worked, we will try with no section - try - let res = s:get_path('', a:name) - if !empty(res) - return res - endif - catch /^command error (/ - endtry - - " if that still didn't work, we will check for $MANSECT and try again with it - " unset - if !empty($MANSECT) - try - let MANSECT = $MANSECT - call setenv('MANSECT', v:null) - let res = s:get_path('', a:name) - if !empty(res) - return res - endif - catch /^command error (/ - finally - call setenv('MANSECT', MANSECT) - endtry - endif - - " finally, if that didn't work, there is no hope - throw 'no manual entry for ' . a:name -endfunction - -" Extracts the name/section from the 'path/name.sect', because sometimes the actual section is -" more specific than what we provided to `man` (try `:Man 3 App::CLI`). -" Also on linux, name seems to be case-insensitive. So for `:Man PRIntf`, we -" still want the name of the buffer to be 'printf'. -function! s:extract_sect_and_name_path(path) abort - let tail = fnamemodify(a:path, ':t') - if a:path =~# '\.\%([glx]z\|bz2\|lzma\|Z\)$' " valid extensions - let tail = fnamemodify(tail, ':r') - endif - let sect = matchstr(tail, '\.\zs[^.]\+$') - let name = matchstr(tail, '^.\+\ze\.') - return [sect, name] -endfunction - -function! s:find_man() abort - let l:win = 1 - while l:win <= winnr('$') - let l:buf = winbufnr(l:win) - if getbufvar(l:buf, '&filetype', '') ==# 'man' - execute l:win.'wincmd w' - return 1 - endif - let l:win += 1 - endwhile - return 0 -endfunction - -function! s:error(msg) abort - redraw - echohl ErrorMsg - echon 'man.vim: ' a:msg - echohl None -endfunction - -" see s:extract_sect_and_name_ref on why tolower(sect) -function! man#complete(arg_lead, cmd_line, cursor_pos) abort - let args = split(a:cmd_line) - let cmd_offset = index(args, 'Man') - if cmd_offset > 0 - " Prune all arguments up to :Man itself. Otherwise modifier commands like - " :tab, :vertical, etc. would lead to a wrong length. - let args = args[cmd_offset:] - endif - let l = len(args) - if l > 3 - return - elseif l ==# 1 - let name = '' - let sect = '' - elseif a:arg_lead =~# '^[^()]\+([^()]*$' - " cursor (|) is at ':Man printf(|' or ':Man 1 printf(|' - " The later is is allowed because of ':Man pri<TAB>'. - " It will offer 'priclass.d(1m)' even though section is specified as 1. - let tmp = split(a:arg_lead, '(') - let name = tmp[0] - let sect = tolower(get(tmp, 1, '')) - return s:complete(sect, '', name) - elseif args[1] !~# '^[^()]\+$' - " cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|' - " or ':Man 3() pri |' - return - elseif l ==# 2 - if empty(a:arg_lead) - " cursor (|) is at ':Man 1 |' - let name = '' - let sect = tolower(args[1]) - else - " cursor (|) is at ':Man pri|' - if a:arg_lead =~# '\/' - " if the name is a path, complete files - " TODO(nhooyr) why does this complete the last one automatically - return glob(a:arg_lead.'*', 0, 1) - endif - let name = a:arg_lead - let sect = '' - endif - elseif a:arg_lead !~# '^[^()]\+$' - " cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|' - return - else - " cursor (|) is at ':Man 3 pri|' - let name = a:arg_lead - let sect = tolower(args[1]) - endif - return s:complete(sect, sect, name) -endfunction - -function! s:get_paths(sect, name, do_fallback) abort - " callers must try-catch this, as some `man` implementations don't support `s:find_arg` - try - let mandirs = join(split(s:system(['man', s:find_arg]), ':\|\n'), ',') - let paths = globpath(mandirs, 'man?/'.a:name.'*.'.a:sect.'*', 0, 1) - try - " Prioritize the result from verify_exists as it obeys b:man_default_sects. - let first = s:verify_exists(a:sect, a:name) - let paths = filter(paths, 'v:val !=# first') - let paths = [first] + paths - catch - endtry - return paths - catch - if !a:do_fallback - throw v:exception - endif - - " Fallback to a single path, with the page we're trying to find. - try - return [s:verify_exists(a:sect, a:name)] - catch - return [] - endtry - endtry -endfunction - -function! s:complete(sect, psect, name) abort - let pages = s:get_paths(a:sect, a:name, v:false) - " We remove duplicates in case the same manpage in different languages was found. - return uniq(sort(map(pages, 's:format_candidate(v:val, a:psect)'), 'i')) -endfunction - -function! s:format_candidate(path, psect) abort - if a:path =~# '\.\%(pdf\|in\)$' " invalid extensions - return - endif - let [sect, name] = s:extract_sect_and_name_path(a:path) - if sect ==# a:psect - return name - elseif sect =~# a:psect.'.\+$' - " We include the section if the user provided section is a prefix - " of the actual section. - return name.'('.sect.')' - endif -endfunction - -" Called when Nvim is invoked as $MANPAGER. -function! man#init_pager() abort - if getline(1) =~# '^\s*$' - silent keepjumps 1delete _ - else - keepjumps 1 - endif - lua require("man").highlight_man_page() - " Guess the ref from the heading (which is usually uppercase, so we cannot - " know the correct casing, cf. `man glDrawArraysInstanced`). - let ref = substitute(matchstr(getline(1), '^[^)]\+)'), ' ', '_', 'g') - try - let b:man_sect = s:extract_sect_and_name_ref(ref)[0] - catch - let b:man_sect = '' - endtry - if -1 == match(bufname('%'), 'man:\/\/') " Avoid duplicate buffers, E95. - execute 'silent file man://'.tolower(fnameescape(ref)) - endif - - call s:set_options(v:true) -endfunction - -function! man#goto_tag(pattern, flags, info) abort - let [l:sect, l:name] = s:extract_sect_and_name_ref(a:pattern) - - let l:paths = s:get_paths(l:sect, l:name, v:true) - let l:structured = [] - - for l:path in l:paths - let [l:sect, l:name] = s:extract_sect_and_name_path(l:path) - let l:structured += [{ - \ 'name': l:name, - \ 'title': l:name . '(' . l:sect . ')' - \ }] - endfor - - if &cscopetag - " return only a single entry so we work well with :cstag (#11675) - let l:structured = l:structured[:0] - endif - - return map(l:structured, { - \ _, entry -> { - \ 'name': entry.name, - \ 'filename': 'man://' . entry.title, - \ 'cmd': '1' - \ } - \ }) -endfunction - -call man#init() diff --git a/runtime/autoload/python.vim b/runtime/autoload/python.vim index e45dbd9db8..1eaad09ef5 100644 --- a/runtime/autoload/python.vim +++ b/runtime/autoload/python.vim @@ -3,13 +3,19 @@ let s:keepcpo= &cpo set cpo&vim -" searchpair() can be slow, limit the time to 150 msec or what is put in -" g:pyindent_searchpair_timeout -let s:searchpair_timeout = get(g:, 'pyindent_searchpair_timeout', 150) - -" Identing inside parentheses can be very slow, regardless of the searchpair() -" timeout, so let the user disable this feature if he doesn't need it -let s:disable_parentheses_indenting = get(g:, 'pyindent_disable_parentheses_indenting', v:false) +" need to inspect some old g:pyindent_* variables to be backward compatible +let g:python_indent = extend(get(g:, 'python_indent', {}), #{ + \ closed_paren_align_last_line: v:true, + \ open_paren: get(g:, 'pyindent_open_paren', 'shiftwidth() * 2'), + \ nested_paren: get(g:, 'pyindent_nested_paren', 'shiftwidth()'), + \ continue: get(g:, 'pyindent_continue', 'shiftwidth() * 2'), + "\ searchpair() can be slow, limit the time to 150 msec or what is put in + "\ g:python_indent.searchpair_timeout + \ searchpair_timeout: get(g:, 'pyindent_searchpair_timeout', 150), + "\ Identing inside parentheses can be very slow, regardless of the searchpair() + "\ timeout, so let the user disable this feature if he doesn't need it + \ disable_parentheses_indenting: get(g:, 'pyindent_disable_parentheses_indenting', v:false), + \ }, 'keep') let s:maxoff = 50 " maximum number of lines to look backwards for () @@ -18,7 +24,7 @@ function s:SearchBracket(fromlnum, flags) \ {-> synstack('.', col('.')) \ ->map({_, id -> id->synIDattr('name')}) \ ->match('\%(Comment\|Todo\|String\)$') >= 0}, - \ [0, a:fromlnum - s:maxoff]->max(), s:searchpair_timeout) + \ [0, a:fromlnum - s:maxoff]->max(), g:python_indent.searchpair_timeout) endfunction " See if the specified line is already user-dedented from the expected value. @@ -38,7 +44,7 @@ function python#GetIndent(lnum, ...) if a:lnum > 1 && getline(a:lnum - 2) =~ '\\$' return indent(a:lnum - 1) endif - return indent(a:lnum - 1) + (exists("g:pyindent_continue") ? eval(g:pyindent_continue) : (shiftwidth() * 2)) + return indent(a:lnum - 1) + get(g:, 'pyindent_continue', g:python_indent.continue)->eval() endif " If the start of the line is in a string don't change the indent. @@ -55,7 +61,7 @@ function python#GetIndent(lnum, ...) return 0 endif - if s:disable_parentheses_indenting == 1 + if g:python_indent.disable_parentheses_indenting == 1 let plindent = indent(plnum) let plnumstart = plnum else @@ -70,8 +76,12 @@ function python#GetIndent(lnum, ...) " 100, 200, 300, 400) call cursor(a:lnum, 1) let [parlnum, parcol] = s:SearchBracket(a:lnum, 'nbW') - if parlnum > 0 && parcol != col([parlnum, '$']) - 1 - return parcol + if parlnum > 0 + if parcol != col([parlnum, '$']) - 1 + return parcol + elseif getline(a:lnum) =~ '^\s*[])}]' && !g:python_indent.closed_paren_align_last_line + return indent(parlnum) + endif endif call cursor(plnum, 1) @@ -123,9 +133,11 @@ function python#GetIndent(lnum, ...) " When the start is inside parenthesis, only indent one 'shiftwidth'. let [pp, _] = s:SearchBracket(a:lnum, 'bW') if pp > 0 - return indent(plnum) + (exists("g:pyindent_nested_paren") ? eval(g:pyindent_nested_paren) : shiftwidth()) + return indent(plnum) + \ + get(g:, 'pyindent_nested_paren', g:python_indent.nested_paren)->eval() endif - return indent(plnum) + (exists("g:pyindent_open_paren") ? eval(g:pyindent_open_paren) : (shiftwidth() * 2)) + return indent(plnum) + \ + get(g:, 'pyindent_open_paren', g:python_indent.open_paren)->eval() endif if plnumstart == p return indent(plnum) diff --git a/runtime/colors/blue.vim b/runtime/colors/blue.vim index 0d2f07c654..652046b561 100644 --- a/runtime/colors/blue.vim +++ b/runtime/colors/blue.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Steven Vertigan <steven@vertigan.wattle.id.au> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Fri Aug 5 12:25:12 2022 +" Last Updated: Fri 02 Sep 2022 09:41:44 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=dark hi clear let g:colors_name = 'blue' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'] @@ -57,7 +57,7 @@ hi ToolbarLine guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NO hi VertSplit guifg=#008787 guibg=NONE gui=NONE cterm=NONE hi Visual guifg=#ffffff guibg=#008787 gui=NONE cterm=NONE hi VisualNOS guifg=#008787 guibg=#ffffff gui=NONE cterm=NONE -hi WarningMsg guifg=#d70000 guibg=NONE gui=NONE cterm=NONE +hi WarningMsg guifg=#d787d7 guibg=NONE gui=NONE cterm=NONE hi WildMenu guifg=#000087 guibg=#ffd700 gui=NONE cterm=NONE hi debugBreakpoint guifg=#00ff00 guibg=#000087 gui=reverse cterm=reverse hi debugPC guifg=#5fffff guibg=#000087 gui=reverse cterm=reverse @@ -120,6 +120,8 @@ hi! link Structure Type hi! link Tag Special hi! link Typedef Type hi! link Terminal Normal +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi DiffAdd guifg=#ffffff guibg=#5f875f gui=NONE cterm=NONE hi DiffChange guifg=#ffffff guibg=#5f87af gui=NONE cterm=NONE hi DiffText guifg=#000000 guibg=#c6c6c6 gui=NONE cterm=NONE @@ -165,7 +167,7 @@ if s:t_Co >= 256 hi VertSplit ctermfg=30 ctermbg=NONE cterm=NONE hi Visual ctermfg=231 ctermbg=30 cterm=NONE hi VisualNOS ctermfg=30 ctermbg=231 cterm=NONE - hi WarningMsg ctermfg=160 ctermbg=NONE cterm=NONE + hi WarningMsg ctermfg=176 ctermbg=NONE cterm=NONE hi WildMenu ctermfg=18 ctermbg=220 cterm=NONE hi debugBreakpoint ctermfg=46 ctermbg=18 cterm=reverse hi debugPC ctermfg=87 ctermbg=18 cterm=reverse @@ -228,6 +230,8 @@ if s:t_Co >= 256 hi! link Tag Special hi! link Typedef Type hi! link Terminal Normal + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi DiffAdd ctermfg=231 ctermbg=65 cterm=NONE hi DiffChange ctermfg=231 ctermbg=67 cterm=NONE hi DiffText ctermfg=16 ctermbg=251 cterm=NONE @@ -276,7 +280,7 @@ if s:t_Co >= 16 hi VertSplit ctermfg=darkcyan ctermbg=NONE cterm=NONE hi Visual ctermfg=white ctermbg=darkcyan cterm=NONE hi VisualNOS ctermfg=darkcyan ctermbg=white cterm=NONE - hi WarningMsg ctermfg=red ctermbg=NONE cterm=NONE + hi WarningMsg ctermfg=magenta ctermbg=NONE cterm=NONE hi WildMenu ctermfg=darkblue ctermbg=yellow cterm=NONE hi debugBreakpoint ctermfg=green ctermbg=darkblue cterm=reverse hi debugPC ctermfg=cyan ctermbg=darkblue cterm=reverse @@ -339,6 +343,8 @@ if s:t_Co >= 16 hi! link Tag Special hi! link Typedef Type hi! link Terminal Normal + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi DiffAdd ctermfg=white ctermbg=darkgreen cterm=NONE hi DiffChange ctermfg=white ctermbg=blue cterm=NONE hi DiffText ctermfg=black ctermbg=grey cterm=NONE @@ -449,6 +455,8 @@ if s:t_Co >= 8 hi! link Tag Special hi! link Typedef Type hi! link Terminal Normal + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi DiffAdd ctermfg=white ctermbg=darkgreen cterm=NONE hi DiffChange ctermfg=white ctermbg=darkblue cterm=NONE hi DiffText ctermfg=black ctermbg=grey cterm=NONE diff --git a/runtime/colors/darkblue.vim b/runtime/colors/darkblue.vim index b4c286af37..4ce8687415 100644 --- a/runtime/colors/darkblue.vim +++ b/runtime/colors/darkblue.vim @@ -4,7 +4,7 @@ " Maintainer: Original author Bohdan Vlasyuk <bohdan@vstu.edu.ua> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:06 2022 +" Last Updated: Fri 02 Sep 2022 09:40:36 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=dark hi clear let g:colors_name = 'darkblue' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#8b0000', '#90f020', '#ffa500', '#00008b', '#8b008b', '#008b8b', '#c0c0c0', '#808080', '#ffa0a0', '#90f020', '#ffff60', '#0030ff', '#ff00ff', '#90fff0', '#ffffff'] @@ -65,6 +65,8 @@ hi! link diffCommon WarningMsg hi! link diffBDiffer WarningMsg hi! link lCursor Cursor hi! link CurSearch Search +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#c0c0c0 guibg=#000040 gui=NONE cterm=NONE hi Conceal guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi ColorColumn guifg=#c0c0c0 guibg=#8b0000 gui=NONE cterm=NONE @@ -171,6 +173,8 @@ if s:t_Co >= 256 hi! link diffBDiffer WarningMsg hi! link lCursor Cursor hi! link CurSearch Search + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=252 ctermbg=17 cterm=NONE hi Conceal ctermfg=NONE ctermbg=NONE cterm=NONE hi ColorColumn ctermfg=252 ctermbg=88 cterm=NONE diff --git a/runtime/colors/delek.vim b/runtime/colors/delek.vim index bd9c5cf52d..38f21d7156 100644 --- a/runtime/colors/delek.vim +++ b/runtime/colors/delek.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer David Schweikert <david@schweikert.ch> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:07 2022 +" Last Updated: Sun 04 Sep 2022 09:31:26 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=light hi clear let g:colors_name = 'delek' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#ffffff', '#0000ff', '#00cd00', '#cd00cd', '#008b8b', '#0000ff', '#ff1493', '#bcbcbc', '#ee0000', '#0000ff', '#00cd00', '#cd00cd', '#008b8b', '#0000ff', '#ff1493', '#000000'] @@ -25,6 +25,8 @@ hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine hi! link ErrorMsg Error +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE hi EndOfBuffer guifg=#bcbcbc guibg=NONE gui=NONE cterm=NONE hi StatusLine guifg=#ffff00 guibg=#00008b gui=bold cterm=bold @@ -57,7 +59,7 @@ hi Error guifg=#ff0000 guibg=#ffffff gui=reverse cterm=reverse hi WarningMsg guifg=#cd00cd guibg=#ffffff gui=NONE cterm=NONE hi MoreMsg guifg=#000000 guibg=#ffffff gui=bold cterm=bold hi ModeMsg guifg=#000000 guibg=#ffffff gui=bold cterm=bold -hi Question guifg=#00cd00 guibg=NONE gui=bold cterm=bold +hi Question guifg=#008700 guibg=NONE gui=bold cterm=bold hi Todo guifg=#000000 guibg=#ffff00 gui=NONE cterm=NONE hi MatchParen guifg=#ffffff guibg=#ff1493 gui=NONE cterm=NONE hi Search guifg=#ffffff guibg=#cd00cd gui=NONE cterm=NONE @@ -97,6 +99,8 @@ if s:t_Co >= 256 hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine hi! link ErrorMsg Error + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=16 ctermbg=231 cterm=NONE hi EndOfBuffer ctermfg=250 ctermbg=NONE cterm=NONE hi StatusLine ctermfg=226 ctermbg=18 cterm=bold @@ -129,7 +133,7 @@ if s:t_Co >= 256 hi WarningMsg ctermfg=164 ctermbg=231 cterm=NONE hi MoreMsg ctermfg=16 ctermbg=231 cterm=bold hi ModeMsg ctermfg=16 ctermbg=231 cterm=bold - hi Question ctermfg=40 ctermbg=NONE cterm=bold + hi Question ctermfg=28 ctermbg=NONE cterm=bold hi Todo ctermfg=16 ctermbg=226 cterm=NONE hi MatchParen ctermfg=231 ctermbg=198 cterm=NONE hi Search ctermfg=231 ctermbg=164 cterm=NONE diff --git a/runtime/colors/desert.vim b/runtime/colors/desert.vim index e9b8108d19..4bfdf7eabd 100644 --- a/runtime/colors/desert.vim +++ b/runtime/colors/desert.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Hans Fugal <hans@fugal.net> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:08 2022 +" Last Updated: Fri 02 Sep 2022 09:39:21 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=dark hi clear let g:colors_name = 'desert' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#7f7f8c', '#cd5c5c', '#9acd32', '#bdb76b', '#75a0ff', '#eeee00', '#cd853f', '#666666', '#8a7f7f', '#ff0000', '#89fb98', '#f0e68c', '#6dceeb', '#ffde9b', '#ffa0a0', '#c2bfa5'] @@ -25,6 +25,8 @@ hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine hi! link EndOfBuffer NonText +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#ffffff guibg=#333333 gui=NONE cterm=NONE hi StatusLine guifg=#333333 guibg=#c2bfa5 gui=NONE cterm=NONE hi StatusLineNC guifg=#7f7f8c guibg=#c2bfa5 gui=NONE cterm=NONE @@ -97,6 +99,8 @@ if s:t_Co >= 256 hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine hi! link EndOfBuffer NonText + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=231 ctermbg=236 cterm=NONE hi StatusLine ctermfg=236 ctermbg=144 cterm=NONE hi StatusLineNC ctermfg=242 ctermbg=144 cterm=NONE diff --git a/runtime/colors/elflord.vim b/runtime/colors/elflord.vim index 4bfda2a083..a9bdac7a1d 100644 --- a/runtime/colors/elflord.vim +++ b/runtime/colors/elflord.vim @@ -3,7 +3,7 @@ " Maintainer: original maintainer Ron Aaron <ron@ronware.org> " Website: https://www.github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:08 2022 +" Last Updated: Fri 02 Sep 2022 09:44:22 MSK " Generated by Colortemplate v2.2.0 @@ -12,7 +12,7 @@ set background=dark hi clear let g:colors_name = 'elflord' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 hi! link Terminal Normal hi! link Boolean Constant @@ -43,6 +43,8 @@ hi! link lCursor Cursor hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'] diff --git a/runtime/colors/evening.vim b/runtime/colors/evening.vim index 7e0609e9c4..23ff8421e8 100644 --- a/runtime/colors/evening.vim +++ b/runtime/colors/evening.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Steven Vertigan <steven@vertigan.wattle.id.au> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:09 2022 +" Last Updated: Sun 04 Sep 2022 09:48:34 MSK " Generated by Colortemplate v2.2.0 @@ -13,10 +13,10 @@ set background=dark hi clear let g:colors_name = 'evening' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') - let g:terminal_ansi_colors = ['#000000', '#ffa500', '#2e8b57', '#ffff00', '#006faf', '#8b008b', '#008b8b', '#bebebe', '#4d4d4d', '#ff5f5f', '#00ff00', '#ffff60', '#0087ff', '#ff80ff', '#00ffff', '#ffffff'] + let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0087ff', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'] endif hi! link VertSplit StatusLineNC hi! link StatusLineTerm StatusLine @@ -64,6 +64,8 @@ hi! link String Constant hi! link Structure Type hi! link Tag Special hi! link Typedef Type +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#ffffff guibg=#333333 gui=NONE cterm=NONE hi ColorColumn guifg=NONE guibg=#8b0000 gui=NONE cterm=NONE hi CursorLine guifg=NONE guibg=#666666 gui=NONE cterm=NONE @@ -98,7 +100,7 @@ hi ToolbarButton guifg=NONE guibg=#999999 gui=bold cterm=bold hi ToolbarLine guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi Visual guifg=#ffffff guibg=#999999 gui=NONE cterm=NONE hi VisualNOS guifg=NONE guibg=NONE gui=bold,underline ctermfg=NONE ctermbg=NONE cterm=bold,underline -hi WarningMsg guifg=#8b0000 guibg=NONE gui=NONE cterm=NONE +hi WarningMsg guifg=#ff0000 guibg=NONE gui=NONE cterm=NONE hi WildMenu guifg=#000000 guibg=#ffff00 gui=bold cterm=bold hi debugBreakpoint guifg=#00008b guibg=#ff0000 gui=NONE cterm=NONE hi debugPC guifg=#00008b guibg=#0000ff gui=NONE cterm=NONE @@ -170,6 +172,8 @@ if s:t_Co >= 256 hi! link Structure Type hi! link Tag Special hi! link Typedef Type + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=231 ctermbg=236 cterm=NONE hi ColorColumn ctermfg=NONE ctermbg=88 cterm=NONE hi CursorLine ctermfg=NONE ctermbg=241 cterm=NONE @@ -204,7 +208,7 @@ if s:t_Co >= 256 hi ToolbarLine ctermfg=NONE ctermbg=NONE cterm=NONE hi Visual ctermfg=231 ctermbg=246 cterm=NONE hi VisualNOS ctermfg=NONE ctermbg=NONE cterm=bold,underline - hi WarningMsg ctermfg=88 ctermbg=NONE cterm=NONE + hi WarningMsg ctermfg=196 ctermbg=NONE cterm=NONE hi WildMenu ctermfg=16 ctermbg=226 cterm=bold hi debugBreakpoint ctermfg=18 ctermbg=196 cterm=NONE hi debugPC ctermfg=18 ctermbg=21 cterm=NONE @@ -279,6 +283,8 @@ if s:t_Co >= 16 hi! link Structure Type hi! link Tag Special hi! link Typedef Type + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=white ctermbg=black cterm=NONE hi ColorColumn ctermfg=white ctermbg=darkred cterm=NONE hi CursorLine ctermfg=NONE ctermbg=NONE cterm=underline @@ -313,7 +319,7 @@ if s:t_Co >= 16 hi ToolbarLine ctermfg=NONE ctermbg=NONE cterm=NONE hi Visual ctermfg=white ctermbg=darkgray cterm=NONE hi VisualNOS ctermfg=NONE ctermbg=NONE cterm=bold,underline - hi WarningMsg ctermfg=darkred ctermbg=NONE cterm=NONE + hi WarningMsg ctermfg=red ctermbg=NONE cterm=NONE hi WildMenu ctermfg=black ctermbg=darkyellow cterm=bold hi debugBreakpoint ctermfg=darkblue ctermbg=red cterm=NONE hi debugPC ctermfg=darkblue ctermbg=blue cterm=NONE @@ -494,13 +500,26 @@ endif " Color: grey30 #4d4d4d 239 darkgray " Color: grey40 #666666 241 darkgray " Color: grey60 #999999 246 darkgray -" Color: xtermblue #0087ff 33 blue -" Color: xtermdarkblue #006faf 25 darkblue -" Color: xtermred #ff5f5f 203 red " Color: comment #80a0ff 111 lightblue " Color: darkred #8b0000 88 darkred -" Term colors: black orange seagreen yellow xtermdarkblue darkmagenta darkcyan grey -" Term colors: grey30 xtermred green lightyellow xtermblue magenta cyan white +" Color: x_black #000000 16 black +" Color: x_darkred #cd0000 160 darkred +" Color: x_darkgreen #00cd00 40 darkgreen +" Color: x_darkyellow #cdcd00 184 darkyellow +" Color: x_darkblue_m #0087ff 33 darkblue +" Color: x_darkmagenta #cd00cd 164 darkmagenta +" Color: x_darkcyan #00cdcd 44 darkcyan +" Color: x_gray #e5e5e5 254 gray +" Color: x_darkgray #7f7f7f 244 darkgray +" Color: x_red #ff0000 196 red +" Color: x_green #00ff00 46 green +" Color: x_yellow #ffff00 226 yellow +" Color: x_blue #5c5cff 63 blue +" Color: x_magenta #ff00ff 201 magenta +" Color: x_cyan #00ffff 51 cyan +" Color: x_white #ffffff 231 white +" Term colors: x_black x_darkred x_darkgreen x_darkyellow x_darkblue_m x_darkmagenta x_darkcyan x_gray +" Term colors: x_darkgray x_red x_green x_yellow x_blue x_magenta x_cyan x_white " Color: bgDiffA #5F875F 65 darkgreen " Color: bgDiffC #5F87AF 67 blue " Color: bgDiffD #AF5FAF 133 magenta diff --git a/runtime/colors/habamax.vim b/runtime/colors/habamax.vim index 169fc28021..049413beef 100644 --- a/runtime/colors/habamax.vim +++ b/runtime/colors/habamax.vim @@ -4,7 +4,7 @@ " Maintainer: Maxim Kim <habamax@gmail.com> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:10 2022 +" Last Updated: Fri 02 Sep 2022 09:45:11 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=dark hi clear let g:colors_name = 'habamax' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#1c1c1c', '#d75f5f', '#87af87', '#afaf87', '#5f87af', '#af87af', '#5f8787', '#9e9e9e', '#767676', '#d7875f', '#afd7af', '#d7d787', '#87afd7', '#d7afd7', '#87afaf', '#bcbcbc'] @@ -21,6 +21,8 @@ endif hi! link Terminal Normal hi! link StatuslineTerm Statusline hi! link StatuslineTermNC StatuslineNC +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi! link javaScriptFunction Statement hi! link javaScriptIdentifier Statement hi! link sqlKeyword Statement @@ -142,6 +144,8 @@ if s:t_Co >= 256 hi! link Terminal Normal hi! link StatuslineTerm Statusline hi! link StatuslineTermNC StatuslineNC + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi! link javaScriptFunction Statement hi! link javaScriptIdentifier Statement hi! link sqlKeyword Statement diff --git a/runtime/colors/industry.vim b/runtime/colors/industry.vim index 359600fa4a..3f6726038e 100644 --- a/runtime/colors/industry.vim +++ b/runtime/colors/industry.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Shian Lee. " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:11 2022 +" Last Updated: Sun 04 Sep 2022 09:50:04 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=dark hi clear let g:colors_name = 'industry' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#303030', '#870000', '#5fd75f', '#afaf00', '#87afff', '#af00af', '#00afaf', '#6c6c6c', '#444444', '#ff0000', '#00ff00', '#ffff00', '#005fff', '#ff00ff', '#00ffff', '#ffffff'] @@ -51,7 +51,7 @@ hi Underlined guifg=#87afff guibg=NONE gui=underline cterm=underline hi Error guifg=#ffffff guibg=#ff0000 gui=NONE cterm=NONE hi ErrorMsg guifg=#ffffff guibg=#ff0000 gui=NONE cterm=NONE hi ModeMsg guifg=#ffffff guibg=NONE gui=bold cterm=bold -hi WarningMsg guifg=#870000 guibg=NONE gui=bold cterm=bold +hi WarningMsg guifg=#ff0000 guibg=NONE gui=bold cterm=bold hi MoreMsg guifg=#5fd75f guibg=NONE gui=bold cterm=bold hi Question guifg=#00ff00 guibg=NONE gui=bold cterm=bold hi Todo guifg=#005fff guibg=#ffff00 gui=NONE cterm=NONE @@ -84,6 +84,8 @@ hi! link LineNrBelow LineNr hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi DiffAdd guifg=#ffffff guibg=#5f875f gui=NONE cterm=NONE hi DiffChange guifg=#ffffff guibg=#5f87af gui=NONE cterm=NONE hi DiffText guifg=#000000 guibg=#c6c6c6 gui=NONE cterm=NONE @@ -123,7 +125,7 @@ if s:t_Co >= 256 hi Error ctermfg=231 ctermbg=196 cterm=NONE hi ErrorMsg ctermfg=231 ctermbg=196 cterm=NONE hi ModeMsg ctermfg=231 ctermbg=NONE cterm=bold - hi WarningMsg ctermfg=88 ctermbg=NONE cterm=bold + hi WarningMsg ctermfg=196 ctermbg=NONE cterm=bold hi MoreMsg ctermfg=77 ctermbg=NONE cterm=bold hi Question ctermfg=46 ctermbg=NONE cterm=bold hi Todo ctermfg=27 ctermbg=226 cterm=NONE @@ -156,6 +158,8 @@ if s:t_Co >= 256 hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi DiffAdd ctermfg=231 ctermbg=65 cterm=NONE hi DiffChange ctermfg=231 ctermbg=67 cterm=NONE hi DiffText ctermfg=16 ctermbg=251 cterm=NONE @@ -198,7 +202,7 @@ if s:t_Co >= 16 hi Error ctermfg=white ctermbg=red cterm=NONE hi ErrorMsg ctermfg=white ctermbg=red cterm=NONE hi ModeMsg ctermfg=white ctermbg=NONE cterm=bold - hi WarningMsg ctermfg=darkred ctermbg=NONE cterm=bold + hi WarningMsg ctermfg=red ctermbg=NONE cterm=bold hi MoreMsg ctermfg=darkgreen ctermbg=NONE cterm=bold hi Question ctermfg=green ctermbg=NONE cterm=bold hi Todo ctermfg=blue ctermbg=yellow cterm=NONE @@ -231,6 +235,8 @@ if s:t_Co >= 16 hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi DiffAdd ctermfg=white ctermbg=darkgreen cterm=NONE hi DiffChange ctermfg=white ctermbg=blue cterm=NONE hi DiffText ctermfg=black ctermbg=grey cterm=NONE diff --git a/runtime/colors/koehler.vim b/runtime/colors/koehler.vim index 04476d1ee9..f414eeb3e6 100644 --- a/runtime/colors/koehler.vim +++ b/runtime/colors/koehler.vim @@ -3,7 +3,7 @@ " Maintainer: original maintainer Ron Aaron <ron@ronware.org> " Website: https://www.github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:12 2022 +" Last Updated: Fri 02 Sep 2022 09:23:56 MSK " Generated by Colortemplate v2.2.0 @@ -12,7 +12,7 @@ set background=dark hi clear let g:colors_name = 'koehler' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 hi! link Terminal Normal hi! link Boolean Constant @@ -49,6 +49,8 @@ hi! link lCursor Cursor hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'] diff --git a/runtime/colors/lunaperche.vim b/runtime/colors/lunaperche.vim index d6c73eb28c..159e04cc0b 100644 --- a/runtime/colors/lunaperche.vim +++ b/runtime/colors/lunaperche.vim @@ -4,14 +4,14 @@ " Maintainer: Maxim Kim <habamax@gmail.com> " Website: https://www.github.com/vim/colorschemes " License: Vim License (see `:help license`) -" Last Updated: Thu Aug 18 14:36:32 2022 +" Last Updated: Fri 16 Sep 2022 13:15:33 MSK " Generated by Colortemplate v2.2.0 hi clear let g:colors_name = 'lunaperche' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 hi! link helpVim Title hi! link helpHeader Title @@ -26,12 +26,15 @@ hi! link fugitiveUnstagedModifier PreProc hi! link fugitiveHash Constant hi! link diffFile PreProc hi! link markdownHeadingDelimiter Special -hi! link rstSectionDelimiter PreProc -hi! link rstDirective Special +hi! link rstSectionDelimiter Statement +hi! link rstDirective PreProc hi! link rstHyperlinkReference Special -hi! link rstFieldName Special +hi! link rstFieldName Constant hi! link rstDelimiter Special hi! link rstInterpretedText Special +hi! link rstCodeBlock Normal +hi! link rstLiteralBlock rstCodeBlock +hi! link markdownUrl String hi! link colortemplateKey Statement hi! link xmlTagName Statement hi! link javaScriptFunction Statement @@ -81,25 +84,52 @@ hi! link shOption Normal hi! link shCommandSub Normal hi! link shDerefPattern shQuote hi! link shDerefOp Special +hi! link phpStorageClass Statement +hi! link phpStructure Statement +hi! link phpInclude Statement +hi! link phpDefine Statement +hi! link phpSpecialFunction Normal +hi! link phpParent Normal +hi! link phpComparison Normal +hi! link phpOperator Normal +hi! link phpVarSelector Special +hi! link phpMemberSelector Special +hi! link phpDocCustomTags phpDocTags +hi! link javaExternal Statement +hi! link javaType Statement +hi! link javaScopeDecl Statement +hi! link javaClassDecl Statement +hi! link javaStorageClass Statement +hi! link javaDocParam PreProc +hi! link csStorage Statement +hi! link csAccessModifier Statement +hi! link csClass Statement +hi! link csModifier Statement +hi! link csAsyncModifier Statement +hi! link csLogicSymbols Normal +hi! link csClassType Normal +hi! link csType Statement hi! link Terminal Normal hi! link StatuslineTerm Statusline hi! link StatuslineTermNC StatuslineNC hi! link LineNrAbove LineNr hi! link LineNrBelow LineNr +hi! link MessageWindow PMenu +hi! link PopupNotification Todo if &background ==# 'dark' if (has('termguicolors') && &termguicolors) || has('gui_running') - let g:terminal_ansi_colors = ['#000000', '#af5f5f', '#5faf5f', '#af875f', '#5f87af', '#d787af', '#5fafaf', '#c6c6c6', '#767676', '#ff5f5f', '#5fd75f', '#ffd787', '#87afd7', '#ffafd7', '#5fd7d7', '#ffffff'] + let g:terminal_ansi_colors = ['#000000', '#af5f5f', '#5faf5f', '#af875f', '#5f87af', '#d787d7', '#5fafaf', '#c6c6c6', '#767676', '#ff5f5f', '#5fd75f', '#ffd787', '#5fafff', '#ff87ff', '#5fd7d7', '#ffffff'] endif hi Normal guifg=#c6c6c6 guibg=#000000 gui=NONE cterm=NONE - hi Statusline guifg=#000000 guibg=#c6c6c6 gui=bold cterm=bold - hi StatuslineNC guifg=#000000 guibg=#767676 gui=NONE cterm=NONE + hi Statusline guifg=#c6c6c6 guibg=#000000 gui=bold,reverse cterm=bold,reverse + hi StatuslineNC guifg=#767676 guibg=#000000 gui=reverse cterm=reverse hi VertSplit guifg=#767676 guibg=#767676 gui=NONE cterm=NONE hi TabLine guifg=#000000 guibg=#c6c6c6 gui=NONE cterm=NONE hi TabLineFill guifg=NONE guibg=#767676 gui=NONE cterm=NONE hi TabLineSel guifg=#ffffff guibg=#000000 gui=bold cterm=bold hi ToolbarLine guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi ToolbarButton guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE - hi QuickFixLine guifg=#000000 guibg=#87afd7 gui=NONE cterm=NONE + hi QuickFixLine guifg=#000000 guibg=#5fafff gui=NONE cterm=NONE hi CursorLineNr guifg=#ffffff guibg=NONE gui=bold cterm=bold hi LineNr guifg=#585858 guibg=NONE gui=NONE cterm=NONE hi NonText guifg=#585858 guibg=NONE gui=NONE cterm=NONE @@ -107,7 +137,7 @@ if &background ==# 'dark' hi EndOfBuffer guifg=#585858 guibg=NONE gui=NONE cterm=NONE hi SpecialKey guifg=#585858 guibg=NONE gui=NONE cterm=NONE hi Pmenu guifg=NONE guibg=#1c1c1c gui=NONE cterm=NONE - hi PmenuSel guifg=NONE guibg=#005f00 gui=NONE cterm=NONE + hi PmenuSel guifg=NONE guibg=#444444 gui=NONE cterm=NONE hi PmenuThumb guifg=NONE guibg=#c6c6c6 gui=NONE cterm=NONE hi PmenuSbar guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi SignColumn guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE @@ -115,7 +145,7 @@ if &background ==# 'dark' hi ErrorMsg guifg=#ffffff guibg=#ff5f5f gui=NONE cterm=NONE hi ModeMsg guifg=#ffd787 guibg=NONE gui=reverse cterm=reverse hi MoreMsg guifg=#5fd75f guibg=NONE gui=NONE cterm=NONE - hi Question guifg=#ffafd7 guibg=NONE gui=NONE cterm=NONE + hi Question guifg=#ff87ff guibg=NONE gui=NONE cterm=NONE hi WarningMsg guifg=#ff5f5f guibg=NONE gui=NONE cterm=NONE hi Todo guifg=#5fd7d7 guibg=#000000 gui=reverse cterm=reverse hi Search guifg=#000000 guibg=#ffd787 gui=NONE cterm=NONE @@ -124,7 +154,7 @@ if &background ==# 'dark' hi WildMenu guifg=#000000 guibg=#ffd787 gui=bold cterm=bold hi debugPC guifg=#5f87af guibg=NONE gui=reverse cterm=reverse hi debugBreakpoint guifg=#5fafaf guibg=NONE gui=reverse cterm=reverse - hi Cursor guifg=#ffffff guibg=#000000 gui=reverse cterm=reverse + hi Cursor guifg=NONE guibg=NONE gui=reverse ctermfg=NONE ctermbg=NONE cterm=reverse hi lCursor guifg=#ff5fff guibg=#000000 gui=reverse cterm=reverse hi Visual guifg=#ffffff guibg=#005f87 gui=NONE cterm=NONE hi MatchParen guifg=#c5e7c5 guibg=#000000 gui=reverse cterm=reverse @@ -136,17 +166,18 @@ if &background ==# 'dark' hi SpellBad guifg=NONE guibg=NONE guisp=#ff5f5f gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE hi SpellCap guifg=NONE guibg=NONE guisp=#5fafaf gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE hi SpellLocal guifg=NONE guibg=NONE guisp=#5faf5f gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE - hi SpellRare guifg=NONE guibg=NONE guisp=#ffafd7 gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE - hi Comment guifg=#87afd7 guibg=NONE gui=NONE cterm=NONE - hi Constant guifg=#ffd787 guibg=NONE gui=NONE cterm=NONE + hi SpellRare guifg=NONE guibg=NONE guisp=#ff87ff gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE + hi Comment guifg=#5fafff guibg=NONE gui=NONE cterm=NONE + hi Constant guifg=#ff87ff guibg=NONE gui=NONE cterm=NONE + hi String guifg=#ffd787 guibg=NONE gui=NONE cterm=NONE hi Identifier guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE - hi Statement guifg=#eeeeee guibg=NONE gui=bold cterm=bold - hi Type guifg=#5fd75f guibg=NONE gui=bold cterm=bold - hi PreProc guifg=#af875f guibg=NONE gui=NONE cterm=NONE + hi Statement guifg=#e4e4e4 guibg=NONE gui=bold cterm=bold + hi Type guifg=#5fd75f guibg=NONE gui=NONE cterm=NONE + hi PreProc guifg=#5fd7d7 guibg=NONE gui=NONE cterm=NONE hi Special guifg=#5fafaf guibg=NONE gui=NONE cterm=NONE hi Underlined guifg=NONE guibg=NONE gui=underline ctermfg=NONE ctermbg=NONE cterm=underline hi Title guifg=NONE guibg=NONE gui=bold ctermfg=NONE ctermbg=NONE cterm=bold - hi Directory guifg=#5fd7d7 guibg=NONE gui=bold cterm=bold + hi Directory guifg=#5fafff guibg=NONE gui=bold cterm=bold hi Conceal guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi Ignore guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi DiffAdd guifg=#000000 guibg=#af87af gui=NONE cterm=NONE @@ -155,8 +186,8 @@ if &background ==# 'dark' hi DiffDelete guifg=#d78787 guibg=NONE gui=NONE cterm=NONE hi diffAdded guifg=#5fd75f guibg=NONE gui=NONE cterm=NONE hi diffRemoved guifg=#d78787 guibg=NONE gui=NONE cterm=NONE - hi diffSubname guifg=#ffafd7 guibg=NONE gui=NONE cterm=NONE - hi dirType guifg=#d787af guibg=NONE gui=NONE cterm=NONE + hi diffSubname guifg=#ff87ff guibg=NONE gui=NONE cterm=NONE + hi dirType guifg=#d787d7 guibg=NONE gui=NONE cterm=NONE hi dirPermissionUser guifg=#5faf5f guibg=NONE gui=NONE cterm=NONE hi dirPermissionGroup guifg=#af875f guibg=NONE gui=NONE cterm=NONE hi dirPermissionOther guifg=#5fafaf guibg=NONE gui=NONE cterm=NONE @@ -164,17 +195,16 @@ if &background ==# 'dark' hi dirGroup guifg=#767676 guibg=NONE gui=NONE cterm=NONE hi dirTime guifg=#767676 guibg=NONE gui=NONE cterm=NONE hi dirSize guifg=#ffd787 guibg=NONE gui=NONE cterm=NONE - hi dirSizeMod guifg=#d787af guibg=NONE gui=NONE cterm=NONE + hi dirSizeMod guifg=#d787d7 guibg=NONE gui=NONE cterm=NONE hi FilterMenuDirectorySubtle guifg=#878787 guibg=NONE gui=NONE cterm=NONE hi dirFilterMenuBookmarkPath guifg=#878787 guibg=NONE gui=NONE cterm=NONE hi dirFilterMenuHistoryPath guifg=#878787 guibg=NONE gui=NONE cterm=NONE hi FilterMenuLineNr guifg=#878787 guibg=NONE gui=NONE cterm=NONE - hi CocMenuSel guifg=NONE guibg=#005f00 gui=NONE cterm=NONE hi CocSearch guifg=#ffd787 guibg=NONE gui=NONE cterm=NONE else " Light background if (has('termguicolors') && &termguicolors) || has('gui_running') - let g:terminal_ansi_colors = ['#000000', '#870000', '#008700', '#875f00', '#005faf', '#870087', '#005f5f', '#808080', '#767676', '#d70000', '#87d787', '#d7d787', '#0087d7', '#af00af', '#00afaf', '#ffffff'] + let g:terminal_ansi_colors = ['#000000', '#af0000', '#008700', '#af5f00', '#005fd7', '#af00af', '#005f5f', '#808080', '#767676', '#d70000', '#87d787', '#ffd787', '#0087d7', '#ff00ff', '#008787', '#ffffff'] endif hi Normal guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE hi Statusline guifg=#ffffff guibg=#000000 gui=bold cterm=bold @@ -193,46 +223,47 @@ else hi EndOfBuffer guifg=#9e9e9e guibg=NONE gui=NONE cterm=NONE hi SpecialKey guifg=#9e9e9e guibg=NONE gui=NONE cterm=NONE hi Pmenu guifg=NONE guibg=#eeeeee gui=NONE cterm=NONE - hi PmenuSel guifg=NONE guibg=#afd7af gui=NONE cterm=NONE + hi PmenuSel guifg=NONE guibg=#c6c6c6 gui=NONE cterm=NONE hi PmenuThumb guifg=NONE guibg=#767676 gui=NONE cterm=NONE hi PmenuSbar guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi SignColumn guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi Error guifg=#ffffff guibg=#d70000 gui=NONE cterm=NONE hi ErrorMsg guifg=#ffffff guibg=#d70000 gui=NONE cterm=NONE - hi ModeMsg guifg=#d7d787 guibg=#000000 gui=reverse cterm=reverse + hi ModeMsg guifg=#ffd787 guibg=#000000 gui=reverse cterm=reverse hi MoreMsg guifg=#008700 guibg=NONE gui=bold cterm=bold - hi Question guifg=#870087 guibg=NONE gui=bold cterm=bold + hi Question guifg=#af00af guibg=NONE gui=bold cterm=bold hi WarningMsg guifg=#d70000 guibg=NONE gui=bold cterm=bold - hi Todo guifg=#005f5f guibg=#ffffff gui=reverse cterm=reverse - hi Search guifg=#000000 guibg=#d7d787 gui=NONE cterm=NONE + hi Todo guifg=#008787 guibg=#ffffff gui=reverse cterm=reverse + hi Search guifg=#000000 guibg=#ffd787 gui=NONE cterm=NONE hi IncSearch guifg=#000000 guibg=#87d787 gui=NONE cterm=NONE hi CurSearch guifg=#000000 guibg=#87d787 gui=NONE cterm=NONE - hi WildMenu guifg=#000000 guibg=#d7d787 gui=bold cterm=bold - hi debugPC guifg=#005faf guibg=NONE gui=reverse cterm=reverse + hi WildMenu guifg=#000000 guibg=#ffd787 gui=bold cterm=bold + hi debugPC guifg=#005fd7 guibg=NONE gui=reverse cterm=reverse hi debugBreakpoint guifg=#005f5f guibg=NONE gui=reverse cterm=reverse - hi Cursor guifg=#000000 guibg=#ffffff gui=reverse cterm=reverse + hi Cursor guifg=NONE guibg=NONE gui=reverse ctermfg=NONE ctermbg=NONE cterm=reverse hi lCursor guifg=#ff00ff guibg=#000000 gui=reverse cterm=reverse hi Visual guifg=#ffffff guibg=#5f87af gui=NONE cterm=NONE hi MatchParen guifg=NONE guibg=#c5e7c5 gui=NONE cterm=NONE - hi VisualNOS guifg=#ffffff guibg=#00afaf gui=NONE cterm=NONE + hi VisualNOS guifg=#ffffff guibg=#008787 gui=NONE cterm=NONE hi CursorLine guifg=NONE guibg=#e4e4e4 gui=NONE cterm=NONE hi CursorColumn guifg=NONE guibg=#e4e4e4 gui=NONE cterm=NONE hi Folded guifg=#767676 guibg=#eeeeee gui=NONE cterm=NONE hi ColorColumn guifg=NONE guibg=#eeeeee gui=NONE cterm=NONE - hi SpellBad guifg=NONE guibg=NONE guisp=#870000 gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE + hi SpellBad guifg=NONE guibg=NONE guisp=#af0000 gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE hi SpellCap guifg=NONE guibg=NONE guisp=#005f5f gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE hi SpellLocal guifg=NONE guibg=NONE guisp=#008700 gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE - hi SpellRare guifg=NONE guibg=NONE guisp=#af00af gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE - hi Comment guifg=#005faf guibg=NONE gui=NONE cterm=NONE - hi Constant guifg=#870000 guibg=NONE gui=NONE cterm=NONE + hi SpellRare guifg=NONE guibg=NONE guisp=#ff00ff gui=undercurl ctermfg=NONE ctermbg=NONE cterm=NONE + hi Comment guifg=#005fd7 guibg=NONE gui=NONE cterm=NONE + hi Constant guifg=#af00af guibg=NONE gui=NONE cterm=NONE + hi String guifg=#af5f00 guibg=NONE gui=NONE cterm=NONE hi Identifier guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi Statement guifg=#000000 guibg=NONE gui=bold cterm=bold - hi Type guifg=#008700 guibg=NONE gui=bold cterm=bold - hi PreProc guifg=#875f00 guibg=NONE gui=NONE cterm=NONE - hi Special guifg=#005f5f guibg=NONE gui=NONE cterm=NONE + hi Type guifg=#008700 guibg=NONE gui=NONE cterm=NONE + hi PreProc guifg=#005f5f guibg=NONE gui=NONE cterm=NONE + hi Special guifg=#008787 guibg=NONE gui=NONE cterm=NONE hi Underlined guifg=NONE guibg=NONE gui=underline ctermfg=NONE ctermbg=NONE cterm=underline hi Title guifg=NONE guibg=NONE gui=bold ctermfg=NONE ctermbg=NONE cterm=bold - hi Directory guifg=#005faf guibg=NONE gui=bold cterm=bold + hi Directory guifg=#005fd7 guibg=NONE gui=bold cterm=bold hi Conceal guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi Ignore guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi DiffAdd guifg=#000000 guibg=#d7afd7 gui=NONE cterm=NONE @@ -241,23 +272,22 @@ else hi DiffDelete guifg=#870000 guibg=NONE gui=NONE cterm=NONE hi diffAdded guifg=#008700 guibg=NONE gui=NONE cterm=NONE hi diffRemoved guifg=#d70000 guibg=NONE gui=NONE cterm=NONE - hi diffSubname guifg=#870087 guibg=NONE gui=NONE cterm=NONE + hi diffSubname guifg=#af00af guibg=NONE gui=NONE cterm=NONE hi dirType guifg=#005f5f guibg=NONE gui=NONE cterm=NONE - hi dirPermissionUser guifg=#875f00 guibg=NONE gui=NONE cterm=NONE + hi dirPermissionUser guifg=#af5f00 guibg=NONE gui=NONE cterm=NONE hi dirPermissionGroup guifg=#008700 guibg=NONE gui=NONE cterm=NONE - hi dirPermissionOther guifg=#870087 guibg=NONE gui=NONE cterm=NONE + hi dirPermissionOther guifg=#af00af guibg=NONE gui=NONE cterm=NONE hi dirOwner guifg=#808080 guibg=NONE gui=NONE cterm=NONE hi dirGroup guifg=#808080 guibg=NONE gui=NONE cterm=NONE hi dirTime guifg=#808080 guibg=NONE gui=NONE cterm=NONE - hi dirSize guifg=#870000 guibg=NONE gui=NONE cterm=NONE + hi dirSize guifg=#af0000 guibg=NONE gui=NONE cterm=NONE hi dirSizeMod guifg=#005f5f guibg=NONE gui=NONE cterm=NONE hi dirLink guifg=#008700 guibg=NONE gui=bold cterm=bold hi dirFilterMenuBookmarkPath guifg=#626262 guibg=NONE gui=NONE cterm=NONE hi dirFilterMenuHistoryPath guifg=#626262 guibg=NONE gui=NONE cterm=NONE hi FilterMenuDirectorySubtle guifg=#626262 guibg=NONE gui=NONE cterm=NONE hi FilterMenuLineNr guifg=#626262 guibg=NONE gui=NONE cterm=NONE - hi CocMenuSel guifg=NONE guibg=#afd7af gui=NONE cterm=NONE - hi CocSearch guifg=#870000 guibg=NONE gui=NONE cterm=NONE + hi CocSearch guifg=#af0000 guibg=NONE gui=NONE cterm=NONE endif if s:t_Co >= 256 @@ -274,12 +304,15 @@ if s:t_Co >= 256 hi! link fugitiveHash Constant hi! link diffFile PreProc hi! link markdownHeadingDelimiter Special - hi! link rstSectionDelimiter PreProc - hi! link rstDirective Special + hi! link rstSectionDelimiter Statement + hi! link rstDirective PreProc hi! link rstHyperlinkReference Special - hi! link rstFieldName Special + hi! link rstFieldName Constant hi! link rstDelimiter Special hi! link rstInterpretedText Special + hi! link rstCodeBlock Normal + hi! link rstLiteralBlock rstCodeBlock + hi! link markdownUrl String hi! link colortemplateKey Statement hi! link xmlTagName Statement hi! link javaScriptFunction Statement @@ -329,22 +362,49 @@ if s:t_Co >= 256 hi! link shCommandSub Normal hi! link shDerefPattern shQuote hi! link shDerefOp Special + hi! link phpStorageClass Statement + hi! link phpStructure Statement + hi! link phpInclude Statement + hi! link phpDefine Statement + hi! link phpSpecialFunction Normal + hi! link phpParent Normal + hi! link phpComparison Normal + hi! link phpOperator Normal + hi! link phpVarSelector Special + hi! link phpMemberSelector Special + hi! link phpDocCustomTags phpDocTags + hi! link javaExternal Statement + hi! link javaType Statement + hi! link javaScopeDecl Statement + hi! link javaClassDecl Statement + hi! link javaStorageClass Statement + hi! link javaDocParam PreProc + hi! link csStorage Statement + hi! link csAccessModifier Statement + hi! link csClass Statement + hi! link csModifier Statement + hi! link csAsyncModifier Statement + hi! link csLogicSymbols Normal + hi! link csClassType Normal + hi! link csType Statement hi! link Terminal Normal hi! link StatuslineTerm Statusline hi! link StatuslineTermNC StatuslineNC hi! link LineNrAbove LineNr hi! link LineNrBelow LineNr + hi! link MessageWindow PMenu + hi! link PopupNotification Todo if &background ==# 'dark' hi Normal ctermfg=251 ctermbg=16 cterm=NONE - hi Statusline ctermfg=16 ctermbg=251 cterm=bold - hi StatuslineNC ctermfg=16 ctermbg=243 cterm=NONE + hi Statusline ctermfg=251 ctermbg=16 cterm=bold,reverse + hi StatuslineNC ctermfg=243 ctermbg=16 cterm=reverse hi VertSplit ctermfg=243 ctermbg=243 cterm=NONE hi TabLine ctermfg=16 ctermbg=251 cterm=NONE hi TabLineFill ctermfg=NONE ctermbg=243 cterm=NONE hi TabLineSel ctermfg=231 ctermbg=16 cterm=bold hi ToolbarLine ctermfg=NONE ctermbg=NONE cterm=NONE hi ToolbarButton ctermfg=16 ctermbg=231 cterm=NONE - hi QuickFixLine ctermfg=16 ctermbg=110 cterm=NONE + hi QuickFixLine ctermfg=16 ctermbg=75 cterm=NONE hi CursorLineNr ctermfg=231 ctermbg=NONE cterm=bold hi LineNr ctermfg=240 ctermbg=NONE cterm=NONE hi NonText ctermfg=240 ctermbg=NONE cterm=NONE @@ -352,7 +412,7 @@ if s:t_Co >= 256 hi EndOfBuffer ctermfg=240 ctermbg=NONE cterm=NONE hi SpecialKey ctermfg=240 ctermbg=NONE cterm=NONE hi Pmenu ctermfg=NONE ctermbg=234 cterm=NONE - hi PmenuSel ctermfg=NONE ctermbg=22 cterm=NONE + hi PmenuSel ctermfg=NONE ctermbg=238 cterm=NONE hi PmenuThumb ctermfg=NONE ctermbg=251 cterm=NONE hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE @@ -360,7 +420,7 @@ if s:t_Co >= 256 hi ErrorMsg ctermfg=231 ctermbg=203 cterm=NONE hi ModeMsg ctermfg=222 ctermbg=NONE cterm=reverse hi MoreMsg ctermfg=77 ctermbg=NONE cterm=NONE - hi Question ctermfg=218 ctermbg=NONE cterm=NONE + hi Question ctermfg=213 ctermbg=NONE cterm=NONE hi WarningMsg ctermfg=203 ctermbg=NONE cterm=NONE hi Todo ctermfg=116 ctermbg=16 cterm=reverse hi Search ctermfg=16 ctermbg=222 cterm=NONE @@ -379,17 +439,18 @@ if s:t_Co >= 256 hi SpellBad ctermfg=203 ctermbg=NONE cterm=underline hi SpellCap ctermfg=73 ctermbg=NONE cterm=underline hi SpellLocal ctermfg=77 ctermbg=NONE cterm=underline - hi SpellRare ctermfg=218 ctermbg=NONE cterm=underline - hi Comment ctermfg=110 ctermbg=NONE cterm=NONE - hi Constant ctermfg=222 ctermbg=NONE cterm=NONE + hi SpellRare ctermfg=213 ctermbg=NONE cterm=underline + hi Comment ctermfg=75 ctermbg=NONE cterm=NONE + hi Constant ctermfg=213 ctermbg=NONE cterm=NONE + hi String ctermfg=222 ctermbg=NONE cterm=NONE hi Identifier ctermfg=NONE ctermbg=NONE cterm=NONE - hi Statement ctermfg=255 ctermbg=NONE cterm=bold - hi Type ctermfg=77 ctermbg=NONE cterm=bold - hi PreProc ctermfg=137 ctermbg=NONE cterm=NONE + hi Statement ctermfg=254 ctermbg=NONE cterm=bold + hi Type ctermfg=77 ctermbg=NONE cterm=NONE + hi PreProc ctermfg=116 ctermbg=NONE cterm=NONE hi Special ctermfg=73 ctermbg=NONE cterm=NONE hi Underlined ctermfg=NONE ctermbg=NONE cterm=underline hi Title ctermfg=NONE ctermbg=NONE cterm=bold - hi Directory ctermfg=116 ctermbg=NONE cterm=bold + hi Directory ctermfg=75 ctermbg=NONE cterm=bold hi Conceal ctermfg=NONE ctermbg=NONE cterm=NONE hi Ignore ctermfg=NONE ctermbg=NONE cterm=NONE hi DiffAdd ctermfg=16 ctermbg=139 cterm=NONE @@ -398,8 +459,8 @@ if s:t_Co >= 256 hi DiffDelete ctermfg=174 ctermbg=NONE cterm=NONE hi diffAdded ctermfg=77 ctermbg=NONE cterm=NONE hi diffRemoved ctermfg=174 ctermbg=NONE cterm=NONE - hi diffSubname ctermfg=218 ctermbg=NONE cterm=NONE - hi dirType ctermfg=175 ctermbg=NONE cterm=NONE + hi diffSubname ctermfg=213 ctermbg=NONE cterm=NONE + hi dirType ctermfg=176 ctermbg=NONE cterm=NONE hi dirPermissionUser ctermfg=71 ctermbg=NONE cterm=NONE hi dirPermissionGroup ctermfg=137 ctermbg=NONE cterm=NONE hi dirPermissionOther ctermfg=73 ctermbg=NONE cterm=NONE @@ -407,12 +468,11 @@ if s:t_Co >= 256 hi dirGroup ctermfg=243 ctermbg=NONE cterm=NONE hi dirTime ctermfg=243 ctermbg=NONE cterm=NONE hi dirSize ctermfg=222 ctermbg=NONE cterm=NONE - hi dirSizeMod ctermfg=175 ctermbg=NONE cterm=NONE + hi dirSizeMod ctermfg=176 ctermbg=NONE cterm=NONE hi FilterMenuDirectorySubtle ctermfg=102 ctermbg=NONE cterm=NONE hi dirFilterMenuBookmarkPath ctermfg=102 ctermbg=NONE cterm=NONE hi dirFilterMenuHistoryPath ctermfg=102 ctermbg=NONE cterm=NONE hi FilterMenuLineNr ctermfg=102 ctermbg=NONE cterm=NONE - hi CocMenuSel ctermfg=NONE ctermbg=22 cterm=NONE hi CocSearch ctermfg=222 ctermbg=NONE cterm=NONE else " Light background @@ -433,44 +493,45 @@ if s:t_Co >= 256 hi EndOfBuffer ctermfg=247 ctermbg=NONE cterm=NONE hi SpecialKey ctermfg=247 ctermbg=NONE cterm=NONE hi Pmenu ctermfg=NONE ctermbg=255 cterm=NONE - hi PmenuSel ctermfg=NONE ctermbg=151 cterm=NONE + hi PmenuSel ctermfg=NONE ctermbg=251 cterm=NONE hi PmenuThumb ctermfg=NONE ctermbg=243 cterm=NONE hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE hi Error ctermfg=231 ctermbg=160 cterm=NONE hi ErrorMsg ctermfg=231 ctermbg=160 cterm=NONE - hi ModeMsg ctermfg=186 ctermbg=16 cterm=reverse + hi ModeMsg ctermfg=222 ctermbg=16 cterm=reverse hi MoreMsg ctermfg=28 ctermbg=NONE cterm=bold - hi Question ctermfg=90 ctermbg=NONE cterm=bold + hi Question ctermfg=127 ctermbg=NONE cterm=bold hi WarningMsg ctermfg=160 ctermbg=NONE cterm=bold - hi Todo ctermfg=23 ctermbg=231 cterm=reverse - hi Search ctermfg=16 ctermbg=186 cterm=NONE + hi Todo ctermfg=30 ctermbg=231 cterm=reverse + hi Search ctermfg=16 ctermbg=222 cterm=NONE hi IncSearch ctermfg=16 ctermbg=114 cterm=NONE hi CurSearch ctermfg=16 ctermbg=114 cterm=NONE - hi WildMenu ctermfg=16 ctermbg=186 cterm=bold - hi debugPC ctermfg=25 ctermbg=NONE cterm=reverse + hi WildMenu ctermfg=16 ctermbg=222 cterm=bold + hi debugPC ctermfg=26 ctermbg=NONE cterm=reverse hi debugBreakpoint ctermfg=23 ctermbg=NONE cterm=reverse hi Visual ctermfg=231 ctermbg=67 cterm=NONE hi MatchParen ctermfg=30 ctermbg=231 cterm=reverse - hi VisualNOS ctermfg=231 ctermbg=37 cterm=NONE + hi VisualNOS ctermfg=231 ctermbg=30 cterm=NONE hi CursorLine ctermfg=NONE ctermbg=254 cterm=NONE hi CursorColumn ctermfg=NONE ctermbg=254 cterm=NONE hi Folded ctermfg=243 ctermbg=255 cterm=NONE hi ColorColumn ctermfg=NONE ctermbg=255 cterm=NONE - hi SpellBad ctermfg=88 ctermbg=NONE cterm=underline + hi SpellBad ctermfg=124 ctermbg=NONE cterm=underline hi SpellCap ctermfg=23 ctermbg=NONE cterm=underline hi SpellLocal ctermfg=28 ctermbg=NONE cterm=underline hi SpellRare ctermfg=133 ctermbg=NONE cterm=underline - hi Comment ctermfg=25 ctermbg=NONE cterm=NONE - hi Constant ctermfg=88 ctermbg=NONE cterm=NONE + hi Comment ctermfg=26 ctermbg=NONE cterm=NONE + hi Constant ctermfg=127 ctermbg=NONE cterm=NONE + hi String ctermfg=130 ctermbg=NONE cterm=NONE hi Identifier ctermfg=NONE ctermbg=NONE cterm=NONE hi Statement ctermfg=16 ctermbg=NONE cterm=bold - hi Type ctermfg=28 ctermbg=NONE cterm=bold - hi PreProc ctermfg=94 ctermbg=NONE cterm=NONE - hi Special ctermfg=23 ctermbg=NONE cterm=NONE + hi Type ctermfg=28 ctermbg=NONE cterm=NONE + hi PreProc ctermfg=23 ctermbg=NONE cterm=NONE + hi Special ctermfg=30 ctermbg=NONE cterm=NONE hi Underlined ctermfg=NONE ctermbg=NONE cterm=underline hi Title ctermfg=NONE ctermbg=NONE cterm=bold - hi Directory ctermfg=25 ctermbg=NONE cterm=bold + hi Directory ctermfg=26 ctermbg=NONE cterm=bold hi Conceal ctermfg=NONE ctermbg=NONE cterm=NONE hi Ignore ctermfg=NONE ctermbg=NONE cterm=NONE hi DiffAdd ctermfg=16 ctermbg=182 cterm=NONE @@ -479,23 +540,22 @@ if s:t_Co >= 256 hi DiffDelete ctermfg=88 ctermbg=NONE cterm=NONE hi diffAdded ctermfg=28 ctermbg=NONE cterm=NONE hi diffRemoved ctermfg=160 ctermbg=NONE cterm=NONE - hi diffSubname ctermfg=90 ctermbg=NONE cterm=NONE + hi diffSubname ctermfg=127 ctermbg=NONE cterm=NONE hi dirType ctermfg=23 ctermbg=NONE cterm=NONE - hi dirPermissionUser ctermfg=94 ctermbg=NONE cterm=NONE + hi dirPermissionUser ctermfg=130 ctermbg=NONE cterm=NONE hi dirPermissionGroup ctermfg=28 ctermbg=NONE cterm=NONE - hi dirPermissionOther ctermfg=90 ctermbg=NONE cterm=NONE + hi dirPermissionOther ctermfg=127 ctermbg=NONE cterm=NONE hi dirOwner ctermfg=244 ctermbg=NONE cterm=NONE hi dirGroup ctermfg=244 ctermbg=NONE cterm=NONE hi dirTime ctermfg=244 ctermbg=NONE cterm=NONE - hi dirSize ctermfg=88 ctermbg=NONE cterm=NONE + hi dirSize ctermfg=124 ctermbg=NONE cterm=NONE hi dirSizeMod ctermfg=23 ctermbg=NONE cterm=NONE hi dirLink ctermfg=28 ctermbg=NONE cterm=bold hi dirFilterMenuBookmarkPath ctermfg=241 ctermbg=NONE cterm=NONE hi dirFilterMenuHistoryPath ctermfg=241 ctermbg=NONE cterm=NONE hi FilterMenuDirectorySubtle ctermfg=241 ctermbg=NONE cterm=NONE hi FilterMenuLineNr ctermfg=241 ctermbg=NONE cterm=NONE - hi CocMenuSel ctermfg=NONE ctermbg=151 cterm=NONE - hi CocSearch ctermfg=88 ctermbg=NONE cterm=NONE + hi CocSearch ctermfg=124 ctermbg=NONE cterm=NONE endif unlet s:t_Co finish @@ -504,8 +564,8 @@ endif if s:t_Co >= 16 if &background ==# 'dark' hi Normal ctermfg=grey ctermbg=black cterm=NONE - hi Statusline ctermfg=black ctermbg=grey cterm=bold - hi StatuslineNC ctermfg=black ctermbg=darkgrey cterm=NONE + hi Statusline ctermfg=grey ctermbg=black cterm=bold,reverse + hi StatuslineNC ctermfg=darkgrey ctermbg=black cterm=reverse hi VertSplit ctermfg=darkgrey ctermbg=darkgrey cterm=NONE hi TabLine ctermfg=black ctermbg=grey cterm=NONE hi TabLineFill ctermfg=NONE ctermbg=darkgrey cterm=NONE @@ -520,7 +580,7 @@ if s:t_Co >= 16 hi EndOfBuffer ctermfg=grey ctermbg=NONE cterm=NONE hi SpecialKey ctermfg=grey ctermbg=NONE cterm=NONE hi Pmenu ctermfg=black ctermbg=darkgrey cterm=NONE - hi PmenuSel ctermfg=black ctermbg=darkgreen cterm=NONE + hi PmenuSel ctermfg=black ctermbg=darkcyan cterm=NONE hi PmenuThumb ctermfg=NONE ctermbg=grey cterm=NONE hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE @@ -549,15 +609,16 @@ if s:t_Co >= 16 hi SpellLocal ctermfg=green ctermbg=NONE cterm=underline hi SpellRare ctermfg=magenta ctermbg=NONE cterm=underline hi Comment ctermfg=blue ctermbg=NONE cterm=NONE - hi Constant ctermfg=yellow ctermbg=NONE cterm=NONE + hi Constant ctermfg=magenta ctermbg=NONE cterm=NONE + hi String ctermfg=yellow ctermbg=NONE cterm=NONE hi Identifier ctermfg=NONE ctermbg=NONE cterm=NONE hi Statement ctermfg=grey ctermbg=NONE cterm=bold - hi Type ctermfg=green ctermbg=NONE cterm=bold - hi PreProc ctermfg=darkyellow ctermbg=NONE cterm=NONE + hi Type ctermfg=green ctermbg=NONE cterm=NONE + hi PreProc ctermfg=cyan ctermbg=NONE cterm=NONE hi Special ctermfg=darkcyan ctermbg=NONE cterm=NONE hi Underlined ctermfg=NONE ctermbg=NONE cterm=underline hi Title ctermfg=NONE ctermbg=NONE cterm=bold - hi Directory ctermfg=cyan ctermbg=NONE cterm=bold + hi Directory ctermfg=blue ctermbg=NONE cterm=bold hi Conceal ctermfg=NONE ctermbg=NONE cterm=NONE hi Ignore ctermfg=NONE ctermbg=NONE cterm=NONE hi DiffAdd ctermfg=black ctermbg=darkmagenta cterm=NONE @@ -567,6 +628,20 @@ if s:t_Co >= 16 hi diffAdded ctermfg=green ctermbg=NONE cterm=NONE hi diffRemoved ctermfg=darkred ctermbg=NONE cterm=NONE hi diffSubname ctermfg=magenta ctermbg=NONE cterm=NONE + hi dirType ctermfg=darkmagenta ctermbg=NONE cterm=NONE + hi dirPermissionUser ctermfg=darkgreen ctermbg=NONE cterm=NONE + hi dirPermissionGroup ctermfg=darkyellow ctermbg=NONE cterm=NONE + hi dirPermissionOther ctermfg=darkcyan ctermbg=NONE cterm=NONE + hi dirOwner ctermfg=darkgrey ctermbg=NONE cterm=NONE + hi dirGroup ctermfg=darkgrey ctermbg=NONE cterm=NONE + hi dirTime ctermfg=darkgrey ctermbg=NONE cterm=NONE + hi dirSize ctermfg=yellow ctermbg=NONE cterm=NONE + hi dirSizeMod ctermfg=darkmagenta ctermbg=NONE cterm=NONE + hi FilterMenuDirectorySubtle ctermfg=grey ctermbg=NONE cterm=NONE + hi dirFilterMenuBookmarkPath ctermfg=grey ctermbg=NONE cterm=NONE + hi dirFilterMenuHistoryPath ctermfg=grey ctermbg=NONE cterm=NONE + hi FilterMenuLineNr ctermfg=grey ctermbg=NONE cterm=NONE + hi CocSearch ctermfg=yellow ctermbg=NONE cterm=NONE else " Light background hi Normal ctermfg=black ctermbg=white cterm=NONE @@ -586,7 +661,7 @@ if s:t_Co >= 16 hi EndOfBuffer ctermfg=darkgrey ctermbg=NONE cterm=NONE hi SpecialKey ctermfg=darkgrey ctermbg=NONE cterm=NONE hi Pmenu ctermfg=black ctermbg=grey cterm=NONE - hi PmenuSel ctermfg=black ctermbg=darkgreen cterm=NONE + hi PmenuSel ctermfg=black ctermbg=darkcyan cterm=NONE hi PmenuThumb ctermfg=NONE ctermbg=darkgrey cterm=NONE hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE @@ -596,7 +671,7 @@ if s:t_Co >= 16 hi MoreMsg ctermfg=darkgreen ctermbg=NONE cterm=bold hi Question ctermfg=darkmagenta ctermbg=NONE cterm=bold hi WarningMsg ctermfg=red ctermbg=NONE cterm=bold - hi Todo ctermfg=darkcyan ctermbg=white cterm=reverse + hi Todo ctermfg=cyan ctermbg=white cterm=reverse hi Search ctermfg=black ctermbg=yellow cterm=NONE hi IncSearch ctermfg=black ctermbg=green cterm=NONE hi CurSearch ctermfg=black ctermbg=green cterm=NONE @@ -615,12 +690,13 @@ if s:t_Co >= 16 hi SpellLocal ctermfg=darkgreen ctermbg=NONE cterm=underline hi SpellRare ctermfg=magenta ctermbg=NONE cterm=underline hi Comment ctermfg=darkblue ctermbg=NONE cterm=NONE - hi Constant ctermfg=darkred ctermbg=NONE cterm=NONE + hi Constant ctermfg=darkmagenta ctermbg=NONE cterm=NONE + hi String ctermfg=darkyellow ctermbg=NONE cterm=NONE hi Identifier ctermfg=NONE ctermbg=NONE cterm=NONE hi Statement ctermfg=black ctermbg=NONE cterm=bold - hi Type ctermfg=darkgreen ctermbg=NONE cterm=bold - hi PreProc ctermfg=darkyellow ctermbg=NONE cterm=NONE - hi Special ctermfg=darkcyan ctermbg=NONE cterm=NONE + hi Type ctermfg=darkgreen ctermbg=NONE cterm=NONE + hi PreProc ctermfg=darkcyan ctermbg=NONE cterm=NONE + hi Special ctermfg=cyan ctermbg=NONE cterm=NONE hi Underlined ctermfg=NONE ctermbg=NONE cterm=underline hi Title ctermfg=NONE ctermbg=NONE cterm=bold hi Directory ctermfg=darkblue ctermbg=NONE cterm=bold @@ -633,6 +709,21 @@ if s:t_Co >= 16 hi diffAdded ctermfg=darkgreen ctermbg=NONE cterm=NONE hi diffRemoved ctermfg=red ctermbg=NONE cterm=NONE hi diffSubname ctermfg=darkmagenta ctermbg=NONE cterm=NONE + hi dirType ctermfg=darkcyan ctermbg=NONE cterm=NONE + hi dirPermissionUser ctermfg=darkyellow ctermbg=NONE cterm=NONE + hi dirPermissionGroup ctermfg=darkgreen ctermbg=NONE cterm=NONE + hi dirPermissionOther ctermfg=darkmagenta ctermbg=NONE cterm=NONE + hi dirOwner ctermfg=grey ctermbg=NONE cterm=NONE + hi dirGroup ctermfg=grey ctermbg=NONE cterm=NONE + hi dirTime ctermfg=grey ctermbg=NONE cterm=NONE + hi dirSize ctermfg=darkred ctermbg=NONE cterm=NONE + hi dirSizeMod ctermfg=darkcyan ctermbg=NONE cterm=NONE + hi dirLink ctermfg=darkgreen ctermbg=NONE cterm=bold + hi dirFilterMenuBookmarkPath ctermfg=darkgrey ctermbg=NONE cterm=NONE + hi dirFilterMenuHistoryPath ctermfg=darkgrey ctermbg=NONE cterm=NONE + hi FilterMenuDirectorySubtle ctermfg=darkgrey ctermbg=NONE cterm=NONE + hi FilterMenuLineNr ctermfg=darkgrey ctermbg=NONE cterm=NONE + hi CocSearch ctermfg=darkred ctermbg=NONE cterm=NONE endif unlet s:t_Co finish @@ -656,10 +747,10 @@ if s:t_Co >= 8 hi FoldColumn ctermfg=black ctermbg=NONE cterm=NONE hi EndOfBuffer ctermfg=black ctermbg=NONE cterm=NONE hi SpecialKey ctermfg=black ctermbg=NONE cterm=NONE - hi Pmenu ctermfg=black ctermbg=grey cterm=NONE + hi Pmenu ctermfg=NONE ctermbg=grey cterm=NONE hi PmenuThumb ctermfg=NONE ctermbg=darkgreen cterm=NONE hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE - hi PmenuSel ctermfg=black ctermbg=darkgreen cterm=NONE + hi PmenuSel ctermfg=black ctermbg=darkcyan cterm=NONE hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE hi Error ctermfg=grey ctermbg=darkred cterm=NONE hi ErrorMsg ctermfg=grey ctermbg=darkred cterm=NONE @@ -674,7 +765,7 @@ if s:t_Co >= 8 hi WildMenu ctermfg=black ctermbg=darkyellow cterm=bold hi debugPC ctermfg=darkblue ctermbg=NONE cterm=reverse hi debugBreakpoint ctermfg=darkcyan ctermbg=NONE cterm=reverse - hi Visual ctermfg=black ctermbg=darkblue cterm=NONE + hi Visual ctermfg=NONE ctermbg=NONE cterm=reverse hi MatchParen ctermfg=darkcyan ctermbg=black cterm=reverse hi VisualNOS ctermfg=black ctermbg=darkcyan cterm=NONE hi CursorLine ctermfg=NONE ctermbg=NONE cterm=underline @@ -688,13 +779,13 @@ if s:t_Co >= 8 hi Comment ctermfg=darkblue ctermbg=NONE cterm=NONE hi Constant ctermfg=darkred ctermbg=NONE cterm=NONE hi Identifier ctermfg=NONE ctermbg=NONE cterm=NONE - hi Statement ctermfg=black ctermbg=NONE cterm=bold - hi Type ctermfg=darkgreen ctermbg=NONE cterm=bold - hi PreProc ctermfg=darkyellow ctermbg=NONE cterm=NONE + hi Statement ctermfg=grey ctermbg=NONE cterm=bold + hi Type ctermfg=darkgreen ctermbg=NONE cterm=NONE + hi PreProc ctermfg=darkcyan ctermbg=NONE cterm=NONE hi Special ctermfg=darkcyan ctermbg=NONE cterm=NONE hi Underlined ctermfg=NONE ctermbg=NONE cterm=underline hi Title ctermfg=NONE ctermbg=NONE cterm=bold - hi Directory ctermfg=darkcyan ctermbg=NONE cterm=bold + hi Directory ctermfg=darkblue ctermbg=NONE cterm=bold hi Conceal ctermfg=NONE ctermbg=NONE cterm=NONE hi Ignore ctermfg=NONE ctermbg=NONE cterm=NONE hi DiffAdd ctermfg=black ctermbg=darkmagenta cterm=NONE @@ -719,10 +810,10 @@ if s:t_Co >= 8 hi FoldColumn ctermfg=black ctermbg=NONE cterm=NONE hi EndOfBuffer ctermfg=black ctermbg=NONE cterm=NONE hi SpecialKey ctermfg=black ctermbg=NONE cterm=NONE - hi Pmenu ctermfg=grey ctermbg=black cterm=NONE + hi Pmenu ctermfg=NONE ctermbg=black cterm=NONE hi PmenuThumb ctermfg=NONE ctermbg=darkgreen cterm=NONE hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE - hi PmenuSel ctermfg=black ctermbg=darkgreen cterm=NONE + hi PmenuSel ctermfg=NONE ctermbg=darkcyan cterm=NONE hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE hi Error ctermfg=grey ctermbg=darkred cterm=NONE hi ErrorMsg ctermfg=grey ctermbg=darkred cterm=NONE @@ -737,7 +828,7 @@ if s:t_Co >= 8 hi WildMenu ctermfg=black ctermbg=darkyellow cterm=bold hi debugPC ctermfg=darkblue ctermbg=NONE cterm=reverse hi debugBreakpoint ctermfg=darkcyan ctermbg=NONE cterm=reverse - hi Visual ctermfg=grey ctermbg=darkblue cterm=NONE + hi Visual ctermfg=NONE ctermbg=NONE cterm=reverse hi MatchParen ctermfg=darkcyan ctermbg=grey cterm=reverse hi VisualNOS ctermfg=black ctermbg=darkcyan cterm=NONE hi CursorLine ctermfg=NONE ctermbg=NONE cterm=underline @@ -752,12 +843,12 @@ if s:t_Co >= 8 hi Constant ctermfg=darkred ctermbg=NONE cterm=NONE hi Identifier ctermfg=NONE ctermbg=NONE cterm=NONE hi Statement ctermfg=black ctermbg=NONE cterm=bold - hi Type ctermfg=darkgreen ctermbg=NONE cterm=bold - hi PreProc ctermfg=darkyellow ctermbg=NONE cterm=NONE + hi Type ctermfg=darkgreen ctermbg=NONE cterm=NONE + hi PreProc ctermfg=darkcyan ctermbg=NONE cterm=NONE hi Special ctermfg=darkcyan ctermbg=NONE cterm=NONE hi Underlined ctermfg=NONE ctermbg=NONE cterm=underline hi Title ctermfg=black ctermbg=NONE cterm=bold - hi Directory ctermfg=darkcyan ctermbg=NONE cterm=bold + hi Directory ctermfg=darkblue ctermbg=NONE cterm=bold hi Conceal ctermfg=NONE ctermbg=NONE cterm=NONE hi Ignore ctermfg=NONE ctermbg=NONE cterm=NONE hi DiffAdd ctermfg=black ctermbg=darkmagenta cterm=NONE @@ -848,14 +939,14 @@ endif " Color: color03 #AF875F 137 darkyellow " Color: color11 #FFD787 222 yellow " Color: color04 #5F87AF 67 darkblue -" Color: color12 #87AFD7 110 blue -" Color: color05 #D787AF 175 darkmagenta -" Color: color13 #FFAFD7 218 magenta +" Color: color12 #5FAFFF 75 blue +" Color: color05 #D787D7 176 darkmagenta +" Color: color13 #FF87FF 213 magenta " Color: color06 #5FAFAF 73 darkcyan " Color: color14 #5FD7D7 116 cyan " Color: color07 #C6C6C6 251 grey " Color: color15 #FFFFFF 231 white -" Color: colorDimWhite #EEEEEE 255 grey +" Color: colorDimWhite #E4E4E4 254 grey " Color: colorLine #262626 235 darkgrey " Color: colorB #1C1C1C 234 darkgrey " Color: colorNonT #585858 240 grey @@ -864,7 +955,7 @@ endif " Color: colorlC #FF5FFF 207 magenta " Color: colorV #005F87 24 darkblue " Color: colorMP #C5E7C5 30 darkcyan -" Color: colorPMenuSel #005F00 22 darkgreen +" Color: colorPMenuSel #444444 238 darkcyan " Color: colorDim #878787 102 grey " Color: diffAdd #AF87AF 139 darkmagenta " Color: diffDelete #D78787 174 darkred @@ -876,18 +967,18 @@ endif " Background: light " Color: color00 #000000 16 black " Color: color08 #767676 243 darkgrey -" Color: color01 #870000 88 darkred +" Color: color01 #AF0000 124 darkred " Color: color09 #D70000 160 red " Color: color02 #008700 28 darkgreen " Color: color10 #87D787 114 green -" Color: color03 #875F00 94 darkyellow -" Color: color11 #D7D787 186 yellow -" Color: color04 #005FAF 25 darkblue +" Color: color03 #AF5F00 130 darkyellow +" Color: color11 #FFD787 222 yellow +" Color: color04 #005FD7 26 darkblue " Color: color12 #0087D7 32 blue -" Color: color05 #870087 90 darkmagenta -" Color: color13 #AF00AF 133 magenta +" Color: color05 #AF00AF 127 darkmagenta +" Color: color13 #FF00FF 133 magenta " Color: color06 #005F5F 23 darkcyan -" Color: color14 #00AFAF 37 cyan +" Color: color14 #008787 30 cyan " Color: color07 #808080 244 grey " Color: color15 #FFFFFF 231 white " Color: colorLine #E4E4E4 254 grey @@ -898,7 +989,7 @@ endif " Color: colorlC #FF00FF 201 magenta " Color: colorV #5F87AF 67 darkblue " Color: colorMP #C5E7C5 30 darkcyan -" Color: colorPMenuSel #AFD7AF 151 darkgreen +" Color: colorPMenuSel #C6C6C6 251 darkcyan " Color: colorDim #626262 241 darkgrey " Color: diffAdd #D7AFD7 182 darkmagenta " Color: diffDelete #870000 88 darkred diff --git a/runtime/colors/morning.vim b/runtime/colors/morning.vim index 5764d0df78..a7aec49808 100644 --- a/runtime/colors/morning.vim +++ b/runtime/colors/morning.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Bram Moolenaar <Bram@vim.org> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:13 2022 +" Last Updated: Fri 02 Sep 2022 09:46:24 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=light hi clear let g:colors_name = 'morning' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#e4e4e4', '#a52a2a', '#ff00ff', '#6a0dad', '#008787', '#2e8b57', '#6a5acd', '#bcbcbc', '#0000ff', '#a52a2a', '#ff00ff', '#6a0dad', '#008787', '#2e8b57', '#6a5acd', '#000000'] @@ -26,6 +26,8 @@ hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine hi! link StatuslineTerm Statusline hi! link StatuslineTermNC StatuslineNC +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#000000 guibg=#e4e4e4 gui=NONE cterm=NONE hi EndOfBuffer guifg=#0000ff guibg=#cccccc gui=bold cterm=bold hi Folded guifg=#00008b guibg=#d3d3d3 gui=NONE cterm=NONE @@ -96,6 +98,8 @@ if s:t_Co >= 256 hi! link CursorLineSign CursorLine hi! link StatuslineTerm Statusline hi! link StatuslineTermNC StatuslineNC + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=16 ctermbg=254 cterm=NONE hi EndOfBuffer ctermfg=21 ctermbg=252 cterm=bold hi Folded ctermfg=18 ctermbg=252 cterm=NONE diff --git a/runtime/colors/murphy.vim b/runtime/colors/murphy.vim index b7cf6ce985..60a6aed428 100644 --- a/runtime/colors/murphy.vim +++ b/runtime/colors/murphy.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Ron Aaron <ron@ronware.org>. " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:14 2022 +" Last Updated: Fri 02 Sep 2022 09:47:20 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=dark hi clear let g:colors_name = 'murphy' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#303030', '#ffa700', '#005f00', '#ffd7af', '#87afff', '#ffafaf', '#00afaf', '#bcbcbc', '#444444', '#ff0000', '#00875f', '#ffff00', '#005fff', '#ff00ff', '#00ffff', '#ffffff'] @@ -26,6 +26,8 @@ hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine hi! link StatusLineTerm StatusLine hi! link StatusLineTermNC StatusLineNC +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#87ff87 guibg=#000000 gui=NONE cterm=NONE hi EndOfBuffer guifg=#0000ff guibg=#000000 gui=NONE cterm=NONE hi StatusLine guifg=#ffffff guibg=#00008b gui=NONE cterm=NONE @@ -96,6 +98,8 @@ if s:t_Co >= 256 hi! link CursorLineSign CursorLine hi! link StatusLineTerm StatusLine hi! link StatusLineTermNC StatusLineNC + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=120 ctermbg=16 cterm=NONE hi EndOfBuffer ctermfg=21 ctermbg=16 cterm=NONE hi StatusLine ctermfg=231 ctermbg=18 cterm=NONE diff --git a/runtime/colors/pablo.vim b/runtime/colors/pablo.vim index 521ea44aaf..dc3e496853 100644 --- a/runtime/colors/pablo.vim +++ b/runtime/colors/pablo.vim @@ -3,7 +3,7 @@ " Maintainer: Original maintainerRon Aaron <ron@ronware.org> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:15 2022 +" Last Updated: Wed 14 Sep 2022 19:05:27 MSK " Generated by Colortemplate v2.2.0 @@ -12,18 +12,20 @@ set background=dark hi clear let g:colors_name = 'pablo' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'] endif -hi Normal guifg=#ffffff guibg=#000000 gui=NONE cterm=NONE hi! link Terminal Normal hi! link StatusLineTerm StatusLine hi! link StatusLineTermNC StatusLineNC hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo +hi Normal guifg=#ffffff guibg=#000000 gui=NONE cterm=NONE hi Comment guifg=#808080 guibg=NONE gui=NONE cterm=NONE hi Constant guifg=#00ffff guibg=NONE gui=NONE cterm=NONE hi Identifier guifg=#00c0c0 guibg=NONE gui=NONE cterm=NONE @@ -88,13 +90,15 @@ hi DiffText guifg=#000000 guibg=#c6c6c6 gui=NONE cterm=NONE hi DiffDelete guifg=#ffffff guibg=#af5faf gui=NONE cterm=NONE if s:t_Co >= 256 - hi Normal ctermfg=231 ctermbg=16 cterm=NONE hi! link Terminal Normal hi! link StatusLineTerm StatusLine hi! link StatusLineTermNC StatusLineNC hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo + hi Normal ctermfg=231 ctermbg=16 cterm=NONE hi Comment ctermfg=244 ctermbg=NONE cterm=NONE hi Constant ctermfg=51 ctermbg=NONE cterm=NONE hi Identifier ctermfg=37 ctermbg=NONE cterm=NONE @@ -117,7 +121,7 @@ if s:t_Co >= 256 hi NonText ctermfg=63 ctermbg=NONE cterm=bold hi EndOfBuffer ctermfg=63 ctermbg=NONE cterm=bold hi ErrorMsg ctermfg=231 ctermbg=160 cterm=NONE - hi WarningMsg ctermfg=224 ctermbg=NONE cterm=NONE + hi WarningMsg ctermfg=196 ctermbg=NONE cterm=NONE hi SignColumn ctermfg=51 ctermbg=248 cterm=NONE hi ColorColumn ctermfg=NONE ctermbg=239 cterm=NONE hi FoldColumn ctermfg=102 ctermbg=236 cterm=NONE @@ -163,12 +167,6 @@ endif if s:t_Co >= 16 hi Normal ctermfg=white ctermbg=black cterm=NONE - hi! link Terminal Normal - hi! link StatusLineTerm StatusLine - hi! link StatusLineTermNC StatusLineNC - hi! link CurSearch Search - hi! link CursorLineFold CursorLine - hi! link CursorLineSign CursorLine hi Comment ctermfg=darkgrey ctermbg=NONE cterm=NONE hi Constant ctermfg=cyan ctermbg=NONE cterm=NONE hi Identifier ctermfg=darkcyan ctermbg=NONE cterm=NONE @@ -191,7 +189,7 @@ if s:t_Co >= 16 hi NonText ctermfg=blue ctermbg=NONE cterm=bold hi EndOfBuffer ctermfg=blue ctermbg=NONE cterm=bold hi ErrorMsg ctermfg=white ctermbg=darkred cterm=NONE - hi WarningMsg ctermfg=darkred ctermbg=NONE cterm=NONE + hi WarningMsg ctermfg=red ctermbg=NONE cterm=NONE hi SignColumn ctermfg=cyan ctermbg=black cterm=NONE hi ColorColumn ctermfg=white ctermbg=darkgrey cterm=NONE hi FoldColumn ctermfg=NONE ctermbg=NONE cterm=NONE @@ -282,7 +280,6 @@ if s:t_Co >= 8 hi SpellLocal ctermfg=darkmagenta ctermbg=darkyellow cterm=reverse hi SpellRare ctermfg=darkgreen ctermbg=NONE cterm=reverse hi Comment ctermfg=grey ctermbg=NONE cterm=bold - hi Comment ctermfg=darkgrey ctermbg=NONE cterm=NONE hi Constant ctermfg=darkcyan ctermbg=NONE cterm=bold hi Identifier ctermfg=darkcyan ctermbg=NONE cterm=NONE hi Statement ctermfg=darkyellow ctermbg=NONE cterm=bold @@ -405,7 +402,7 @@ endif " Color: SpecialKey #00ffff 81 cyan " Color: StatusLineTerm #90ee90 121 darkgreen " Color: Title #ff00ff 225 magenta -" Color: WarningMsg #ff0000 224 darkred +" Color: WarningMsg #ff0000 196 red " Color: ToolbarLine #7f7f7f 242 darkgrey " Color: ToolbarButton #d3d3d3 254 grey " Color: Underlined #80a0ff 111 darkgreen diff --git a/runtime/colors/peachpuff.vim b/runtime/colors/peachpuff.vim index 3e896ffdeb..130eceeb18 100644 --- a/runtime/colors/peachpuff.vim +++ b/runtime/colors/peachpuff.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer David Ne\v{c}as (Yeti) <yeti@physics.muni.cz> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:16 2022 +" Last Updated: Fri 02 Sep 2022 09:50:02 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=light hi clear let g:colors_name = 'peachpuff' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#ffdab9', '#a52a2a', '#c00058', '#cd00cd', '#008b8b', '#2e8b57', '#6a5acd', '#737373', '#406090', '#a52a2a', '#c00058', '#cd00cd', '#008b8b', '#2e8b57', '#6a5acd', '#000000'] @@ -24,6 +24,8 @@ hi! link LineNrBelow LineNr hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#000000 guibg=#ffdab9 gui=NONE cterm=NONE hi Folded guifg=#000000 guibg=#e3c1a5 gui=NONE cterm=NONE hi CursorLine guifg=NONE guibg=#f5c195 gui=NONE cterm=NONE @@ -94,6 +96,8 @@ if s:t_Co >= 256 hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=16 ctermbg=223 cterm=NONE hi Folded ctermfg=16 ctermbg=252 cterm=NONE hi CursorLine ctermfg=NONE ctermbg=180 cterm=NONE diff --git a/runtime/colors/quiet.vim b/runtime/colors/quiet.vim index 4c4baa994c..aecc69619b 100644 --- a/runtime/colors/quiet.vim +++ b/runtime/colors/quiet.vim @@ -4,18 +4,20 @@ " Maintainer: neutaaaaan <neutaaaaan-gh@protonmail.com> " Website: https://github.com/vim/colorschemes " License: Vim License (see `:help license`)` -" Last Updated: 2022-08-14 15:17:11 +" Last Updated: Fri 16 Sep 2022 09:52:50 MSK " Generated by Colortemplate v2.2.0 hi clear let g:colors_name = 'quiet' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 hi! link Terminal Normal hi! link StatusLineTerm StatusLine hi! link StatusLineTermNC StatusLineNC +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi! link Boolean Constant hi! link Character Constant hi! link Conditional Statement @@ -59,8 +61,8 @@ if &background ==# 'dark' hi DiffChange guifg=#87afd7 guibg=#080808 gui=reverse cterm=reverse hi DiffDelete guifg=#d75f5f guibg=#080808 gui=reverse cterm=reverse hi DiffText guifg=#d787d7 guibg=#080808 gui=reverse cterm=reverse - hi Directory guifg=#dadada guibg=#080808 gui=NONE cterm=NONE - hi EndOfBuffer guifg=#dadada guibg=#080808 gui=NONE cterm=NONE + hi Directory guifg=#dadada guibg=NONE gui=NONE cterm=NONE + hi EndOfBuffer guifg=#dadada guibg=NONE gui=NONE cterm=NONE hi ErrorMsg guifg=#dadada guibg=#080808 gui=reverse cterm=reverse hi FoldColumn guifg=#707070 guibg=NONE gui=NONE cterm=NONE hi Folded guifg=#707070 guibg=#080808 gui=NONE cterm=NONE @@ -84,13 +86,13 @@ if &background ==# 'dark' hi SpellLocal guifg=#d787d7 guibg=NONE guisp=#d787d7 gui=undercurl cterm=underline hi SpellRare guifg=#00afaf guibg=NONE guisp=#00afaf gui=undercurl cterm=underline hi StatusLine guifg=#080808 guibg=#dadada gui=bold cterm=bold - hi StatusLineNC guifg=#707070 guibg=#080808 gui=underline cterm=underline - hi TabLine guifg=#707070 guibg=#080808 gui=underline cterm=underline + hi StatusLineNC guifg=#707070 guibg=#080808 gui=reverse cterm=reverse + hi TabLine guifg=#707070 guibg=#080808 gui=reverse cterm=reverse hi TabLineFill guifg=#dadada guibg=NONE gui=NONE cterm=NONE hi TabLineSel guifg=#080808 guibg=#dadada gui=bold cterm=bold - hi Title guifg=#dadada guibg=NONE gui=NONE cterm=NONE + hi Title guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi VertSplit guifg=#707070 guibg=#080808 gui=NONE cterm=NONE - hi Visual guifg=NONE guibg=NONE gui=reverse ctermfg=NONE ctermbg=NONE cterm=reverse + hi Visual guifg=#ffaf00 guibg=#080808 gui=reverse cterm=reverse hi VisualNOS guifg=NONE guibg=#303030 gui=NONE cterm=NONE hi WarningMsg guifg=#dadada guibg=NONE gui=NONE cterm=NONE hi WildMenu guifg=#00afff guibg=#080808 gui=bold cterm=bold @@ -153,9 +155,9 @@ else hi TabLine guifg=#080808 guibg=#a8a8a8 gui=NONE cterm=NONE hi TabLineFill guifg=#080808 guibg=#d7d7d7 gui=NONE cterm=NONE hi TabLineSel guifg=#eeeeee guibg=#080808 gui=bold cterm=bold - hi Title guifg=#080808 guibg=NONE gui=NONE cterm=NONE + hi Title guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE hi VertSplit guifg=#626262 guibg=#d7d7d7 gui=NONE cterm=NONE - hi Visual guifg=NONE guibg=NONE gui=reverse ctermfg=NONE ctermbg=NONE cterm=reverse + hi Visual guifg=#ffaf00 guibg=#080808 gui=reverse cterm=reverse hi VisualNOS guifg=NONE guibg=#eeeeee gui=NONE cterm=NONE hi WarningMsg guifg=#080808 guibg=NONE gui=NONE cterm=NONE hi WildMenu guifg=#080808 guibg=#eeeeee gui=bold cterm=bold @@ -188,8 +190,8 @@ if s:t_Co >= 256 hi DiffChange ctermfg=110 ctermbg=232 cterm=reverse hi DiffDelete ctermfg=167 ctermbg=232 cterm=reverse hi DiffText ctermfg=176 ctermbg=232 cterm=reverse - hi Directory ctermfg=253 ctermbg=232 cterm=NONE - hi EndOfBuffer ctermfg=253 ctermbg=232 cterm=NONE + hi Directory ctermfg=253 ctermbg=NONE cterm=NONE + hi EndOfBuffer ctermfg=253 ctermbg=NONE cterm=NONE hi ErrorMsg ctermfg=253 ctermbg=232 cterm=reverse hi FoldColumn ctermfg=242 ctermbg=NONE cterm=NONE hi Folded ctermfg=242 ctermbg=232 cterm=NONE @@ -213,13 +215,13 @@ if s:t_Co >= 256 hi SpellLocal ctermfg=176 ctermbg=NONE cterm=underline hi SpellRare ctermfg=37 ctermbg=NONE cterm=underline hi StatusLine ctermfg=232 ctermbg=253 cterm=bold - hi StatusLineNC ctermfg=242 ctermbg=232 cterm=underline - hi TabLine ctermfg=242 ctermbg=232 cterm=underline + hi StatusLineNC ctermfg=242 ctermbg=232 cterm=reverse + hi TabLine ctermfg=242 ctermbg=232 cterm=reverse hi TabLineFill ctermfg=253 ctermbg=NONE cterm=NONE hi TabLineSel ctermfg=232 ctermbg=253 cterm=bold - hi Title ctermfg=253 ctermbg=NONE cterm=NONE + hi Title ctermfg=NONE ctermbg=NONE cterm=NONE hi VertSplit ctermfg=242 ctermbg=232 cterm=NONE - hi Visual ctermfg=NONE ctermbg=NONE cterm=reverse + hi Visual ctermfg=214 ctermbg=232 cterm=reverse hi VisualNOS ctermfg=NONE ctermbg=236 cterm=NONE hi WarningMsg ctermfg=253 ctermbg=NONE cterm=NONE hi WildMenu ctermfg=39 ctermbg=232 cterm=bold @@ -279,9 +281,9 @@ if s:t_Co >= 256 hi TabLine ctermfg=232 ctermbg=248 cterm=NONE hi TabLineFill ctermfg=232 ctermbg=188 cterm=NONE hi TabLineSel ctermfg=255 ctermbg=232 cterm=bold - hi Title ctermfg=232 ctermbg=NONE cterm=NONE + hi Title ctermfg=NONE ctermbg=NONE cterm=NONE hi VertSplit ctermfg=241 ctermbg=188 cterm=NONE - hi Visual ctermfg=NONE ctermbg=NONE cterm=reverse + hi Visual ctermfg=214 ctermbg=232 cterm=reverse hi VisualNOS ctermfg=NONE ctermbg=255 cterm=NONE hi WarningMsg ctermfg=232 ctermbg=NONE cterm=NONE hi WildMenu ctermfg=232 ctermbg=255 cterm=bold @@ -348,7 +350,7 @@ if s:t_Co >= 16 hi TabLineSel ctermfg=NONE ctermbg=NONE cterm=bold,reverse hi Title ctermfg=NONE ctermbg=NONE cterm=NONE hi VertSplit ctermfg=NONE ctermbg=NONE cterm=NONE - hi Visual ctermfg=NONE ctermbg=NONE cterm=reverse + hi Visual ctermfg=darkyellow ctermbg=black cterm=reverse hi VisualNOS ctermfg=NONE ctermbg=NONE cterm=NONE hi WarningMsg ctermfg=NONE ctermbg=NONE cterm=standout hi WildMenu ctermfg=NONE ctermbg=NONE cterm=bold @@ -410,7 +412,7 @@ if s:t_Co >= 16 hi TabLineSel ctermfg=NONE ctermbg=NONE cterm=bold,reverse hi Title ctermfg=NONE ctermbg=NONE cterm=NONE hi VertSplit ctermfg=NONE ctermbg=NONE cterm=NONE - hi Visual ctermfg=NONE ctermbg=NONE cterm=reverse + hi Visual ctermfg=darkyellow ctermbg=black cterm=reverse hi VisualNOS ctermfg=NONE ctermbg=NONE cterm=NONE hi WarningMsg ctermfg=NONE ctermbg=NONE cterm=standout hi WildMenu ctermfg=NONE ctermbg=NONE cterm=bold @@ -477,7 +479,7 @@ if s:t_Co >= 8 hi TabLineSel ctermfg=NONE ctermbg=NONE cterm=bold,reverse hi Title ctermfg=NONE ctermbg=NONE cterm=NONE hi VertSplit ctermfg=NONE ctermbg=NONE cterm=NONE - hi Visual ctermfg=NONE ctermbg=NONE cterm=reverse + hi Visual ctermfg=darkyellow ctermbg=black cterm=reverse hi VisualNOS ctermfg=NONE ctermbg=NONE cterm=NONE hi WarningMsg ctermfg=NONE ctermbg=NONE cterm=standout hi WildMenu ctermfg=NONE ctermbg=NONE cterm=bold @@ -539,7 +541,7 @@ if s:t_Co >= 8 hi TabLineSel ctermfg=NONE ctermbg=NONE cterm=bold,reverse hi Title ctermfg=NONE ctermbg=NONE cterm=NONE hi VertSplit ctermfg=NONE ctermbg=NONE cterm=NONE - hi Visual ctermfg=NONE ctermbg=NONE cterm=reverse + hi Visual ctermfg=darkyellow ctermbg=black cterm=reverse hi VisualNOS ctermfg=NONE ctermbg=NONE cterm=NONE hi WarningMsg ctermfg=NONE ctermbg=NONE cterm=standout hi WildMenu ctermfg=NONE ctermbg=NONE cterm=bold @@ -650,7 +652,7 @@ endif " Color: diffred #d75f5f 167 darkred " Color: diffgreen #00af00 34 darkgreen " Color: diffblue #87afd7 110 darkblue -" Color: diffpink #d787d7 176 darkmagenta +" Color: diffpink #d787d7 176 darkmagenta " Color: uipink #ff00af 199 magenta " Color: uilime #afff00 154 green " Color: uiteal #00ffaf 49 green diff --git a/runtime/colors/ron.vim b/runtime/colors/ron.vim index a529d6c199..ea37b646a6 100644 --- a/runtime/colors/ron.vim +++ b/runtime/colors/ron.vim @@ -3,7 +3,7 @@ " Maintainer: original maintainer Ron Aaron <ron@ronware.org> " Website: https://www.github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:18 2022 +" Last Updated: Fri 02 Sep 2022 09:50:56 MSK " Generated by Colortemplate v2.2.0 @@ -12,7 +12,7 @@ set background=dark hi clear let g:colors_name = 'ron' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 hi! link Terminal Normal hi! link Boolean Constant @@ -46,6 +46,8 @@ hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine hi! link LineNrAbove LineNr hi! link LineNrBelow LineNr +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'] diff --git a/runtime/colors/shine.vim b/runtime/colors/shine.vim index b84be280e1..f9b1e39324 100644 --- a/runtime/colors/shine.vim +++ b/runtime/colors/shine.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer is Yasuhiro Matsumoto <mattn@mail.goo.ne.jp> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:19 2022 +" Last Updated: Fri 02 Sep 2022 09:51:42 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=light hi clear let g:colors_name = 'shine' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#8b0000', '#006400', '#ffff00', '#00008b', '#6a0dad', '#008b8b', '#dadada', '#767676', '#ffafaf', '#90ee90', '#ffff60', '#add8e6', '#ff00ff', '#00ffff', '#ffffff'] @@ -28,6 +28,8 @@ hi! link EndOfBuffer NonText hi! link ErrorMsg Error hi! link Tag Special hi! link Operator Statement +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE hi Folded guifg=#00008b guibg=#dadada gui=NONE cterm=NONE hi CursorLine guifg=NONE guibg=#dadada gui=NONE cterm=NONE @@ -104,6 +106,8 @@ if s:t_Co >= 256 hi! link ErrorMsg Error hi! link Tag Special hi! link Operator Statement + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=16 ctermbg=231 cterm=NONE hi Folded ctermfg=18 ctermbg=253 cterm=NONE hi CursorLine ctermfg=NONE ctermbg=253 cterm=NONE diff --git a/runtime/colors/slate.vim b/runtime/colors/slate.vim index 49dbc6387c..04fbc6d6c8 100644 --- a/runtime/colors/slate.vim +++ b/runtime/colors/slate.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Ralph Amissah <ralph@amissah.com> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Tue Aug 16 08:11:08 2022 +" Last Updated: Fri 02 Sep 2022 09:52:25 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=dark hi clear let g:colors_name = 'slate' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'] @@ -24,6 +24,8 @@ hi! link LineNrBelow LineNr hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#ffffff guibg=#262626 gui=NONE cterm=NONE hi EndOfBuffer guifg=#5f87d7 guibg=NONE gui=NONE cterm=NONE hi StatusLine guifg=#000000 guibg=#afaf87 gui=NONE cterm=NONE @@ -99,6 +101,8 @@ if s:t_Co >= 256 hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=231 ctermbg=235 cterm=NONE hi EndOfBuffer ctermfg=68 ctermbg=NONE cterm=NONE hi StatusLine ctermfg=16 ctermbg=144 cterm=NONE diff --git a/runtime/colors/torte.vim b/runtime/colors/torte.vim index ce36507ae8..01d5f0b4e0 100644 --- a/runtime/colors/torte.vim +++ b/runtime/colors/torte.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Thorsten Maerz <info@netztorte.de> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:22 2022 +" Last Updated: Fri 02 Sep 2022 09:53:21 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=dark hi clear let g:colors_name = 'torte' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'] @@ -26,6 +26,8 @@ hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine hi! link StatusLineTerm StatusLine hi! link StatusLineTermNC StatusLineNC +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#cccccc guibg=#000000 gui=NONE cterm=NONE hi Comment guifg=#80a0ff guibg=NONE gui=NONE cterm=NONE hi Constant guifg=#ffa0a0 guibg=NONE gui=NONE cterm=NONE @@ -97,6 +99,8 @@ if s:t_Co >= 256 hi! link CursorLineSign CursorLine hi! link StatusLineTerm StatusLine hi! link StatusLineTermNC StatusLineNC + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=251 ctermbg=16 cterm=NONE hi Comment ctermfg=111 ctermbg=NONE cterm=NONE hi Constant ctermfg=217 ctermbg=NONE cterm=NONE diff --git a/runtime/colors/zellner.vim b/runtime/colors/zellner.vim index 135591052c..ab794c0193 100644 --- a/runtime/colors/zellner.vim +++ b/runtime/colors/zellner.vim @@ -4,7 +4,7 @@ " Maintainer: Original maintainer Ron Aaron <ron@ronware.org> " Website: https://github.com/vim/colorschemes " License: Same as Vim -" Last Updated: Mon Aug 8 15:21:23 2022 +" Last Updated: Fri 02 Sep 2022 09:54:15 MSK " Generated by Colortemplate v2.2.0 @@ -13,7 +13,7 @@ set background=light hi clear let g:colors_name = 'zellner' -let s:t_Co = exists('&t_Co') ? (&t_Co ? &t_Co : 0) : -1 +let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1 if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#ffffff', '#a52a2a', '#ff00ff', '#a020f0', '#0000ff', '#0000ff', '#ff00ff', '#a9a9a9', '#ff0000', '#a52a2a', '#ff00ff', '#a020f0', '#0000ff', '#0000ff', '#ff00ff', '#000000'] @@ -24,6 +24,8 @@ hi! link LineNrBelow LineNr hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine +hi! link MessageWindow Pmenu +hi! link PopupNotification Todo hi Normal guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE hi Folded guifg=#00008b guibg=#d3d3d3 gui=NONE cterm=NONE hi CursorLine guifg=NONE guibg=#e5e5e5 gui=NONE cterm=NONE @@ -95,6 +97,8 @@ if s:t_Co >= 256 hi! link CurSearch Search hi! link CursorLineFold CursorLine hi! link CursorLineSign CursorLine + hi! link MessageWindow Pmenu + hi! link PopupNotification Todo hi Normal ctermfg=16 ctermbg=231 cterm=NONE hi Folded ctermfg=18 ctermbg=252 cterm=NONE hi CursorLine ctermfg=NONE ctermbg=254 cterm=NONE diff --git a/runtime/compiler/hare.vim b/runtime/compiler/hare.vim new file mode 100644 index 0000000000..c0fa68cc00 --- /dev/null +++ b/runtime/compiler/hare.vim @@ -0,0 +1,31 @@ +" Vim compiler file +" Compiler: Hare Compiler +" Maintainer: Amelia Clarke <me@rsaihe.dev> +" Last Change: 2022-09-21 + +if exists("g:current_compiler") + finish +endif +let g:current_compiler = "hare" + +let s:cpo_save = &cpo +set cpo&vim + +if exists(':CompilerSet') != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +if filereadable("Makefile") || filereadable("makefile") + CompilerSet makeprg=make +else + CompilerSet makeprg=hare\ build +endif + +CompilerSet errorformat= + \Error\ %f:%l:%c:\ %m, + \Syntax\ error:\ %.%#\ at\ %f:%l:%c\\,\ %m, + \%-G%.%# + +let &cpo = s:cpo_save +unlet s:cpo_save +" vim: tabstop=2 shiftwidth=2 expandtab diff --git a/runtime/compiler/raco.vim b/runtime/compiler/raco.vim new file mode 100644 index 0000000000..bd10859aa9 --- /dev/null +++ b/runtime/compiler/raco.vim @@ -0,0 +1,14 @@ +" Vim compiler file +" Compiler: raco (Racket command-line tools) +" Maintainer: D. Ben Knoble <ben.knoble+github@gmail.com> +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +let current_compiler = 'raco' + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +CompilerSet makeprg=raco +CompilerSet errorformat=%f:%l:%c:%m diff --git a/runtime/compiler/racomake.vim b/runtime/compiler/racomake.vim new file mode 100644 index 0000000000..dae95fec42 --- /dev/null +++ b/runtime/compiler/racomake.vim @@ -0,0 +1,14 @@ +" Vim compiler file +" Compiler: raco make (Racket command-line tools) +" Maintainer: D. Ben Knoble <ben.knoble+github@gmail.com> +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +let current_compiler = 'racomake' + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +CompilerSet makeprg=raco\ make\ --\ % +CompilerSet errorformat=%f:%l:%c:%m diff --git a/runtime/compiler/racosetup.vim b/runtime/compiler/racosetup.vim new file mode 100644 index 0000000000..1efe8a15a2 --- /dev/null +++ b/runtime/compiler/racosetup.vim @@ -0,0 +1,14 @@ +" Vim compiler file +" Compiler: raco setup (Racket command-line tools) +" Maintainer: D. Ben Knoble <ben.knoble+github@gmail.com> +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +let current_compiler = 'racosetup' + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +CompilerSet makeprg=raco\ setup +CompilerSet errorformat=%f:%l:%c:%m diff --git a/runtime/compiler/racotest.vim b/runtime/compiler/racotest.vim new file mode 100644 index 0000000000..d2a1a3c0f3 --- /dev/null +++ b/runtime/compiler/racotest.vim @@ -0,0 +1,14 @@ +" Vim compiler file +" Compiler: raco test (Racket command-line tools) +" Maintainer: D. Ben Knoble <ben.knoble+github@gmail.com> +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +let current_compiler = 'racotest' + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +CompilerSet makeprg=raco\ test\ % +CompilerSet errorformat=location:%f:%l:%c diff --git a/runtime/doc/Makefile b/runtime/doc/Makefile deleted file mode 100644 index 18d32c0820..0000000000 --- a/runtime/doc/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -# -# Makefile for the Vim documentation on Unix -# -# If you get "don't know how to make scratch", first run make in the source -# directory. Or remove the include below. - -AWK = awk - -DOCS = $(wildcard *.txt) -HTMLS = $(DOCS:.txt=.html) - -.SUFFIXES: -.SUFFIXES: .c .o .txt .html - -# Awk version of .txt to .html conversion. -html: noerrors vimindex.html $(HTMLS) - @if test -f errors.log; then cat errors.log; fi - -noerrors: - -rm -f errors.log - -$(HTMLS): tags.ref - -.txt.html: - $(AWK) -f makehtml.awk $< >$@ - -# index.html is the starting point for HTML, but for the help files it is -# help.txt. Therefore use vimindex.html for index.txt. -index.html: help.txt - $(AWK) -f makehtml.awk help.txt >index.html - -vimindex.html: index.txt - $(AWK) -f makehtml.awk index.txt >vimindex.html - -tags.ref tags.html: tags - $(AWK) -f maketags.awk tags >tags.html - -clean: - -rm -f *.html tags.ref $(HTMLS) errors.log tags - diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index a388592981..f92ef26399 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -83,6 +83,7 @@ and |rpcnotify()|: let nvim = jobstart(['nvim', '--embed'], {'rpc': v:true}) echo rpcrequest(nvim, 'nvim_eval', '"Hello " . "world!"') call jobstop(nvim) +< ============================================================================== API Definitions *api-definitions* @@ -92,7 +93,7 @@ The Nvim C API defines custom types for all function parameters. Some are just typedefs around C99 standard types, others are Nvim-defined data structures. Basic types ~ - +> API Type C type ------------------------------------------------------------------------ Nil @@ -103,7 +104,7 @@ Basic types ~ Array Dictionary (msgpack: map) Object - +< Note: empty Array is accepted as a valid argument for Dictionary parameter. Special types (msgpack EXT) ~ @@ -115,13 +116,13 @@ Special types (msgpack EXT) ~ The EXT object data is the (integer) object handle. The EXT type codes given in the |api-metadata| `types` key are stable: they will not change and are thus forward-compatible. - +> EXT Type C type Data ------------------------------------------------------------------------ Buffer enum value kObjectTypeBuffer |bufnr()| Window enum value kObjectTypeWindow |window-ID| Tabpage enum value kObjectTypeTabpage internal handle - +< *api-indexing* Most of the API uses 0-based indices, and ranges are end-exclusive. For the @@ -130,19 +131,19 @@ end of a range, -1 denotes the last line/column. Exception: the following API functions use "mark-like" indexing (1-based lines, 0-based columns): - |nvim_get_mark()| - |nvim_buf_get_mark()| - |nvim_buf_set_mark()| - |nvim_win_get_cursor()| - |nvim_win_set_cursor()| +- |nvim_get_mark()| +- |nvim_buf_get_mark()| +- |nvim_buf_set_mark()| +- |nvim_win_get_cursor()| +- |nvim_win_set_cursor()| Exception: the following API functions use |extmarks| indexing (0-based indices, end-inclusive): - |nvim_buf_del_extmark()| - |nvim_buf_get_extmark_by_id()| - |nvim_buf_get_extmarks()| - |nvim_buf_set_extmark()| +- |nvim_buf_del_extmark()| +- |nvim_buf_get_extmark_by_id()| +- |nvim_buf_get_extmarks()| +- |nvim_buf_set_extmark()| *api-fast* Most API functions are "deferred": they are queued on the main loop and @@ -162,19 +163,19 @@ and return values. Nvim exposes its API metadata as a Dictionary with these items: -version Nvim version, API level/compatibility -version.api_level API version integer *api-level* -version.api_compatible API is backwards-compatible with this level -version.api_prerelease Declares the API as unstable/unreleased > - (version.api_prerelease && fn.since == version.api_level) -functions API function signatures, containing |api-types| info - describing the return value and parameters. -ui_events |UI| event signatures -ui_options Supported |ui-option|s -{fn}.since API level where function {fn} was introduced -{fn}.deprecated_since API level where function {fn} was deprecated -types Custom handle types defined by Nvim -error_types Possible error types returned by API functions +- version Nvim version, API level/compatibility +- version.api_level API version integer *api-level* +- version.api_compatible API is backwards-compatible with this level +- version.api_prerelease Declares the API as unstable/unreleased + `(version.api_prerelease && fn.since == version.api_level)` +- functions API function signatures, containing |api-types| info + describing the return value and parameters. +- ui_events |UI| event signatures +- ui_options Supported |ui-option|s +- {fn}.since API level where function {fn} was introduced +- {fn}.deprecated_since API level where function {fn} was deprecated +- types Custom handle types defined by Nvim +- error_types Possible error types returned by API functions About the `functions` map: @@ -230,6 +231,15 @@ As Nvim evolves the API may change in compliance with this CONTRACT: - Existing items will not be removed (after release). - Deprecated functions will not be removed until Nvim version 2.0 +"Private" interfaces are NOT covered by this contract: + +- Undocumented (not in :help) functions or events of any kind +- nvim__x ("double underscore") functions + +The idea is "versionless evolution", in the words of Rich Hickey: +- Relaxing a requirement should be a compatible change. +- Strengthening a promise should be a compatible change. + ============================================================================== Global events *api-global-events* @@ -345,7 +355,7 @@ LUA ~ In-process Lua plugins can receive buffer updates in the form of Lua callbacks. These callbacks are called frequently in various contexts; |textlock| prevents changing buffer contents and window layout (use -|vim.schedule| to defer such operations to the main loop instead). +|vim.schedule()| to defer such operations to the main loop instead). |nvim_buf_attach()| will take keyword args for the callbacks. "on_lines" will receive parameters ("lines", {buf}, {changedtick}, {firstline}, {lastline}, @@ -433,7 +443,7 @@ its config is non-empty: > if vim.api.nvim_win_get_config(window_id).relative ~= '' then -- window with this window_id is floating end -> +< Buffer text can be highlighted by typical mechanisms (syntax highlighting, |api-highlights|). The |hl-NormalFloat| group highlights normal text; @@ -455,7 +465,7 @@ Example: create a float with scratch buffer: > let win = nvim_open_win(buf, 0, opts) " optional: change highlight, otherwise Pmenu is used call nvim_win_set_option(win, 'winhl', 'Normal:MyHighlight') -> +< ============================================================================== Extended marks *api-extended-marks* *extmarks* @@ -499,8 +509,8 @@ Let's set an extmark at the first row (row=0) and third column (column=2). 01 2345678 0 ex|ample.. -< ^ extmark position -> + ^ extmark position + let g:mark_ns = nvim_create_namespace('myplugin') let g:mark_id = nvim_buf_set_extmark(0, g:mark_ns, 0, 2, {}) < @@ -519,8 +529,8 @@ use |nvim_buf_del_extmark()|. Deleting "x" in our example: > 0 12345678 0 e|ample.. -< ^ extmark position -> + ^ extmark position + echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {}) => [0, 1] < @@ -544,9 +554,9 @@ nvim__get_runtime({pat}, {all}, {*opts}) *nvim__get_runtime()* |api-fast| Parameters: ~ - {pat} pattern of files to search for - {all} whether to return all matches or only the first - {opts} is_lua: only search lua subdirs + • {pat} pattern of files to search for + • {all} whether to return all matches or only the first + • {opts} is_lua: only search lua subdirs Return: ~ list of absolute paths to the found files @@ -558,7 +568,7 @@ nvim__id({obj}) *nvim__id()* in plugins. Parameters: ~ - {obj} Object to return. + • {obj} Object to return. Return: ~ its argument. @@ -570,7 +580,7 @@ nvim__id_array({arr}) *nvim__id_array()* in plugins. Parameters: ~ - {arr} Array to return. + • {arr} Array to return. Return: ~ its argument. @@ -582,7 +592,7 @@ nvim__id_dictionary({dct}) *nvim__id_dictionary()* in plugins. Parameters: ~ - {dct} Dictionary to return. + • {dct} Dictionary to return. Return: ~ its argument. @@ -594,7 +604,7 @@ nvim__id_float({flt}) *nvim__id_float()* in plugins. Parameters: ~ - {flt} Value to return. + • {flt} Value to return. Return: ~ its argument. @@ -624,7 +634,7 @@ nvim_call_atomic({calls}) *nvim_call_atomic()* |RPC| only Parameters: ~ - {calls} an array of calls, where each call is described by an array + • {calls} an array of calls, where each call is described by an array with two elements: the request name, and an array of arguments. @@ -648,18 +658,18 @@ nvim_chan_send({chan}, {data}) *nvim_chan_send()* Attributes: ~ |RPC| only - |vim.api| only + Lua |vim.api| only Parameters: ~ - {chan} id of the channel - {data} data to write. 8-bit clean: can contain NUL bytes. + • {chan} id of the channel + • {data} data to write. 8-bit clean: can contain NUL bytes. nvim_create_buf({listed}, {scratch}) *nvim_create_buf()* Creates a new, empty, unnamed buffer. Parameters: ~ - {listed} Sets 'buflisted' - {scratch} Creates a "throwaway" |scratch-buffer| for temporary work + • {listed} Sets 'buflisted' + • {scratch} Creates a "throwaway" |scratch-buffer| for temporary work (always 'nomodified'). Also sets 'nomodeline' on the buffer. @@ -690,7 +700,7 @@ nvim_del_mark({name}) *nvim_del_mark()* fails with error if a lowercase or buffer local named mark is used. Parameters: ~ - {name} Mark name + • {name} Mark name Return: ~ true if the mark was deleted, else false. @@ -703,31 +713,31 @@ nvim_del_var({name}) *nvim_del_var()* Removes a global (g:) variable. Parameters: ~ - {name} Variable name + • {name} Variable name nvim_echo({chunks}, {history}, {opts}) *nvim_echo()* Echo a message. Parameters: ~ - {chunks} A list of [text, hl_group] arrays, each representing a text + • {chunks} A list of [text, hl_group] arrays, each representing a text chunk with specified highlight. `hl_group` element can be omitted for no highlight. - {history} if true, add to |message-history|. - {opts} Optional parameters. Reserved for future use. + • {history} if true, add to |message-history|. + • {opts} Optional parameters. Reserved for future use. nvim_err_write({str}) *nvim_err_write()* Writes a message to the Vim error buffer. Does not append "\n", the message is buffered (won't display) until a linefeed is written. Parameters: ~ - {str} Message + • {str} Message nvim_err_writeln({str}) *nvim_err_writeln()* Writes a message to the Vim error buffer. Appends "\n", so the buffer is flushed (and displayed). Parameters: ~ - {str} Message + • {str} Message See also: ~ nvim_err_write() @@ -739,8 +749,8 @@ nvim_eval_statusline({str}, {*opts}) *nvim_eval_statusline()* |api-fast| Parameters: ~ - {str} Statusline string (see 'statusline'). - {opts} Optional parameters. + • {str} Statusline string (see 'statusline'). + • {opts} Optional parameters. • winid: (number) |window-ID| of the window to use as context for statusline. • maxwidth: (number) Maximum width of statusline. @@ -750,7 +760,7 @@ nvim_eval_statusline({str}, {*opts}) *nvim_eval_statusline()* • highlights: (boolean) Return highlight information. • use_winbar: (boolean) Evaluate winbar instead of statusline. • use_tabline: (boolean) Evaluate tabline instead of - statusline. When |TRUE|, {winid} is ignored. Mutually + statusline. When true, {winid} is ignored. Mutually exclusive with {use_winbar}. Return: ~ @@ -759,7 +769,7 @@ nvim_eval_statusline({str}, {*opts}) *nvim_eval_statusline()* • width: (number) Display width of the statusline. • highlights: Array containing highlight information of the statusline. Only included when the "highlights" key in {opts} is - |TRUE|. Each element of the array is a |Dictionary| with these keys: + true. Each element of the array is a |Dictionary| with these keys: • start: (number) Byte index (0-based) of first character that uses the highlight. • group: (string) Name of highlight group. @@ -775,8 +785,8 @@ nvim_exec_lua({code}, {args}) *nvim_exec_lua()* |RPC| only Parameters: ~ - {code} Lua code to execute - {args} Arguments to the code + • {code} Lua code to execute + • {args} Arguments to the code Return: ~ Return value of Lua code if present or NIL. @@ -797,9 +807,9 @@ nvim_feedkeys({keys}, {mode}, {escape_ks}) *nvim_feedkeys()* < Parameters: ~ - {keys} to be typed - {mode} behavior flags, see |feedkeys()| - {escape_ks} If true, escape K_SPECIAL bytes in `keys` This should be + • {keys} to be typed + • {mode} behavior flags, see |feedkeys()| + • {escape_ks} If true, escape K_SPECIAL bytes in `keys` This should be false if you already used |nvim_replace_termcodes()|, and true otherwise. @@ -853,7 +863,7 @@ nvim_get_color_by_name({name}) *nvim_get_color_by_name()* < Parameters: ~ - {name} Color name or "#rrggbb" string + • {name} Color name or "#rrggbb" string Return: ~ 24-bit RGB value, or -1 for invalid argument. @@ -871,7 +881,7 @@ nvim_get_context({*opts}) *nvim_get_context()* Gets a map of the current editor state. Parameters: ~ - {opts} Optional parameters. + • {opts} Optional parameters. • types: List of |context-types| ("regs", "jumps", "bufs", "gvars", …) to gather, or empty for "all". @@ -906,8 +916,8 @@ nvim_get_hl_by_id({hl_id}, {rgb}) *nvim_get_hl_by_id()* Gets a highlight definition by id. |hlID()| Parameters: ~ - {hl_id} Highlight id as returned by |hlID()| - {rgb} Export RGB colors + • {hl_id} Highlight id as returned by |hlID()| + • {rgb} Export RGB colors Return: ~ Highlight definition map @@ -919,8 +929,8 @@ nvim_get_hl_by_name({name}, {rgb}) *nvim_get_hl_by_name()* Gets a highlight definition by name. Parameters: ~ - {name} Highlight group name - {rgb} Export RGB colors + • {name} Highlight group name + • {rgb} Export RGB colors Return: ~ Highlight definition map @@ -937,7 +947,7 @@ nvim_get_keymap({mode}) *nvim_get_keymap()* Gets a list of global (non-buffer-local) |mapping| definitions. Parameters: ~ - {mode} Mode short-name ("n", "i", "v", ...) + • {mode} Mode short-name ("n", "i", "v", ...) Return: ~ Array of |maparg()|-like dictionaries describing mappings. The @@ -953,8 +963,8 @@ nvim_get_mark({name}, {opts}) *nvim_get_mark()* fails with error if a lowercase or buffer local named mark is used. Parameters: ~ - {name} Mark name - {opts} Optional parameters. Reserved for future use. + • {name} Mark name + • {opts} Optional parameters. Reserved for future use. Return: ~ 4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if the mark is @@ -989,7 +999,7 @@ nvim_get_proc_children({pid}) *nvim_get_proc_children()* nvim_get_runtime_file({name}, {all}) *nvim_get_runtime_file()* Find files in runtime directories - 'name' can contain wildcards. For example + "name" can contain wildcards. For example nvim_get_runtime_file("colors/*.vim", true) will return all color scheme files. Always use forward slashes (/) in the search pattern for subdirectories regardless of platform. @@ -1000,8 +1010,8 @@ nvim_get_runtime_file({name}, {all}) *nvim_get_runtime_file()* |api-fast| Parameters: ~ - {name} pattern of files to search for - {all} whether to return all matches or only the first + • {name} pattern of files to search for + • {all} whether to return all matches or only the first Return: ~ list of absolute paths to the found files @@ -1010,7 +1020,7 @@ nvim_get_var({name}) *nvim_get_var()* Gets a global (g:) variable. Parameters: ~ - {name} Variable name + • {name} Variable name Return: ~ Variable value @@ -1019,7 +1029,7 @@ nvim_get_vvar({name}) *nvim_get_vvar()* Gets a v: variable. Parameters: ~ - {name} Variable name + • {name} Variable name Return: ~ Variable value @@ -1043,7 +1053,7 @@ nvim_input({keys}) *nvim_input()* |api-fast| Parameters: ~ - {keys} to be typed + • {keys} to be typed Return: ~ Number of bytes actually written (can be fewer than requested if the @@ -1067,16 +1077,18 @@ nvim_input_mouse({button}, {action}, {modifier}, {grid}, {row}, {col}) |api-fast| Parameters: ~ - {button} Mouse button: one of "left", "right", "middle", "wheel". - {action} For ordinary buttons, one of "press", "drag", "release". + • {button} Mouse button: one of "left", "right", "middle", "wheel", + "move". + • {action} For ordinary buttons, one of "press", "drag", "release". For the wheel, one of "up", "down", "left", "right". - {modifier} String of modifiers each represented by a single char. The + Ignored for "move". + • {modifier} String of modifiers each represented by a single char. The same specifiers are used as for a key press, except that the "-" separator is optional, so "C-A-", "c-a" and "CA" can all be used to specify Ctrl+Alt+click. - {grid} Grid number if the client uses |ui-multigrid|, else 0. - {row} Mouse row-position (zero-based, like redraw events) - {col} Mouse column-position (zero-based, like redraw events) + • {grid} Grid number if the client uses |ui-multigrid|, else 0. + • {row} Mouse row-position (zero-based, like redraw events) + • {col} Mouse column-position (zero-based, like redraw events) nvim_list_bufs() *nvim_list_bufs()* Gets the current list of buffer handles @@ -1127,7 +1139,7 @@ nvim_load_context({dict}) *nvim_load_context()* Sets the current editor state from the given |context| map. Parameters: ~ - {dict} |Context| map. + • {dict} |Context| map. nvim_notify({msg}, {log_level}, {opts}) *nvim_notify()* Notify the user with a message @@ -1136,9 +1148,9 @@ nvim_notify({msg}, {log_level}, {opts}) *nvim_notify()* echo area but can be overridden to trigger desktop notifications. Parameters: ~ - {msg} Message to display to the user - {log_level} The log level - {opts} Reserved for future use. + • {msg} Message to display to the user + • {log_level} The log level + • {opts} Reserved for future use. nvim_open_term({buffer}, {opts}) *nvim_open_term()* Open a terminal instance in a buffer @@ -1156,13 +1168,13 @@ nvim_open_term({buffer}, {opts}) *nvim_open_term()* virtual terminal having the intended size. Parameters: ~ - {buffer} the buffer to use (expected to be empty) - {opts} Optional parameters. + • {buffer} the buffer to use (expected to be empty) + • {opts} Optional parameters. • on_input: lua callback for input sent, i e keypresses in terminal mode. Note: keypresses are sent raw as they would be to the pty master end. For instance, a carriage return is sent as a "\r", not as a "\n". |textlock| applies. It - is possible to call |nvim_chan_send| directly in the + is possible to call |nvim_chan_send()| directly in the callback however. ["input", term, bufnr, data] Return: ~ @@ -1173,7 +1185,7 @@ nvim_out_write({str}) *nvim_out_write()* message is buffered (won't display) until a linefeed is written. Parameters: ~ - {str} Message + • {str} Message nvim_paste({data}, {crlf}, {phase}) *nvim_paste()* Pastes at cursor, in any mode. @@ -1190,9 +1202,9 @@ nvim_paste({data}, {crlf}, {phase}) *nvim_paste()* not allowed when |textlock| is active Parameters: ~ - {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 + • {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: • 1: starts the paste (exactly once) • 2: continues the paste (zero or more times) @@ -1212,15 +1224,15 @@ nvim_put({lines}, {type}, {after}, {follow}) *nvim_put()* not allowed when |textlock| is active Parameters: ~ - {lines} |readfile()|-style list of lines. |channel-lines| - {type} Edit behavior: any |getregtype()| result, or: + • {lines} |readfile()|-style list of lines. |channel-lines| + • {type} Edit behavior: any |getregtype()| result, or: • "b" |blockwise-visual| mode (may include width, e.g. "b3") • "c" |charwise| mode • "l" |linewise| mode • "" guess by contents, see |setreg()| - {after} If true insert after cursor (like |p|), or before (like + • {after} If true insert after cursor (like |p|), or before (like |P|). - {follow} If true place cursor at end of inserted text. + • {follow} If true place cursor at end of inserted text. *nvim_replace_termcodes()* nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special}) @@ -1228,10 +1240,10 @@ nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special}) the internal representation. Parameters: ~ - {str} String to be converted. - {from_part} Legacy Vim parameter. Usually true. - {do_lt} Also translate <lt>. Ignored if `special` is false. - {special} Replace |keycodes|, e.g. <CR> becomes a "\r" char. + • {str} String to be converted. + • {from_part} Legacy Vim parameter. Usually true. + • {do_lt} Also translate <lt>. Ignored if `special` is false. + • {special} Replace |keycodes|, e.g. <CR> becomes a "\r" char. See also: ~ replace_termcodes @@ -1247,12 +1259,12 @@ nvim_select_popupmenu_item({item}, {insert}, {finish}, {opts}) ensure the mapping doesn't end completion mode. Parameters: ~ - {item} Index (zero-based) of the item to select. Value of -1 + • {item} Index (zero-based) of the item to select. Value of -1 selects nothing and restores the original text. - {insert} Whether the selection should be inserted in the buffer. - {finish} Finish the completion and dismiss the popupmenu. Implies + • {insert} Whether the selection should be inserted in the buffer. + • {finish} Finish the completion and dismiss the popupmenu. Implies `insert`. - {opts} Optional parameters. Reserved for future use. + • {opts} Optional parameters. Reserved for future use. *nvim_set_client_info()* nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) @@ -1274,8 +1286,8 @@ nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) |RPC| only Parameters: ~ - {name} Short name for the connected client - {version} Dictionary describing the version, with these (optional) + • {name} Short name for the connected client + • {version} Dictionary describing the version, with these (optional) keys: • "major" major version (defaults to 0 if not set, for no release yet) @@ -1284,7 +1296,7 @@ nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) • "prerelease" string describing a prerelease, like "dev" or "beta1" • "commit" hash or similar identifier of commit - {type} Must be one of the following values. Client libraries + • {type} Must be one of the following values. Client libraries should default to "remote" unless overridden by the user. • "remote" remote client connected to Nvim. @@ -1293,7 +1305,7 @@ nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) example, IDE/editor implementing a vim mode). • "host" plugin host, typically started by nvim • "plugin" single plugin, started by nvim - {methods} Builtin methods in the client. For a host, this does not + • {methods} Builtin methods in the client. For a host, this does not include plugin methods which will be discovered later. The key should be the method name, the values are dicts with these (optional) keys (more keys may be added in @@ -1305,7 +1317,7 @@ nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) • "nargs" Number of arguments. Could be a single integer or an array of two integers, minimum and maximum inclusive. - {attributes} Arbitrary string:string map of informal client + • {attributes} Arbitrary string:string map of informal client properties. Suggested keys: • "website": Client homepage URL (e.g. GitHub repository) @@ -1321,13 +1333,13 @@ nvim_set_current_buf({buffer}) *nvim_set_current_buf()* not allowed when |textlock| is active Parameters: ~ - {buffer} Buffer handle + • {buffer} Buffer handle nvim_set_current_dir({dir}) *nvim_set_current_dir()* Changes the global working directory. Parameters: ~ - {dir} Directory path + • {dir} Directory path nvim_set_current_line({line}) *nvim_set_current_line()* Sets the current line. @@ -1336,7 +1348,7 @@ nvim_set_current_line({line}) *nvim_set_current_line()* not allowed when |textlock| is active Parameters: ~ - {line} Line contents + • {line} Line contents nvim_set_current_tabpage({tabpage}) *nvim_set_current_tabpage()* Sets the current tabpage. @@ -1345,7 +1357,7 @@ nvim_set_current_tabpage({tabpage}) *nvim_set_current_tabpage()* not allowed when |textlock| is active Parameters: ~ - {tabpage} Tabpage handle + • {tabpage} Tabpage handle nvim_set_current_win({window}) *nvim_set_current_win()* Sets the current window. @@ -1354,7 +1366,7 @@ nvim_set_current_win({window}) *nvim_set_current_win()* not allowed when |textlock| is active Parameters: ~ - {window} Window handle + • {window} Window handle nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()* Sets a highlight group. @@ -1372,10 +1384,10 @@ nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()* using these values results in an error. Parameters: ~ - {ns_id} Namespace id for this highlight |nvim_create_namespace()|. + • {ns_id} Namespace id for this highlight |nvim_create_namespace()|. Use 0 to set a highlight group globally |:highlight|. - {name} Highlight group name, e.g. "ErrorMsg" - {val} Highlight definition map, accepts the following keys: + • {name} Highlight group name, e.g. "ErrorMsg" + • {val} Highlight definition map, accepts the following keys: • fg (or foreground): color name or "#RRGGBB", see note. • bg (or background): color name or "#RRGGBB", see note. • sp (or special): color name or "#RRGGBB" @@ -1394,31 +1406,31 @@ nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()* • link: name of another highlight group to link to, see |:hi-link|. • default: Don't override existing definition |:hi-default| - • ctermfg: Sets foreground of cterm color |highlight-ctermfg| - • ctermbg: Sets background of cterm color |highlight-ctermbg| + • ctermfg: Sets foreground of cterm color |ctermfg| + • ctermbg: Sets background of cterm color |ctermbg| • cterm: cterm attribute map, like |highlight-args|. If not set, cterm attributes will match those from the attribute map documented above. nvim_set_hl_ns({ns_id}) *nvim_set_hl_ns()* Set active namespace for highlights. This can be set for a single window, - see |nvim_win_set_hl_ns|. + see |nvim_win_set_hl_ns()|. Parameters: ~ - {ns_id} the namespace to use + • {ns_id} the namespace to use nvim_set_hl_ns_fast({ns_id}) *nvim_set_hl_ns_fast()* Set active namespace for highlights while redrawing. This function meant to be called while redrawing, primarily from - |nvim_set_decoration_provider| on_win and on_line callbacks, which are + |nvim_set_decoration_provider()| on_win and on_line callbacks, which are allowed to change the namespace during a redraw cycle. Attributes: ~ |api-fast| Parameters: ~ - {ns_id} the namespace to activate + • {ns_id} the namespace to activate nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()* Sets a global |mapping| for the given mode. @@ -1437,13 +1449,13 @@ nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()* < Parameters: ~ - {mode} Mode short-name (map command prefix: "n", "i", "v", "x", …) or + • {mode} Mode short-name (map command prefix: "n", "i", "v", "x", …) or "!" for |:map!|, or empty string for |:map|. - {lhs} Left-hand-side |{lhs}| of the mapping. - {rhs} Right-hand-side |{rhs}| of the mapping. - {opts} Optional parameters map: keys are |:map-arguments|, values are + • {lhs} Left-hand-side |{lhs}| of the mapping. + • {rhs} Right-hand-side |{rhs}| of the mapping. + • {opts} Optional parameters map: keys are |:map-arguments|, values are booleans (default false). Accepts all |:map-arguments| as keys - excluding |<buffer>| but including |noremap| and "desc". + excluding |<buffer>| but including |:noremap| and "desc". Unknown key is an error. "desc" can be used to give a description to the mapping. When called from Lua, also accepts a "callback" key that takes a Lua function to call when the @@ -1456,22 +1468,22 @@ nvim_set_var({name}, {value}) *nvim_set_var()* Sets a global (g:) variable. Parameters: ~ - {name} Variable name - {value} Variable value + • {name} Variable name + • {value} Variable value nvim_set_vvar({name}, {value}) *nvim_set_vvar()* Sets a v: variable, if it is not readonly. Parameters: ~ - {name} Variable name - {value} Variable value + • {name} Variable name + • {value} Variable value nvim_strwidth({text}) *nvim_strwidth()* Calculates the number of display cells occupied by `text`. Control characters including <Tab> count as one cell. Parameters: ~ - {text} Some text + • {text} Some text Return: ~ Number of cells @@ -1483,7 +1495,7 @@ nvim_subscribe({event}) *nvim_subscribe()* |RPC| only Parameters: ~ - {event} Event type string + • {event} Event type string nvim_unsubscribe({event}) *nvim_unsubscribe()* Unsubscribes to event broadcasts. @@ -1492,7 +1504,7 @@ nvim_unsubscribe({event}) *nvim_unsubscribe()* |RPC| only Parameters: ~ - {event} Event type string + • {event} Event type string ============================================================================== @@ -1505,9 +1517,9 @@ nvim_call_dict_function({dict}, {fn}, {args}) On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {dict} Dictionary, or String evaluating to a VimL |self| dict - {fn} Name of the function defined on the VimL dict - {args} Function arguments packed in an Array + • {dict} Dictionary, or String evaluating to a VimL |self| dict + • {fn} Name of the function defined on the VimL dict + • {args} Function arguments packed in an Array Return: ~ Result of the function call @@ -1518,8 +1530,8 @@ nvim_call_function({fn}, {args}) *nvim_call_function()* On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {fn} Function to call - {args} Function arguments packed in an Array + • {fn} Function to call + • {args} Function arguments packed in an Array Return: ~ Result of the function call @@ -1536,7 +1548,7 @@ nvim_command({command}) *nvim_command()* |nvim_parse_cmd()| in conjunction with |nvim_cmd()|. Parameters: ~ - {command} Ex command string + • {command} Ex command string nvim_eval({expr}) *nvim_eval()* Evaluates a VimL |expression|. Dictionaries and Lists are recursively @@ -1545,7 +1557,7 @@ nvim_eval({expr}) *nvim_eval()* On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {expr} VimL expression string + • {expr} VimL expression string Return: ~ Evaluation result or expanded object @@ -1560,8 +1572,8 @@ nvim_exec({src}, {output}) *nvim_exec()* On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {src} Vimscript code - {output} Capture and return all (non-error, non-shell |:!|) output + • {src} Vimscript code + • {output} Capture and return all (non-error, non-shell |:!|) output Return: ~ Output (non-error, non-shell |:!|) if `output` is true, else empty @@ -1580,8 +1592,8 @@ nvim_parse_expression({expr}, {flags}, {highlight}) |api-fast| Parameters: ~ - {expr} Expression to parse. Always treated as a single line. - {flags} Flags: + • {expr} Expression to parse. Always treated as a single line. + • {flags} Flags: • "m" if multiple expressions in a row are allowed (only the first one will be parsed), • "E" if EOC tokens are not allowed (determines whether @@ -1593,7 +1605,7 @@ nvim_parse_expression({expr}, {flags}, {highlight}) • "E" to parse like for "<C-r>=". • empty string for ":call". • "lm" to parse for ":let". - {highlight} If true, return value will also include "highlight" key + • {highlight} If true, return value will also include "highlight" key containing array of 4-tuples (arrays) (Integer, Integer, Integer, String), where first three numbers define the highlighted region and represent line, starting column @@ -1661,7 +1673,7 @@ nvim_buf_create_user_command({buffer}, {name}, {command}, {*opts}) Create a new user command |user-commands| in the given buffer. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer. + • {buffer} Buffer handle, or 0 for current buffer. See also: ~ nvim_create_user_command @@ -1674,15 +1686,15 @@ nvim_buf_del_user_command({buffer}, {name}) |nvim_buf_create_user_command()| can be deleted with this function. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer. - {name} Name of the command to delete. + • {buffer} Buffer handle, or 0 for current buffer. + • {name} Name of the command to delete. nvim_buf_get_commands({buffer}, {*opts}) *nvim_buf_get_commands()* Gets a map of buffer-local |user-commands|. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {opts} Optional parameters. Currently not used. + • {buffer} Buffer handle, or 0 for current buffer + • {opts} Optional parameters. Currently not used. Return: ~ Map of maps describing commands. @@ -1694,16 +1706,22 @@ nvim_cmd({*cmd}, {*opts}) *nvim_cmd()* of a String. This allows for easier construction and manipulation of an Ex command. This also allows for things such as having spaces inside a command argument, expanding filenames in a command that otherwise doesn't - expand filenames, etc. + expand filenames, etc. Command arguments may also be Number, Boolean or + String. + + The first argument may also be used instead of count for commands that + support it in order to make their usage simpler with |vim.cmd()|. For + example, instead of `vim.cmd.bdelete{ count = 2 }`, you may do + `vim.cmd.bdelete(2)`. On execution error: fails with VimL error, updates v:errmsg. Parameters: ~ - {cmd} Command to execute. Must be a Dictionary that can contain the + • {cmd} Command to execute. Must be a Dictionary that can contain the same values as the return value of |nvim_parse_cmd()| except "addr", "nargs" and "nextcmd" which are ignored if provided. All values except for "cmd" are optional. - {opts} Optional parameters. + • {opts} Optional parameters. • output: (boolean, default false) Whether to return command output. @@ -1731,9 +1749,9 @@ nvim_create_user_command({name}, {command}, {*opts}) < Parameters: ~ - {name} Name of the new user command. Must begin with an uppercase + • {name} Name of the new user command. Must begin with an uppercase letter. - {command} Replacement command to execute when this user command is + • {command} Replacement command to execute when this user command is executed. When called from Lua, the command can also be a Lua function. The function is called with a single table argument that contains the following keys: @@ -1756,7 +1774,7 @@ nvim_create_user_command({name}, {command}, {*opts}) • smods: (table) Command modifiers in a structured format. Has the same structure as the "mods" key of |nvim_parse_cmd()|. - {opts} Optional command attributes. See |command-attributes| for + • {opts} Optional command attributes. See |command-attributes| for more details. To use boolean attributes (such as |:command-bang| or |:command-bar|) set the value to "true". In addition to the string options listed in @@ -1774,7 +1792,7 @@ nvim_del_user_command({name}) *nvim_del_user_command()* Delete a user-defined command. Parameters: ~ - {name} Name of the command to delete. + • {name} Name of the command to delete. nvim_get_commands({*opts}) *nvim_get_commands()* Gets a map of global (non-buffer-local) Ex commands. @@ -1782,7 +1800,7 @@ nvim_get_commands({*opts}) *nvim_get_commands()* Currently only |user-commands| are supported, not builtin Ex commands. Parameters: ~ - {opts} Optional parameters. Currently only supports {"builtin":false} + • {opts} Optional parameters. Currently only supports {"builtin":false} Return: ~ Map of maps describing commands. @@ -1796,21 +1814,21 @@ nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()* |api-fast| Parameters: ~ - {str} Command line string to parse. Cannot contain "\n". - {opts} Optional parameters. Reserved for future use. + • {str} Command line string to parse. Cannot contain "\n". + • {opts} Optional parameters. Reserved for future use. Return: ~ Dictionary containing command information, with these keys: • cmd: (string) Command name. - • range: (array) Command <range>. Can have 0-2 elements depending on - how many items the range contains. Has no elements if command - doesn't accept a range or if no range was specified, one element if - only a single range item was specified and two elements if both - range items were specified. - • count: (number) Any |<count>| that was supplied to the command. -1 - if command cannot take a count. - • reg: (number) The optional command |<register>|, if specified. Empty - string if not specified or if command cannot take a register. + • range: (array) (optional) Command range (|<line1>| |<line2>|). + Omitted if command doesn't accept a range. Otherwise, has no + elements if no range was specified, one element if only a single + range item was specified, or two elements if both range items were + specified. + • count: (number) (optional) Command |<count>|. Omitted if command + cannot take a count. + • reg: (string) (optional) Command |<register>|. Omitted if command + cannot take a register. • bang: (boolean) Whether command contains a |<bang>| (!) modifier. • args: (array) Command arguments. • addr: (string) Value of |:command-addr|. Uses short name. @@ -1839,13 +1857,14 @@ nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()* • browse: (boolean) |:browse|. • confirm: (boolean) |:confirm|. • hide: (boolean) |:hide|. + • horizontal: (boolean) |:horizontal|. • keepalt: (boolean) |:keepalt|. • keepjumps: (boolean) |:keepjumps|. • keepmarks: (boolean) |:keepmarks|. • keeppatterns: (boolean) |:keeppatterns|. • lockmarks: (boolean) |:lockmarks|. • noswapfile: (boolean) |:noswapfile|. - • tab: (integer) |:tab|. + • tab: (integer) |:tab|. -1 when omitted. • verbose: (integer) |:verbose|. -1 when omitted. • vertical: (boolean) |:vertical|. • split: (string) Split modifier string, is an empty string when @@ -1864,8 +1883,8 @@ nvim_buf_get_option({buffer}, {name}) *nvim_buf_get_option()* Gets a buffer option value Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Option name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Option name Return: ~ Option value @@ -1875,15 +1894,15 @@ nvim_buf_set_option({buffer}, {name}, {value}) *nvim_buf_set_option()* (only works if there's a global fallback) Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Option name - {value} Option value + • {buffer} Buffer handle, or 0 for current buffer + • {name} Option name + • {value} Option value nvim_get_all_options_info() *nvim_get_all_options_info()* Gets the option information for all options. The dictionary has the full option names as keys and option metadata - dictionaries as detailed at |nvim_get_option_info|. + dictionaries as detailed at |nvim_get_option_info()|. Return: ~ dictionary of all options @@ -1892,7 +1911,7 @@ nvim_get_option({name}) *nvim_get_option()* Gets the global value of an option. Parameters: ~ - {name} Option name + • {name} Option name Return: ~ Option value (global) @@ -1915,7 +1934,7 @@ nvim_get_option_info({name}) *nvim_get_option_info()* • flaglist: List of single char flags Parameters: ~ - {name} Option name + • {name} Option name Return: ~ Option Information @@ -1927,8 +1946,8 @@ nvim_get_option_value({name}, {*opts}) *nvim_get_option_value()* current buffer or window, unless "buf" or "win" is set in {opts}. Parameters: ~ - {name} Option name - {opts} Optional parameters + • {name} Option name + • {opts} Optional parameters • scope: One of "global" or "local". Analogous to |:setglobal| and |:setlocal|, respectively. • win: |window-ID|. Used for getting window local options. @@ -1942,8 +1961,8 @@ nvim_set_option({name}, {value}) *nvim_set_option()* Sets the global value of an option. Parameters: ~ - {name} Option name - {value} New option value + • {name} Option name + • {value} New option value *nvim_set_option_value()* nvim_set_option_value({name}, {value}, {*opts}) @@ -1954,10 +1973,10 @@ nvim_set_option_value({name}, {value}, {*opts}) Note the options {win} and {buf} cannot be used together. Parameters: ~ - {name} Option name - {value} New option value - {opts} Optional parameters - • scope: One of 'global' or 'local'. Analogous to + • {name} Option name + • {value} New option value + • {opts} Optional parameters + • scope: One of "global" or "local". Analogous to |:setglobal| and |:setlocal|, respectively. • win: |window-ID|. Used for setting window local option. • buf: Buffer number. Used for setting buffer local option. @@ -1966,8 +1985,8 @@ nvim_win_get_option({window}, {name}) *nvim_win_get_option()* Gets a window option value Parameters: ~ - {window} Window handle, or 0 for current window - {name} Option name + • {window} Window handle, or 0 for current window + • {name} Option name Return: ~ Option value @@ -1977,9 +1996,9 @@ nvim_win_set_option({window}, {name}, {value}) *nvim_win_set_option()* (only works if there's a global fallback) Parameters: ~ - {window} Window handle, or 0 for current window - {name} Option name - {value} Option value + • {window} Window handle, or 0 for current window + • {name} Option name + • {value} Option value ============================================================================== @@ -2010,13 +2029,13 @@ nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()* < Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {send_buffer} True if the initial notification should contain the + • {buffer} Buffer handle, or 0 for current buffer + • {send_buffer} True if the initial notification should contain the whole buffer: first notification will be `nvim_buf_lines_event`. Else the first notification will be `nvim_buf_changedtick_event`. Not for Lua callbacks. - {opts} Optional parameters. + • {opts} Optional parameters. • on_lines: Lua callback invoked on change. Return `true` to detach. Args: • the string "lines" • buffer handle @@ -2087,11 +2106,11 @@ nvim_buf_call({buffer}, {fun}) *nvim_buf_call()* buffer/window currently, like |termopen()|. Attributes: ~ - |vim.api| only + Lua |vim.api| only Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {fun} Function to call inside the buffer (currently lua callable + • {buffer} Buffer handle, or 0 for current buffer + • {fun} Function to call inside the buffer (currently lua callable only) Return: ~ @@ -2102,7 +2121,7 @@ nvim_buf_del_keymap({buffer}, {mode}, {lhs}) *nvim_buf_del_keymap()* Unmaps a buffer-local |mapping| for the given mode. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer See also: ~ |nvim_del_keymap()| @@ -2115,8 +2134,8 @@ nvim_buf_del_mark({buffer}, {name}) *nvim_buf_del_mark()* buffer it will return false. Parameters: ~ - {buffer} Buffer to set the mark on - {name} Mark name + • {buffer} Buffer to set the mark on + • {name} Mark name Return: ~ true if the mark was deleted, else false. @@ -2129,8 +2148,8 @@ nvim_buf_del_var({buffer}, {name}) *nvim_buf_del_var()* Removes a buffer-scoped (b:) variable Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Variable name nvim_buf_delete({buffer}, {opts}) *nvim_buf_delete()* Deletes the buffer. See |:bwipeout| @@ -2139,8 +2158,8 @@ nvim_buf_delete({buffer}, {opts}) *nvim_buf_delete()* not allowed when |textlock| is active Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {opts} Optional parameters. Keys: + • {buffer} Buffer handle, or 0 for current buffer + • {opts} Optional parameters. Keys: • force: Force deletion and ignore unsaved changes. • unload: Unloaded only, do not delete. See |:bunload| @@ -2151,7 +2170,7 @@ nvim_buf_detach({buffer}) *nvim_buf_detach()* |RPC| only Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ False if detach failed (because the buffer isn't loaded); otherwise @@ -2165,7 +2184,7 @@ nvim_buf_get_changedtick({buffer}) *nvim_buf_get_changedtick()* Gets a changed tick of a buffer Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ `b:changedtick` value. @@ -2174,8 +2193,8 @@ nvim_buf_get_keymap({buffer}, {mode}) *nvim_buf_get_keymap()* Gets a list of buffer-local |mapping| definitions. Parameters: ~ - {mode} Mode short-name ("n", "i", "v", ...) - {buffer} Buffer handle, or 0 for current buffer + • {mode} Mode short-name ("n", "i", "v", ...) + • {buffer} Buffer handle, or 0 for current buffer Return: ~ Array of |maparg()|-like dictionaries describing mappings. The @@ -2193,10 +2212,10 @@ nvim_buf_get_lines({buffer}, {start}, {end}, {strict_indexing}) `strict_indexing` is set. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start} First line index - {end} Last line index, exclusive - {strict_indexing} Whether out-of-bounds should be an error. + • {buffer} Buffer handle, or 0 for current buffer + • {start} First line index + • {end} Last line index, exclusive + • {strict_indexing} Whether out-of-bounds should be an error. Return: ~ Array of lines, or empty array for unloaded buffer. @@ -2208,8 +2227,8 @@ nvim_buf_get_mark({buffer}, {name}) *nvim_buf_get_mark()* Marks are (1,0)-indexed. |api-indexing| Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Mark name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Mark name Return: ~ (row, col) tuple, (0, 0) if the mark is not set, or is an @@ -2223,7 +2242,7 @@ nvim_buf_get_name({buffer}) *nvim_buf_get_name()* Gets the full file name for the buffer Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ Buffer name @@ -2240,8 +2259,8 @@ nvim_buf_get_offset({buffer}, {index}) *nvim_buf_get_offset()* for unloaded buffer. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {index} Line index + • {buffer} Buffer handle, or 0 for current buffer + • {index} Line index Return: ~ Integer byte offset, or -1 for unloaded buffer. @@ -2260,12 +2279,12 @@ nvim_buf_get_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col}, Prefer |nvim_buf_get_lines()| when retrieving entire lines. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start_row} First line index - {start_col} Starting column (byte offset) on first line - {end_row} Last line index, inclusive - {end_col} Ending column (byte offset) on last line, exclusive - {opts} Optional parameters. Currently unused. + • {buffer} Buffer handle, or 0 for current buffer + • {start_row} First line index + • {start_col} Starting column (byte offset) on first line + • {end_row} Last line index, inclusive + • {end_col} Ending column (byte offset) on last line, exclusive + • {opts} Optional parameters. Currently unused. Return: ~ Array of lines, or empty array for unloaded buffer. @@ -2274,8 +2293,8 @@ nvim_buf_get_var({buffer}, {name}) *nvim_buf_get_var()* Gets a buffer-scoped (b:) variable. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Variable name Return: ~ Variable value @@ -2285,7 +2304,7 @@ nvim_buf_is_loaded({buffer}) *nvim_buf_is_loaded()* about unloaded buffers. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ true if the buffer is valid and loaded, false otherwise. @@ -2298,7 +2317,7 @@ nvim_buf_is_valid({buffer}) *nvim_buf_is_valid()* for more info about unloaded buffers. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ true if the buffer is valid, false otherwise. @@ -2307,7 +2326,7 @@ nvim_buf_line_count({buffer}) *nvim_buf_line_count()* Returns the number of lines in the given buffer. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer Return: ~ Line count, or 0 for unloaded buffer. |api-buffer| @@ -2317,7 +2336,7 @@ nvim_buf_set_keymap({buffer}, {mode}, {lhs}, {rhs}, {*opts}) Sets a buffer-local |mapping| for the given mode. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + • {buffer} Buffer handle, or 0 for current buffer See also: ~ |nvim_set_keymap()| @@ -2340,11 +2359,14 @@ nvim_buf_set_lines({buffer}, {start}, {end}, {strict_indexing}, {replacement}) not allowed when |textlock| is active Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start} First line index - {end} Last line index, exclusive - {strict_indexing} Whether out-of-bounds should be an error. - {replacement} Array of lines to use as replacement + • {buffer} Buffer handle, or 0 for current buffer + • {start} First line index + • {end} Last line index, exclusive + • {strict_indexing} Whether out-of-bounds should be an error. + • {replacement} Array of lines to use as replacement + + See also: ~ + |nvim_buf_set_text()| *nvim_buf_set_mark()* nvim_buf_set_mark({buffer}, {name}, {line}, {col}, {opts}) @@ -2357,11 +2379,11 @@ nvim_buf_set_mark({buffer}, {name}, {line}, {col}, {opts}) Passing 0 as line deletes the mark Parameters: ~ - {buffer} Buffer to set the mark on - {name} Mark name - {line} Line number - {col} Column/row number - {opts} Optional parameters. Reserved for future use. + • {buffer} Buffer to set the mark on + • {name} Mark name + • {line} Line number + • {col} Column/row number + • {opts} Optional parameters. Reserved for future use. Return: ~ true if the mark was set, else false. @@ -2374,8 +2396,8 @@ nvim_buf_set_name({buffer}, {name}) *nvim_buf_set_name()* Sets the full file name for a buffer Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Buffer name + • {buffer} Buffer handle, or 0 for current buffer + • {name} Buffer name *nvim_buf_set_text()* nvim_buf_set_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col}, @@ -2397,20 +2419,23 @@ nvim_buf_set_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col}, lines. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start_row} First line index - {start_col} Starting column (byte offset) on first line - {end_row} Last line index, inclusive - {end_col} Ending column (byte offset) on last line, exclusive - {replacement} Array of lines to use as replacement + • {buffer} Buffer handle, or 0 for current buffer + • {start_row} First line index + • {start_col} Starting column (byte offset) on first line + • {end_row} Last line index, inclusive + • {end_col} Ending column (byte offset) on last line, exclusive + • {replacement} Array of lines to use as replacement + + See also: ~ + |nvim_buf_set_lines()| nvim_buf_set_var({buffer}, {name}, {value}) *nvim_buf_set_var()* Sets a buffer-scoped (b:) variable Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name - {value} Variable value + • {buffer} Buffer handle, or 0 for current buffer + • {name} Variable name + • {value} Variable value ============================================================================== @@ -2441,12 +2466,12 @@ nvim_buf_add_highlight({buffer}, {ns_id}, {hl_group}, {line}, {col_start}, |nvim_create_namespace()| to create a new empty namespace. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} namespace to use or -1 for ungrouped highlight - {hl_group} Name of the highlight group to use - {line} Line to highlight (zero-indexed) - {col_start} Start of (byte-indexed) column range to highlight - {col_end} End of (byte-indexed) column range to highlight, or -1 to + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} namespace to use or -1 for ungrouped highlight + • {hl_group} Name of the highlight group to use + • {line} Line to highlight (zero-indexed) + • {col_start} Start of (byte-indexed) column range to highlight + • {col_end} End of (byte-indexed) column range to highlight, or -1 to highlight to end of line Return: ~ @@ -2461,19 +2486,19 @@ nvim_buf_clear_namespace({buffer}, {ns_id}, {line_start}, {line_end}) buffer, specify line_start=0 and line_end=-1. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace to clear, or -1 to clear all namespaces. - {line_start} Start of range of lines to clear - {line_end} End of range of lines to clear (exclusive) or -1 to + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace to clear, or -1 to clear all namespaces. + • {line_start} Start of range of lines to clear + • {line_end} End of range of lines to clear (exclusive) or -1 to clear to end of buffer. nvim_buf_del_extmark({buffer}, {ns_id}, {id}) *nvim_buf_del_extmark()* Removes an extmark. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {id} Extmark id + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace id from |nvim_create_namespace()| + • {id} Extmark id Return: ~ true if the extmark was found, else false @@ -2483,10 +2508,10 @@ nvim_buf_get_extmark_by_id({buffer}, {ns_id}, {id}, {opts}) Gets the position (0-indexed) of an extmark. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {id} Extmark id - {opts} Optional parameters. Keys: + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace id from |nvim_create_namespace()| + • {id} Extmark id + • {opts} Optional parameters. Keys: • details: Whether to include the details dict Return: ~ @@ -2525,14 +2550,14 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) < Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {start} Start of range: a 0-indexed (row, col) or valid extmark id + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace id from |nvim_create_namespace()| + • {start} Start of range: a 0-indexed (row, col) or valid extmark id (whose position defines the bound). |api-indexing| - {end} End of range (inclusive): a 0-indexed (row, col) or valid + • {end} End of range (inclusive): a 0-indexed (row, col) or valid extmark id (whose position defines the bound). |api-indexing| - {opts} Optional parameters. Keys: + • {opts} Optional parameters. Keys: • limit: Maximum number of marks to return • details Whether to include the details dict @@ -2553,11 +2578,11 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) range of text, and also to associate virtual text to the mark. Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {line} Line where to place the mark, 0-based. |api-indexing| - {col} Column where to place the mark, 0-based. |api-indexing| - {opts} Optional parameters. + • {buffer} Buffer handle, or 0 for current buffer + • {ns_id} Namespace id from |nvim_create_namespace()| + • {line} Line where to place the mark, 0-based. |api-indexing| + • {col} Column where to place the mark, 0-based. |api-indexing| + • {opts} Optional parameters. • id : id of the extmark to edit. • end_row : ending line of the mark, 0-based inclusive. • end_col : ending col of the mark, 0-based exclusive. @@ -2569,11 +2594,11 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) • virt_text : virtual text to link to this mark. A list of [text, highlight] tuples, each representing a text chunk with specified highlight. `highlight` element can either - be a a single highlight group, or an array of multiple + be a single highlight group, or an array of multiple highlight groups that will be stacked (highest priority last). A highlight group can be supplied either as a string or as an integer, the latter which can be obtained - using |nvim_get_hl_id_by_name|. + using |nvim_get_hl_id_by_name()|. • virt_text_pos : position of virtual text. Possible values: • "eol": right after eol character (default) • "overlay": display over the specified column, without @@ -2605,7 +2630,7 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) • virt_lines_above: place virtual lines above instead. • virt_lines_leftcol: Place extmarks in the leftmost column of the window, bypassing sign and number columns. - • ephemeral : for use with |nvim_set_decoration_provider| + • ephemeral : for use with |nvim_set_decoration_provider()| callbacks. The mark will only be used for the current redraw cycle, and not be permantently stored in the buffer. @@ -2643,6 +2668,8 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) When a character is supplied it is used as |:syn-cchar|. "hl_group" is used as highlight for the cchar if provided, otherwise it defaults to |hl-Conceal|. + • spell: boolean indicating that spell checking should be + performed within this extmark • ui_watched: boolean that indicates the mark should be drawn by a UI. When set, the UI will receive win_extmark events. Note: the mark is positioned by virt_text @@ -2662,7 +2689,7 @@ nvim_create_namespace({name}) *nvim_create_namespace()* new, anonymous namespace is created. Parameters: ~ - {name} Namespace name or empty string + • {name} Namespace name or empty string Return: ~ Namespace id @@ -2674,14 +2701,14 @@ nvim_get_namespaces() *nvim_get_namespaces()* dict that maps from names to namespace ids. *nvim_set_decoration_provider()* -nvim_set_decoration_provider({ns_id}, {opts}) +nvim_set_decoration_provider({ns_id}, {*opts}) Set or change decoration provider for a namespace This is a very general purpose interface for having lua callbacks being triggered during the redraw code. The expected usage is to set extmarks for the currently redrawn buffer. - |nvim_buf_set_extmark| can be called to add marks on a per-window or + |nvim_buf_set_extmark()| can be called to add marks on a per-window or per-lines basis. Use the `ephemeral` key to only use the mark for the current screen redraw (the callback will be called again for the next redraw ). @@ -2702,11 +2729,11 @@ nvim_set_decoration_provider({ns_id}, {opts}) quite dubious for the moment. Attributes: ~ - |vim.api| only + Lua |vim.api| only Parameters: ~ - {ns_id} Namespace id from |nvim_create_namespace()| - {opts} Callbacks invoked during redraw: + • {ns_id} Namespace id from |nvim_create_namespace()| + • {opts} Table of callbacks: • on_start: called first on each screen redraw ["start", tick] • on_buf: called for each buffer being redrawn (before window @@ -2726,11 +2753,11 @@ nvim_win_call({window}, {fun}) *nvim_win_call()* Calls a function with window as temporary current window. Attributes: ~ - |vim.api| only + Lua |vim.api| only Parameters: ~ - {window} Window handle, or 0 for current window - {fun} Function to call inside the window (currently lua callable + • {window} Window handle, or 0 for current window + • {fun} Function to call inside the window (currently lua callable only) Return: ~ @@ -2748,8 +2775,8 @@ nvim_win_close({window}, {force}) *nvim_win_close()* not allowed when |textlock| is active Parameters: ~ - {window} Window handle, or 0 for current window - {force} Behave like `:close!` The last window of a buffer with + • {window} Window handle, or 0 for current window + • {force} Behave like `:close!` The last window of a buffer with unwritten changes can be closed. The buffer will become hidden, even if 'hidden' is not set. @@ -2757,23 +2784,25 @@ nvim_win_del_var({window}, {name}) *nvim_win_del_var()* Removes a window-scoped (w:) variable Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name + • {window} Window handle, or 0 for current window + • {name} Variable name nvim_win_get_buf({window}) *nvim_win_get_buf()* Gets the current buffer in a window Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Buffer handle nvim_win_get_cursor({window}) *nvim_win_get_cursor()* - Gets the (1,0)-indexed cursor position in the window. |api-indexing| + Gets the (1,0)-indexed, buffer-relative cursor position for a given window + (different windows showing the same buffer have independent cursor + positions). |api-indexing| Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ (row, col) tuple @@ -2782,7 +2811,7 @@ nvim_win_get_height({window}) *nvim_win_get_height()* Gets the window height Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Height as a count of rows @@ -2791,7 +2820,7 @@ nvim_win_get_number({window}) *nvim_win_get_number()* Gets the window number Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Window number @@ -2800,7 +2829,7 @@ nvim_win_get_position({window}) *nvim_win_get_position()* Gets the window position in display cells. First position is zero. Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ (row, col) tuple with the window position @@ -2809,7 +2838,7 @@ nvim_win_get_tabpage({window}) *nvim_win_get_tabpage()* Gets the window tabpage Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Tabpage that contains the window @@ -2818,8 +2847,8 @@ nvim_win_get_var({window}, {name}) *nvim_win_get_var()* Gets a window-scoped (w:) variable Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name + • {window} Window handle, or 0 for current window + • {name} Variable name Return: ~ Variable value @@ -2828,7 +2857,7 @@ nvim_win_get_width({window}) *nvim_win_get_width()* Gets the window width Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Width as a count of columns @@ -2839,19 +2868,19 @@ nvim_win_hide({window}) *nvim_win_hide()* Like |:hide| the buffer becomes hidden unless another window is editing it, or 'bufhidden' is `unload`, `delete` or `wipe` as opposed to |:close| - or |nvim_win_close|, which will close the buffer. + or |nvim_win_close()|, which will close the buffer. Attributes: ~ not allowed when |textlock| is active Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window nvim_win_is_valid({window}) *nvim_win_is_valid()* Checks if a window is valid Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ true if the window is valid, false otherwise @@ -2863,48 +2892,48 @@ nvim_win_set_buf({window}, {buffer}) *nvim_win_set_buf()* not allowed when |textlock| is active Parameters: ~ - {window} Window handle, or 0 for current window - {buffer} Buffer handle + • {window} Window handle, or 0 for current window + • {buffer} Buffer handle nvim_win_set_cursor({window}, {pos}) *nvim_win_set_cursor()* Sets the (1,0)-indexed cursor position in the window. |api-indexing| This scrolls the window even if it is not the current one. Parameters: ~ - {window} Window handle, or 0 for current window - {pos} (row, col) tuple representing the new position + • {window} Window handle, or 0 for current window + • {pos} (row, col) tuple representing the new position nvim_win_set_height({window}, {height}) *nvim_win_set_height()* Sets the window height. Parameters: ~ - {window} Window handle, or 0 for current window - {height} Height as a count of rows + • {window} Window handle, or 0 for current window + • {height} Height as a count of rows nvim_win_set_hl_ns({window}, {ns_id}) *nvim_win_set_hl_ns()* Set highlight namespace for a window. This will use highlights defined in this namespace, but fall back to global highlights (ns=0) when missing. - This takes predecence over the 'winhighlight' option. + This takes precedence over the 'winhighlight' option. Parameters: ~ - {ns_id} the namespace to use + • {ns_id} the namespace to use nvim_win_set_var({window}, {name}, {value}) *nvim_win_set_var()* Sets a window-scoped (w:) variable Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name - {value} Variable value + • {window} Window handle, or 0 for current window + • {name} Variable name + • {value} Variable value nvim_win_set_width({window}, {width}) *nvim_win_set_width()* Sets the window width. This will only succeed if the screen is split vertically. Parameters: ~ - {window} Window handle, or 0 for current window - {width} Width as a count of columns + • {window} Window handle, or 0 for current window + • {width} Width as a count of columns ============================================================================== @@ -2949,9 +2978,9 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* not allowed when |textlock| is active Parameters: ~ - {buffer} Buffer to display, or 0 for current buffer - {enter} Enter the window (make it the current window) - {config} Map defining the window configuration. Keys: + • {buffer} Buffer to display, or 0 for current buffer + • {enter} Enter the window (make it the current window) + • {config} Map defining the window configuration. Keys: • relative: Sets the window layout to "floating", placed at (row,col) coordinates relative to: • "editor" The global editor grid @@ -3007,7 +3036,7 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* options. 'signcolumn' is changed to `auto` and 'colorcolumn' is cleared. The end-of-buffer region is hidden by setting `eob` flag of 'fillchars' to a space - char, and clearing the |EndOfBuffer| region in + char, and clearing the |hl-EndOfBuffer| region in 'winhighlight'. • border: Style of (optional) window border. This can either @@ -3052,7 +3081,7 @@ nvim_win_get_config({window}) *nvim_win_get_config()* `relative` is empty for normal windows. Parameters: ~ - {window} Window handle, or 0 for current window + • {window} Window handle, or 0 for current window Return: ~ Map defining the window configuration, see |nvim_open_win()| @@ -3065,8 +3094,8 @@ nvim_win_set_config({window}, {*config}) *nvim_win_set_config()* changed. `row`/`col` and `relative` must be reconfigured together. Parameters: ~ - {window} Window handle, or 0 for current window - {config} Map defining the window configuration, see |nvim_open_win()| + • {window} Window handle, or 0 for current window + • {config} Map defining the window configuration, see |nvim_open_win()| See also: ~ |nvim_open_win()| @@ -3079,14 +3108,14 @@ nvim_tabpage_del_var({tabpage}, {name}) *nvim_tabpage_del_var()* Removes a tab-scoped (t:) variable Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name + • {tabpage} Tabpage handle, or 0 for current tabpage + • {name} Variable name nvim_tabpage_get_number({tabpage}) *nvim_tabpage_get_number()* Gets the tabpage number Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + • {tabpage} Tabpage handle, or 0 for current tabpage Return: ~ Tabpage number @@ -3095,8 +3124,8 @@ nvim_tabpage_get_var({tabpage}, {name}) *nvim_tabpage_get_var()* Gets a tab-scoped (t:) variable Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name + • {tabpage} Tabpage handle, or 0 for current tabpage + • {name} Variable name Return: ~ Variable value @@ -3105,7 +3134,7 @@ nvim_tabpage_get_win({tabpage}) *nvim_tabpage_get_win()* Gets the current window in a tabpage Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + • {tabpage} Tabpage handle, or 0 for current tabpage Return: ~ Window handle @@ -3114,7 +3143,7 @@ nvim_tabpage_is_valid({tabpage}) *nvim_tabpage_is_valid()* Checks if a tabpage is valid Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + • {tabpage} Tabpage handle, or 0 for current tabpage Return: ~ true if the tabpage is valid, false otherwise @@ -3123,7 +3152,7 @@ nvim_tabpage_list_wins({tabpage}) *nvim_tabpage_list_wins()* Gets the windows in a tabpage Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + • {tabpage} Tabpage handle, or 0 for current tabpage Return: ~ List of windows in `tabpage` @@ -3133,9 +3162,9 @@ nvim_tabpage_set_var({tabpage}, {name}, {value}) Sets a tab-scoped (t:) variable Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name - {value} Variable value + • {tabpage} Tabpage handle, or 0 for current tabpage + • {name} Variable name + • {value} Variable value ============================================================================== @@ -3143,10 +3172,10 @@ Autocmd Functions *api-autocmd* nvim_clear_autocmds({*opts}) *nvim_clear_autocmds()* Clear all autocommands that match the corresponding {opts}. To delete a - particular autocmd, see |nvim_del_autocmd|. + particular autocmd, see |nvim_del_autocmd()|. Parameters: ~ - {opts} Parameters + • {opts} Parameters • event: (string|table) Examples: • event: "pat1" • event: { "pat1" } @@ -3178,8 +3207,8 @@ nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()* < Parameters: ~ - {name} String: The name of the group - {opts} Dictionary Parameters + • {name} String: The name of the group + • {opts} Dictionary Parameters • clear (bool) optional: defaults to true. Clear existing commands if the group already exists |autocmd-groups|. @@ -3242,9 +3271,9 @@ nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* < Parameters: ~ - {event} (string|array) The event or events to register this + • {event} (string|array) The event or events to register this autocommand - {opts} Dictionary of autocommand options: + • {opts} Dictionary of autocommand options: • group (string|integer) optional: the autocommand group name or id to match against. • pattern (string|array) optional: pattern or patterns to @@ -3290,12 +3319,12 @@ nvim_del_augroup_by_id({id}) *nvim_del_augroup_by_id()* To get a group id one can use |nvim_get_autocmds()|. - NOTE: behavior differs from |augroup-delete|. When deleting a group, + NOTE: behavior differs from |:augroup-delete|. When deleting a group, autocommands contained in this group will also be deleted and cleared. This group will no longer exist. Parameters: ~ - {id} Integer The id of the group. + • {id} Integer The id of the group. See also: ~ |nvim_del_augroup_by_name()| @@ -3304,15 +3333,15 @@ nvim_del_augroup_by_id({id}) *nvim_del_augroup_by_id()* nvim_del_augroup_by_name({name}) *nvim_del_augroup_by_name()* Delete an autocommand group by name. - NOTE: behavior differs from |augroup-delete|. When deleting a group, + NOTE: behavior differs from |:augroup-delete|. When deleting a group, autocommands contained in this group will also be deleted and cleared. This group will no longer exist. Parameters: ~ - {name} String The name of the group. + • {name} String The name of the group. See also: ~ - |autocommand-groups| + |autocmd-groups| nvim_del_autocmd({id}) *nvim_del_autocmd()* Delete an autocommand by id. @@ -3320,7 +3349,7 @@ nvim_del_autocmd({id}) *nvim_del_autocmd()* NOTE: Only autocommands created via the API have an id. Parameters: ~ - {id} Integer The id returned by nvim_create_autocmd + • {id} Integer The id returned by nvim_create_autocmd See also: ~ |nvim_create_autocmd()| @@ -3330,8 +3359,8 @@ nvim_exec_autocmds({event}, {*opts}) *nvim_exec_autocmds()* |autocmd-execute|. Parameters: ~ - {event} (String|Array) The event or events to execute - {opts} Dictionary of autocommand options: + • {event} (String|Array) The event or events to execute + • {opts} Dictionary of autocommand options: • group (string|integer) optional: the autocommand group name or id to match against. |autocmd-groups|. • pattern (string|array) optional: defaults to "*" @@ -3367,13 +3396,16 @@ nvim_get_autocmds({*opts}) *nvim_get_autocmds()* autocommands that match any combination of them. Parameters: ~ - {opts} Dictionary with at least one of the following: + • {opts} Dictionary with at least one of the following: • group (string|integer): the autocommand group name or id to match against. • event (string|array): event or events to match against |autocmd-events|. • pattern (string|array): pattern or patterns to match against - |autocmd-pattern|. + |autocmd-pattern|. Cannot be used with {buffer} + • buffer: Buffer number or list of buffer numbers for buffer + local autocommands |autocmd-buflocal|. Cannot be used with + {pattern} Return: ~ Array of autocommands matching the criteria, with each item containing @@ -3413,9 +3445,9 @@ nvim_ui_attach({width}, {height}, {options}) *nvim_ui_attach()* |RPC| only Parameters: ~ - {width} Requested screen columns - {height} Requested screen rows - {options} |ui-option| map + • {width} Requested screen columns + • {height} Requested screen rows + • {options} |ui-option| map nvim_ui_detach() *nvim_ui_detach()* Deactivates UI events on the channel. @@ -3427,8 +3459,8 @@ nvim_ui_detach() *nvim_ui_detach()* *nvim_ui_pum_set_bounds()* nvim_ui_pum_set_bounds({width}, {height}, {row}, {col}) - Tells Nvim the geometry of the popumenu, to align floating windows with an - external popup menu. + Tells Nvim the geometry of the popupmenu, to align floating windows with + an external popup menu. Note that this method is not to be confused with |nvim_ui_pum_set_height()|, which sets the number of visible items in the @@ -3441,20 +3473,20 @@ nvim_ui_pum_set_bounds({width}, {height}, {row}, {col}) |RPC| only Parameters: ~ - {width} Popupmenu width. - {height} Popupmenu height. - {row} Popupmenu row. - {col} Popupmenu height. + • {width} Popupmenu width. + • {height} Popupmenu height. + • {row} Popupmenu row. + • {col} Popupmenu height. nvim_ui_pum_set_height({height}) *nvim_ui_pum_set_height()* - Tells Nvim the number of elements displaying in the popumenu, to decide + Tells Nvim the number of elements displaying in the popupmenu, to decide <PageUp> and <PageDown> movement. Attributes: ~ |RPC| only Parameters: ~ - {height} Popupmenu height, must be greater than zero. + • {height} Popupmenu height, must be greater than zero. nvim_ui_set_option({name}, {value}) *nvim_ui_set_option()* TODO: Documentation @@ -3479,8 +3511,8 @@ nvim_ui_try_resize_grid({grid}, {width}, {height}) |RPC| only Parameters: ~ - {grid} The handle of the grid to be changed. - {width} The new requested width. - {height} The new requested height. + • {grid} The handle of the grid to be changed. + • {width} The new requested width. + • {height} The new requested height. vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt index 63226fe701..e27f191e0d 100644 --- a/runtime/doc/autocmd.txt +++ b/runtime/doc/autocmd.txt @@ -57,7 +57,7 @@ The special pattern <buffer> or <buffer=N> defines a buffer-local autocommand. See |autocmd-buflocal|. Note: The ":autocmd" command can only be followed by another command when the -'|' appears where the pattern is expected. This works: > +"|" appears where the pattern is expected. This works: > :augroup mine | au! BufRead | augroup END But this sees "augroup" as part of the defined command: > :augroup mine | au! BufRead * | augroup END @@ -412,6 +412,8 @@ CmdwinLeave Before leaving the command-line window. |cmdwin-char| *ColorScheme* ColorScheme After loading a color scheme. |:colorscheme| + Not triggered if the color scheme is not + found. The pattern is matched against the colorscheme name. <afile> can be used for the name of the actual file where this option was @@ -588,6 +590,7 @@ FileChangedShell When Vim notices that the modification time of - executing a shell command - |:checktime| - |FocusGained| + Not used when 'autoread' is set and the buffer was not changed. If a FileChangedShell autocommand exists the warning message and @@ -833,13 +836,13 @@ QuitPre When using `:quit`, `:wq` or `:qall`, before See also |ExitPre|, |WinClosed|. *RemoteReply* RemoteReply When a reply from a Vim that functions as - server was received |server2client()|. The + server was received server2client(). The pattern is matched against the {serverid}. <amatch> is equal to the {serverid} from which the reply was sent, and <afile> is the actual reply string. Note that even if an autocommand is defined, - the reply should be read with |remote_read()| + the reply should be read with remote_read() to consume it. *SearchWrapped* SearchWrapped After making a search with |n| or |N| if the @@ -1204,7 +1207,7 @@ still executed. ============================================================================== 7. Buffer-local autocommands *autocmd-buflocal* *autocmd-buffer-local* - *<buffer=N>* *<buffer=abuf>* *E680* + *<buffer>* *<buffer=N>* *<buffer=abuf>* *E680* Buffer-local autocommands are attached to a specific buffer. They are useful if the buffer does not have a name and when the name does not match a specific diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 0be9e9b9d1..344abe557c 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -6,9 +6,9 @@ Builtin functions *builtin-functions* -1. Overview |builtin-function-list| -2. Details |builtin-function-details| -3. Matching a pattern in a String |string-match| +For functions grouped by what they are used for see |function-list|. + + Type |gO| to see the table of contents. ============================================================================== 1. Overview *builtin-function-list* @@ -279,6 +279,8 @@ join({list} [, {sep}]) String join {list} items into one String json_decode({expr}) any Convert {expr} from JSON json_encode({expr}) String Convert {expr} to JSON keys({dict}) List keys in {dict} +keytrans({string}) String translate internal keycodes to a form + that can be used by |:map| len({expr}) Number the length of {expr} libcall({lib}, {func}, {arg}) String call {func} in library {lib} with {arg} libcallnr({lib}, {func}, {arg}) Number idem, but return a Number @@ -400,6 +402,7 @@ setbufvar({buf}, {varname}, {val}) set {varname} in buffer {buf} to {val} setcellwidths({list}) none set character cell width overrides setcharpos({expr}, {list}) Number set the {expr} position to {list} setcharsearch({dict}) Dict set character search from {dict} +setcmdline({str} [, {pos}]) Number set command-line setcmdpos({pos}) Number set cursor position in command-line setcursorcharpos({list}) Number move cursor to position in {list} setenv({name}, {val}) none set environment variable @@ -527,6 +530,8 @@ uniq({list} [, {func} [, {dict}]]) List remove adjacent duplicates from a list values({dict}) List values in {dict} virtcol({expr}) Number screen column of cursor or mark +virtcol2col({winid}, {lnum}, {col}) + Number byte index of a character on screen visualmode([expr]) String last visual mode used wait({timeout}, {condition} [, {interval}]) Number Wait until {condition} is satisfied @@ -784,7 +789,8 @@ browsedir({title}, {initdir}) browsing is not possible, an empty string is returned. bufadd({name}) *bufadd()* - Add a buffer to the buffer list with String {name}. + Add a buffer to the buffer list with name {name} (must be a + String). If a buffer for file {name} already exists, return that buffer number. Otherwise return the buffer number of the newly created buffer. When {name} is an empty string then a new @@ -835,7 +841,8 @@ bufload({buf}) *bufload()* Ensure the buffer {buf} is loaded. When the buffer name refers to an existing file then the file is read. Otherwise the buffer will be empty. If the buffer was already loaded - then there is no change. + then there is no change. If the buffer is not related to a + file the no file is read (e.g., when 'buftype' is "nofile"). If there is an existing swap file for the file of the buffer, there will be no dialog, the buffer will be loaded anyway. The {buf} argument is used like with |bufexists()|. @@ -1027,7 +1034,7 @@ chanclose({id} [, {stream}]) *chanclose()* are closed. If the channel is a pty, this will then close the pty master, sending SIGHUP to the job process. For a socket, there is only one stream, and {stream} should be - ommited. + omitted. chansend({id}, {data}) *chansend()* Send data to channel {id}. For a job, it writes it to the @@ -1126,16 +1133,20 @@ chdir({dir}) *chdir()* directory (|:tcd|) then changes the tabpage local directory. - Otherwise, changes the global directory. + {dir} must be a String. If successful, returns the previous working directory. Pass this to another chdir() to restore the directory. On failure, returns an empty string. Example: > let save_dir = chdir(newdir) - if save_dir + if save_dir != "" " ... do some work call chdir(save_dir) endif + +< Can also be used as a |method|: > + GetDir()->chdir() < cindent({lnum}) *cindent()* Get the amount of indent for line {lnum} according the C @@ -1270,7 +1281,7 @@ complete_info([{what}]) *complete_info()* typed text only, or the last completion after no item is selected when using the <Up> or <Down> keys) - inserted Inserted string. [NOT IMPLEMENT YET] + inserted Inserted string. [NOT IMPLEMENTED YET] *complete_info_mode* mode values are: @@ -1526,6 +1537,18 @@ cursor({list}) Can also be used as a |method|: > GetCursorPos()->cursor() +debugbreak({pid}) *debugbreak()* + Specifically used to interrupt a program being debugged. It + will cause process {pid} to get a SIGTRAP. Behavior for other + processes is undefined. See |terminal-debug|. + {Sends a SIGINT to a process {pid} other than MS-Windows} + + Returns |TRUE| if successfully interrupted the program. + Otherwise returns |FALSE|. + + Can also be used as a |method|: > + GetPid()->debugbreak() + deepcopy({expr} [, {noref}]) *deepcopy()* *E698* Make a copy of {expr}. For Numbers and Strings this isn't different from using {expr} directly. @@ -1967,18 +1990,6 @@ exp({expr}) *exp()* Can also be used as a |method|: > Compute()->exp() -debugbreak({pid}) *debugbreak()* - Specifically used to interrupt a program being debugged. It - will cause process {pid} to get a SIGTRAP. Behavior for other - processes is undefined. See |terminal-debugger|. - {Sends a SIGINT to a process {pid} other than MS-Windows} - - Returns |TRUE| if successfully interrupted the program. - Otherwise returns |FALSE|. - - Can also be used as a |method|: > - GetPid()->debugbreak() - expand({string} [, {nosuf} [, {list}]]) *expand()* Expand wildcards and the following special keywords in {string}. 'wildignorecase' applies. @@ -2010,6 +2021,8 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* a function <SID> "<SNR>123_" where "123" is the current script ID |<SID>| + <script> sourced script file, or script file + where the current function was defined <stack> call stack <cword> word under the cursor <cWORD> WORD under the cursor @@ -2043,6 +2056,9 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* is not defined, an empty string is used. Using "%:p" in a buffer with no name, results in the current directory, with a '/' added. + When 'verbose' is set then expanding '%', '#' and <> items + will result in an error message if the argument cannot be + expanded. When {string} does not start with '%', '#' or '<', it is expanded like a file name is expanded on the command line. @@ -2496,10 +2512,11 @@ funcref({name} [, {arglist}] [, {dict}]) Can also be used as a |method|: > GetFuncname()->funcref([arg]) < - *function()* *E700* *E922* *E923* + *function()* *partial* *E700* *E922* *E923* function({name} [, {arglist}] [, {dict}]) Return a |Funcref| variable that refers to function {name}. - {name} can be a user defined function or an internal function. + {name} can be the name of a user defined function or an + internal function. {name} can also be a Funcref or a partial. When it is a partial the dict stored in it will be used and the {dict} @@ -2518,30 +2535,56 @@ function({name} [, {arglist}] [, {dict}]) The arguments are passed to the function in front of other arguments, but after any argument from |method|. Example: > func Callback(arg1, arg2, name) - ... + "... let Partial = function('Callback', ['one', 'two']) - ... + "... call Partial('name') < Invokes the function as with: > call Callback('one', 'two', 'name') +< With a |method|: > + func Callback(one, two, three) + "... + let Partial = function('Callback', ['two']) + "... + eval 'one'->Partial('three') +< Invokes the function as with: > + call Callback('one', 'two', 'three') + +< The function() call can be nested to add more arguments to the + Funcref. The extra arguments are appended to the list of + arguments. Example: > + func Callback(arg1, arg2, name) + "... + let Func = function('Callback', ['one']) + let Func2 = function(Func, ['two']) + "... + call Func2('name') +< Invokes the function as with: > + call Callback('one', 'two', 'name') + < The Dictionary is only useful when calling a "dict" function. In that case the {dict} is passed in as "self". Example: > function Callback() dict echo "called for " .. self.name endfunction - ... + "... let context = {"name": "example"} let Func = function('Callback', context) - ... + "... call Func() " will echo: called for example +< The use of function() is not needed when there are no extra + arguments, these two are equivalent, if Callback() is defined + as context.Callback(): > + let Func = function('Callback', context) + let Func = context.Callback < The argument list and the Dictionary can be combined: > function Callback(arg1, count) dict - ... + "... let context = {"name": "example"} let Func = function('Callback', ['one'], context) - ... + "... call Func(500) < Invokes the function as with: > call context.Callback('one', 500) @@ -2587,7 +2630,7 @@ get({dict}, {key} [, {default}]) {default} is omitted. Useful example: > let val = get(g:, 'var_name', 'default') < This gets the value of g:var_name if it exists, and uses - 'default' when it does not exist. + "default" when it does not exist. get({func}, {what}) Get item {what} from Funcref {func}. Possible values for {what} are: @@ -2870,7 +2913,8 @@ getcmdcompltype() *getcmdcompltype()* Only works when the command line is being edited, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=|. See |:command-completion| for the return string. - Also see |getcmdtype()|, |setcmdpos()| and |getcmdline()|. + Also see |getcmdtype()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. Returns an empty string when completion is not defined. getcmdline() *getcmdline()* @@ -2879,7 +2923,8 @@ getcmdline() *getcmdline()* |c_CTRL-R_=|. Example: > :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR> -< Also see |getcmdtype()|, |getcmdpos()| and |setcmdpos()|. +< Also see |getcmdtype()|, |getcmdpos()|, |setcmdpos()| and + |setcmdline()|. Returns an empty string when entering a password or using |inputsecret()|. @@ -2889,7 +2934,8 @@ getcmdpos() *getcmdpos()* Only works when editing the command line, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. Returns 0 otherwise. - Also see |getcmdtype()|, |setcmdpos()| and |getcmdline()|. + Also see |getcmdtype()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. getcmdscreenpos() *getcmdscreenpos()* Return the screen position of the cursor in the command line @@ -2898,7 +2944,8 @@ getcmdscreenpos() *getcmdscreenpos()* Only works when editing the command line, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. Returns 0 otherwise. - Also see |getcmdpos()|, |setcmdpos()|. + Also see |getcmdpos()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. getcmdtype() *getcmdtype()* Return the current command-line type. Possible return values @@ -2990,7 +3037,7 @@ getcurpos([{winid}]) cursor vertically. Also see |getcursorcharpos()| and |getpos()|. The first "bufnum" item is always zero. The byte position of - the cursor is returned in 'col'. To get the character + the cursor is returned in "col". To get the character position, use |getcursorcharpos()|. The optional {winid} argument can specify the window. It can @@ -3196,7 +3243,7 @@ getloclist({nr} [, {what}]) *getloclist()* In addition to the items supported by |getqflist()| in {what}, the following item is supported by |getloclist()|: - filewinid id of the window used to display files + filewinid id of the window used to display files from the location list. This field is applicable only when called from a location list window. See @@ -3245,18 +3292,18 @@ getmatches([{win}]) *getmatches()* an empty list is returned. Example: > :echo getmatches() -< [{'group': 'MyGroup1', 'pattern': 'TODO', - 'priority': 10, 'id': 1}, {'group': 'MyGroup2', - 'pattern': 'FIXME', 'priority': 10, 'id': 2}] > +< [{"group": "MyGroup1", "pattern": "TODO", + "priority": 10, "id": 1}, {"group": "MyGroup2", + "pattern": "FIXME", "priority": 10, "id": 2}] > :let m = getmatches() :call clearmatches() :echo getmatches() < [] > :call setmatches(m) :echo getmatches() -< [{'group': 'MyGroup1', 'pattern': 'TODO', - 'priority': 10, 'id': 1}, {'group': 'MyGroup2', - 'pattern': 'FIXME', 'priority': 10, 'id': 2}] > +< [{"group": "MyGroup1", "pattern": "TODO", + "priority": 10, "id": 1}, {"group": "MyGroup2", + "pattern": "FIXME", "priority": 10, "id": 2}] > :unlet m < getmousepos() *getmousepos()* @@ -3369,7 +3416,7 @@ getqflist([{what}]) *getqflist()* |quickfix-ID|; zero means the id for the current list or the list specified by "nr" idx get information for the quickfix entry at this - index in the list specified by 'id' or 'nr'. + index in the list specified by "id" or "nr". If set to zero, then uses the current entry. See |quickfix-index| items quickfix list entries @@ -3455,7 +3502,7 @@ getreginfo([{regname}]) *getreginfo()* Dictionary with the following entries: regcontents List of lines contained in register {regname}, like - |getreg|({regname}, 1, 1). + getreg({regname}, 1, 1). regtype the type of register {regname}, as in |getregtype()|. isunnamed Boolean flag, v:true if this register @@ -3759,15 +3806,15 @@ has({feature}) Returns 1 if {feature} is supported, 0 otherwise. The {feature} argument is a feature name like "nvim-0.2.1" or "win32", see below. See also |exists()|. - If the code has a syntax error, then Nvim may skip the rest - of the line and miss |:endif|. > - if has('feature') | let x = this->breaks->without->the->feature | endif -< - Put |:if| and |:endif| on separate lines to avoid the - syntax error. > - if has('feature') - let x = this->breaks->without->the->feature - endif + To get the system name use |vim.loop|.os_uname() in Lua: > + :lua print(vim.loop.os_uname().sysname) + +< If the code has a syntax error then Vimscript may skip the + rest of the line. Put |:if| and |:endif| on separate lines to + avoid the syntax error: > + if has('feature') + let x = this->breaks->without->the->feature + endif < Vim's compile-time feature-names (prefixed with "+") are not recognized because Nvim is always compiled with all possible @@ -4371,7 +4418,7 @@ jobstart({cmd} [, {opts}]) *jobstart()* killed when Nvim exits. If the process exits before Nvim, `on_exit` will be invoked. env: (dict) Map of environment variable name:value - pairs extending (or replacing with |clear_env|) + pairs extending (or replace with "clear_env") the current environment. |jobstart-env| height: (number) Height of the `pty` terminal. |on_exit|: (function) Callback invoked when the job exits. @@ -4495,6 +4542,16 @@ keys({dict}) *keys()* Can also be used as a |method|: > mydict->keys() +keytrans({string}) *keytrans()* + Turn the internal byte representation of keys into a form that + can be used for |:map|. E.g. > + :let xx = "\<C-Home>" + :echo keytrans(xx) +< <C-Home> + + Can also be used as a |method|: > + "\<C-Home>"->keytrans() + < *len()* *E701* len({expr}) The result is a Number, which is the length of the argument. When {expr} is a String or a Number the length in bytes is @@ -4955,7 +5012,7 @@ matchadd({group}, {pattern} [, {priority} [, {id} [, {dict}]]]) respectively. 3 is reserved for use by the |matchparen| plugin. If the {id} argument is not specified or -1, |matchadd()| - automatically chooses a free ID. + automatically chooses a free ID, which is at least 1000. The optional {dict} argument allows for further custom values. Currently this is used to specify a match specific @@ -4963,7 +5020,7 @@ matchadd({group}, {pattern} [, {priority} [, {id} [, {dict}]]]) highlighted matches. The dict can have the following members: conceal Special character to show instead of the - match (only for |hl-Conceal| highlighed + match (only for |hl-Conceal| highlighted matches, see |:syn-cchar|) window Instead of the current window use the window with this number or window ID. @@ -5013,8 +5070,6 @@ matchaddpos({group}, {pos} [, {priority} [, {id} [, {dict}]]]) ignored, as well as entries with negative column numbers and lengths. - The maximum number of positions in {pos} is 8. - Returns -1 on error. Example: > @@ -5155,12 +5210,12 @@ matchfuzzypos({list}, {str} [, {dict}]) *matchfuzzypos()* Example: > :echo matchfuzzypos(['testing'], 'tsg') -< results in [['testing'], [[0, 2, 6]], [99]] > +< results in [["testing"], [[0, 2, 6]], [99]] > :echo matchfuzzypos(['clay', 'lacy'], 'la') -< results in [['lacy', 'clay'], [[0, 1], [1, 2]], [153, 133]] > +< results in [["lacy", "clay"], [[0, 1], [1, 2]], [153, 133]] > :echo [{'text': 'hello', 'id' : 10}] \ ->matchfuzzypos('ll', {'key' : 'text'}) -< results in [[{'id': 10, 'text': 'hello'}], [[2, 3]], [127]] +< results in [[{"id": 10, "text": "hello"}], [[2, 3]], [127]] matchlist({expr}, {pat} [, {start} [, {count}]]) *matchlist()* Same as |match()|, but return a |List|. The first item in the @@ -5580,12 +5635,19 @@ nvim_...({...}) *E5555* *nvim_...()* *eval-api* or({expr}, {expr}) *or()* Bitwise OR on the two arguments. The arguments are converted to a number. A List, Dict or Float argument causes an error. + Also see `and()` and `xor()`. Example: > :let bits = or(bits, 0x80) < Can also be used as a |method|: > :let bits = bits->or(0x80) -pathshorten({expr} [, {len}]) *pathshorten()* +< Rationale: The reason this is a function and not using the "|" + character like many languages, is that Vi has always used "|" + to separate commands. In many places it would not be clear if + "|" is an operator or a command separator. + + +pathshorten({path} [, {len}]) *pathshorten()* Shorten directory names in the path {path} and return the result. The tail, the file name, is kept as-is. The other components in the path are reduced to {len} letters in length. @@ -6008,6 +6070,8 @@ rand([{expr}]) *rand()* *readdir()* readdir({directory} [, {expr}]) Return a list with file and directory names in {directory}. + You can also use |glob()| if you don't need to do complicated + things, such as limiting the number of matches. When {expr} is omitted all entries are included. When {expr} is given, it is evaluated to check what to do: @@ -6106,7 +6170,9 @@ reg_recording() *reg_recording()* Returns the single letter name of the register being recorded. Returns an empty string when not recording. See |q|. -reltime([{start} [, {end}]]) *reltime()* +reltime() +reltime({start}) +reltime({start}, {end}) *reltime()* Return an item that represents a time value. The item is a list with items that depend on the system. The item can be passed to |reltimestr()| to convert it to a @@ -6160,7 +6226,8 @@ reltimestr({time}) *reltimestr()* Can also be used as a |method|: > reltime(start)->reltimestr() < -remove({list}, {idx} [, {end}]) *remove()* +remove({list}, {idx}) +remove({list}, {idx}, {end}) *remove()* Without {end}: Remove the item at {idx} from |List| {list} and return the item. With {end}: Remove items from {idx} to {end} (inclusive) and @@ -6178,7 +6245,8 @@ remove({list}, {idx} [, {end}]) *remove()* Can also be used as a |method|: > mylist->remove(idx) -remove({blob}, {idx} [, {end}]) +remove({blob}, {idx}) +remove({blob}, {idx}, {end}) Without {end}: Remove the byte at {idx} from |Blob| {blob} and return the byte. With {end}: Remove bytes from {idx} to {end} (inclusive) and @@ -6417,8 +6485,10 @@ search({pattern} [, {flags} [, {stopline} [, {timeout} [, {skip}]]]]) starts in column zero and then matches before the cursor are skipped. When the 'c' flag is present in 'cpo' the next search starts after the match. Without the 'c' flag the next - search starts one column further. This matters for - overlapping matches. + search starts one column after the start of the match. This + matters for overlapping matches. See |cpo-c|. You can also + insert "\ze" to change where the match ends, see |/\ze|. + When searching backwards and the 'z' flag is given then the search starts in column zero, thus no match in the current line will be found (unless wrapping around the end of the @@ -6900,6 +6970,16 @@ setcharsearch({dict}) *setcharsearch()* Can also be used as a |method|: > SavedSearch()->setcharsearch() +setcmdline({str} [, {pos}]) *setcmdline()* + Set the command line to {str} and set the cursor position to + {pos}. + If {pos} is omitted, the cursor is positioned after the text. + Returns 0 when successful, 1 when not editing the command + line. + + Can also be used as a |method|: > + GetText()->setcmdline() + setcmdpos({pos}) *setcmdpos()* Set the cursor position in the command line to byte position {pos}. The first position is 1. @@ -6912,8 +6992,8 @@ setcmdpos({pos}) *setcmdpos()* before inserting the resulting text. When the number is too big the cursor is put at the end of the line. A number smaller than one has undefined results. - Returns FALSE when successful, TRUE when not editing the - command line. + Returns 0 when successful, 1 when not editing the command + line. Can also be used as a |method|: > GetPos()->setcmdpos() @@ -7150,7 +7230,7 @@ setqflist({list} [, {action} [, {what}]]) *setqflist()* See |quickfix-parse| id quickfix list identifier |quickfix-ID| idx index of the current entry in the quickfix - list specified by 'id' or 'nr'. If set to '$', + list specified by "id" or "nr". If set to '$', then the last entry in the list is set as the current entry. See |quickfix-index| items list of quickfix entries. Same as the {list} @@ -7642,7 +7722,7 @@ sqrt({expr}) *sqrt()* :echo sqrt(100) < 10.0 > :echo sqrt(-4.01) -< str2float('nan') +< str2float("nan") NaN may be different, it depends on system libraries. Can also be used as a |method|: > @@ -7697,14 +7777,13 @@ stdpath({what}) *stdpath()* *E6100* config String User configuration directory. |init.vim| is stored here. config_dirs List Other configuration directories. - data String User data directory. The |shada-file| - is stored here. + data String User data directory. data_dirs List Other data directories. log String Logs directory (for use by plugins too). run String Run directory: temporary, local storage for sockets, named pipes, etc. state String Session state directory: storage for file - drafts, undo, shada, etc. + drafts, swap, undo, |shada|. Example: > :echo stdpath("config") @@ -8175,7 +8254,7 @@ synIDattr({synID}, {what} [, {mode}]) *synIDattr()* "bg" background color (as with "fg") "font" font name (only available in the GUI) |highlight-font| - "sp" special color (as with "fg") |highlight-guisp| + "sp" special color (as with "fg") |guisp| "fg#" like "fg", but for the GUI and the GUI is running the name in "#RRGGBB" form "bg#" like "fg#" for "bg" @@ -8231,12 +8310,12 @@ synconcealed({lnum}, {col}) *synconcealed()* the text is "123456" and both "23" and "45" are concealed and replaced by the character "X", then: call returns ~ - synconcealed(lnum, 1) [0, '', 0] - synconcealed(lnum, 2) [1, 'X', 1] - synconcealed(lnum, 3) [1, 'X', 1] - synconcealed(lnum, 4) [1, 'X', 2] - synconcealed(lnum, 5) [1, 'X', 2] - synconcealed(lnum, 6) [0, '', 0] + synconcealed(lnum, 1) [0, '', 0] + synconcealed(lnum, 2) [1, 'X', 1] + synconcealed(lnum, 3) [1, 'X', 1] + synconcealed(lnum, 4) [1, 'X', 2] + synconcealed(lnum, 5) [1, 'X', 2] + synconcealed(lnum, 6) [0, '', 0] synstack({lnum}, {col}) *synstack()* @@ -8780,6 +8859,26 @@ virtcol({expr}) *virtcol()* < Can also be used as a |method|: > GetPos()->virtcol() +virtcol2col({winid}, {lnum}, {col}) *virtcol2col()* + The result is a Number, which is the byte index of the + character in window {winid} at buffer line {lnum} and virtual + column {col}. + + If {col} is greater than the last virtual column in line + {lnum}, then the byte index of the character at the last + virtual column is returned. + + The {winid} argument can be the window number or the + |window-ID|. If this is zero, then the current window is used. + + Returns -1 if the window {winid} doesn't exist or the buffer + line {lnum} or virtual column {col} is invalid. + + See also |screenpos()|, |virtcol()| and |col()|. + + Can also be used as a |method|: > + GetWinid()->virtcol2col(lnum, col) + visualmode([{expr}]) *visualmode()* The result is a String, which describes the last Visual mode used in the current buffer. Initially it returns an empty @@ -9014,12 +9113,12 @@ winlayout([{tabnr}]) *winlayout()* returns an empty list. For a leaf window, it returns: - ['leaf', {winid}] + ["leaf", {winid}] For horizontally split windows, which form a column, it returns: - ['col', [{nested list of windows}]] + ["col", [{nested list of windows}]] For vertically split windows, which form a row, it returns: - ['row', [{nested list of windows}]] + ["row", [{nested list of windows}]] Example: > " Only one window in the tab page @@ -9211,6 +9310,7 @@ writefile({object}, {fname} [, {flags}]) xor({expr}, {expr}) *xor()* Bitwise XOR on the two arguments. The arguments are converted to a number. A List, Dict or Float argument causes an error. + Also see `and()` and `or()`. Example: > :let bits = xor(bits, 0x80) < diff --git a/runtime/doc/change.txt b/runtime/doc/change.txt index a4ff4474e6..bed5cb26d7 100644 --- a/runtime/doc/change.txt +++ b/runtime/doc/change.txt @@ -1130,11 +1130,20 @@ used. If you do need it you can use |p| with another register. E.g., yank the text to copy, Visually select the text to replace and use "0p . You can repeat this as many times as you like, and the unnamed register will be changed each time. - -When you use a blockwise Visual mode command and yank only a single line into -a register, a paste on a visual selected area will paste that single line on -each of the selected lines (thus replacing the blockwise selected region by a -block of the pasted line). + *blockwise-put* +When a register contains text from one line (characterwise), using a +blockwise Visual selection, putting that register will paste that text +repeatedly in each of the selected lines, thus replacing the blockwise +selected region by multiple copies of the register text. For example: + - yank the word "TEXT" into a register with `yw` + - select a visual block, marked with "v" in this text: + aaavvaaa + bbbvvbbb + cccvvccc + - press `p`, results in: + aaaTEXTaaa + bbbTEXTbbb + cccTEXTccc *blockwise-register* If you use a blockwise Visual mode command to get the text into the register, diff --git a/runtime/doc/channel.txt b/runtime/doc/channel.txt index d4bed7a5f2..f4a17b1842 100644 --- a/runtime/doc/channel.txt +++ b/runtime/doc/channel.txt @@ -48,21 +48,22 @@ a job channel using RPC, bytes can still be read over its stderr. Similarly, only bytes can be written to Nvim's own stderr. *channel-callback* -on_stdout({chan-id}, {data}, {name}) *on_stdout* -on_stderr({chan-id}, {data}, {name}) *on_stderr* -on_stdin({chan-id}, {data}, {name}) *on_stdin* -on_data({chan-id}, {data}, {name}) *on_data* +- on_stdout({chan-id}, {data}, {name}) *on_stdout* +- on_stderr({chan-id}, {data}, {name}) *on_stderr* +- on_stdin({chan-id}, {data}, {name}) *on_stdin* +- on_data({chan-id}, {data}, {name}) *on_data* + Scripts can react to channel activity (received data) via callback functions assigned to the `on_stdout`, `on_stderr`, `on_stdin`, or `on_data` option keys. Callbacks should be fast: avoid potentially slow/expensive work. Parameters: ~ - {chan-id} Channel handle. |channel-id| - {data} Raw data (|readfile()|-style list of strings) read from + - {chan-id} Channel handle. |channel-id| + - {data} Raw data (|readfile()|-style list of strings) read from the channel. EOF is a single-item list: `['']`. First and last items may be partial lines! |channel-lines| - {name} Stream name (string) like "stdout", so the same function + - {name} Stream name (string) like "stdout", so the same function can handle multiple streams. Event names depend on how the channel was opened and in what mode/protocol. @@ -83,13 +84,14 @@ on_data({chan-id}, {data}, {name}) *on_data* the final `['']` emitted at EOF): - `foobar` may arrive as `['fo'], ['obar']` - `foo\nbar` may arrive as - `['foo','bar']` - or `['foo',''], ['bar']` - or `['foo'], ['','bar']` - or `['fo'], ['o','bar']` + - `['foo','bar']` + - or `['foo',''], ['bar']` + - or `['foo'], ['','bar']` + - or `['fo'], ['o','bar']` + There are two ways to deal with this: - 1. To wait for the entire output, use |channel-buffered| mode. - 2. To read line-by-line, use the following code: > + - 1. To wait for the entire output, use |channel-buffered| mode. + - 2. To read line-by-line, use the following code: > let s:lines = [''] func! s:on_event(job_id, data, event) dict let eof = (a:data == ['']) diff --git a/runtime/doc/cmdline.txt b/runtime/doc/cmdline.txt index 29eff75bfa..b1013420fa 100644 --- a/runtime/doc/cmdline.txt +++ b/runtime/doc/cmdline.txt @@ -764,7 +764,7 @@ Count and Range *N:* When giving a count before entering ":", this is translated into: :.,.+(count - 1) -In words: The 'count' lines at and after the cursor. Example: To delete +In words: The "count" lines at and after the cursor. Example: To delete three lines: > 3:d<CR> is translated into: .,.+2d<CR> < @@ -881,7 +881,7 @@ Note: these are typed literally, they are not special keys! file name of the sourced file. *E498* When executing a function, is replaced with the call stack, as with <stack> (this is for backwards compatibility, using - <stack> is preferred). + <stack> or <script> is preferred). Note that filename-modifiers are useless when <sfile> is not used inside a script. *:<stack>* *<stack>* @@ -891,6 +891,12 @@ Note: these are typed literally, they are not special keys! ".." in between items. E.g.: "function {function-name1}[{lnum}]..{function-name2}[{lnum}]" If there is no call stack you get error *E489* . + *:<script>* *<script>* + <script> When executing a `:source` command, is replaced with the file + name of the sourced file. When executing a function, is + replaced with the file name of the script where it is + defined. + If the file name cannot be determined you get error *E1274* . *:<slnum>* *<slnum>* <slnum> When executing a `:source` command, is replaced with the line number. *E842* diff --git a/runtime/doc/deprecated.txt b/runtime/doc/deprecated.txt index eb6d9b6dc9..8fcd0fc1d0 100644 --- a/runtime/doc/deprecated.txt +++ b/runtime/doc/deprecated.txt @@ -10,150 +10,149 @@ The items listed below are deprecated: they will be removed in the future. They should not be used in new scripts, and old scripts should be updated. ============================================================================== - -API ~ -*nvim_buf_clear_highlight()* Use |nvim_buf_clear_namespace()| instead. -*nvim_buf_set_virtual_text()* Use |nvim_buf_set_extmark()| instead. -*nvim_command_output()* Use |nvim_exec()| instead. -*nvim_execute_lua()* Use |nvim_exec_lua()| instead. - -Commands ~ -*:rv* -*:rviminfo* Deprecated alias to |:rshada| command. -*:wv* -*:wviminfo* Deprecated alias to |:wshada| command. - -Environment Variables ~ -*$NVIM_LISTEN_ADDRESS* Deprecated way to - * set the server name (use |--listen| instead) - * get the server name (use |v:servername| instead) - * detect a parent Nvim (use |$NVIM| instead) - Unset by |terminal| and |jobstart()| (unless explicitly - given by the "env" option). Ignored if --listen is given. - -Events ~ -*BufCreate* Use |BufAdd| instead. -*EncodingChanged* Never fired; 'encoding' is always "utf-8". -*FileEncoding* Never fired; equivalent to |EncodingChanged|. -*GUIEnter* Never fired; use |UIEnter| instead. -*GUIFailed* Never fired. - -Keycodes ~ -*<MouseDown>* Use <ScrollWheelUp> instead. -*<MouseUp>* Use <ScrollWheelDown> instead. - -Functions ~ -*buffer_exists()* Obsolete name for |bufexists()|. -*buffer_name()* Obsolete name for |bufname()|. -*buffer_number()* Obsolete name for |bufnr()|. -*file_readable()* Obsolete name for |filereadable()|. -*highlight_exists()* Obsolete name for |hlexists()|. -*highlightID()* Obsolete name for |hlID()|. -*inputdialog()* Use |input()| instead. -*jobclose()* Obsolete name for |chanclose()| -*jobsend()* Obsolete name for |chansend()| -*last_buffer_nr()* Obsolete name for bufnr("$"). -*rpcstop()* Deprecated. Instead use |jobstop()| to stop any job, - or chanclose(id, "rpc") to close RPC communication +Deprecated features + +API +- *nvim_buf_clear_highlight()* Use |nvim_buf_clear_namespace()| instead. +- *nvim_buf_set_virtual_text()* Use |nvim_buf_set_extmark()| instead. +- *nvim_command_output()* Use |nvim_exec()| instead. +- *nvim_execute_lua()* Use |nvim_exec_lua()| instead. + +COMMANDS +- *:rv* *:rviminfo* Deprecated alias to |:rshada| command. +- *:wv* *:wviminfo* Deprecated alias to |:wshada| command. + +ENVIRONMENT VARIABLES +- *$NVIM_LISTEN_ADDRESS* + - Deprecated way to: + - set the server name (use |--listen| or |serverstart()| instead) + - get the server name (use |v:servername| instead) + - detect a parent Nvim (use |$NVIM| instead) + - Ignored if --listen is given. + - Unset by |terminal| and |jobstart()| unless explicitly given by the "env" + option. Example: > + call jobstart(['foo'], { 'env': { 'NVIM_LISTEN_ADDRESS': v:servername } }) +< + +EVENTS +- *BufCreate* Use |BufAdd| instead. +- *EncodingChanged* Never fired; 'encoding' is always "utf-8". +- *FileEncoding* Never fired; equivalent to |EncodingChanged|. +- *GUIEnter* Never fired; use |UIEnter| instead. +- *GUIFailed* Never fired. + +KEYCODES +- *<MouseDown>* Use <ScrollWheelUp> instead. +- *<MouseUp>* Use <ScrollWheelDown> instead. + +FUNCTIONS +- *buffer_exists()* Obsolete name for |bufexists()|. +- *buffer_name()* Obsolete name for |bufname()|. +- *buffer_number()* Obsolete name for |bufnr()|. +- *file_readable()* Obsolete name for |filereadable()|. +- *health#report_error* Use Lua |vim.health.report_error()| instead. +- *health#report_info* Use Lua |vim.health.report_info()| instead. +- *health#report_ok* Use Lua |vim.health.report_ok()| instead. +- *health#report_start* Use Lua |vim.health.report_start()| instead. +- *health#report_warn* Use Lua |vim.health.report_warn()| instead. +- *highlight_exists()* Obsolete name for |hlexists()|. +- *highlightID()* Obsolete name for |hlID()|. +- *inputdialog()* Use |input()| instead. +- *jobclose()* Obsolete name for |chanclose()| +- *jobsend()* Obsolete name for |chansend()| +- *last_buffer_nr()* Obsolete name for bufnr("$"). +- *rpcstop()* Use |jobstop()| instead to stop any job, or + `chanclose(id, "rpc")` to close RPC communication without stopping the job. Use chanclose(id) to close any socket. -Highlights ~ - -*hl-VertSplit* Use |hl-WinSeparator| instead. - -LSP Diagnostics ~ +HIGHLIGHTS +- *hl-VertSplit* Use |hl-WinSeparator| instead. +LSP DIAGNOSTICS For each of the functions below, use the corresponding function in |vim.diagnostic| instead (unless otherwise noted). For example, use |vim.diagnostic.get()| instead of |vim.lsp.diagnostic.get()|. -*vim.lsp.diagnostic.clear()* Use |vim.diagnostic.hide()| instead. -*vim.lsp.diagnostic.disable()* -*vim.lsp.diagnostic.display()* Use |vim.diagnostic.show()| instead. -*vim.lsp.diagnostic.enable()* -*vim.lsp.diagnostic.get()* -*vim.lsp.diagnostic.get_all()* Use |vim.diagnostic.get()| instead. -*vim.lsp.diagnostic.get_count()* Use |vim.diagnostic.get()| instead. -*vim.lsp.diagnostic.get_line_diagnostics()* - Use |vim.diagnostic.get()| instead. -*vim.lsp.diagnostic.get_next()* -*vim.lsp.diagnostic.get_next_pos()* -*vim.lsp.diagnostic.get_prev()* -*vim.lsp.diagnostic.get_prev_pos()* -*vim.lsp.diagnostic.get_virtual_text_chunks_for_line()* - No replacement. Use options provided by - |vim.diagnostic.config()| to customize - virtual text. -*vim.lsp.diagnostic.goto_next()* -*vim.lsp.diagnostic.goto_prev()* -*vim.lsp.diagnostic.redraw()* Use |vim.diagnostic.show()| instead. -*vim.lsp.diagnostic.reset()* -*vim.lsp.diagnostic.save()* Use |vim.diagnostic.set()| instead. -*vim.lsp.diagnostic.set_loclist()* Use |vim.diagnostic.setloclist()| instead. -*vim.lsp.diagnostic.set_qflist()* Use |vim.diagnostic.setqflist()| instead. - -The following have been replaced by |vim.diagnostic.open_float()|. - -*vim.lsp.diagnostic.show_line_diagnostics()* -*vim.lsp.diagnostic.show_position_diagnostics()* +- *vim.lsp.diagnostic.clear()* Use |vim.diagnostic.hide()| instead. +- *vim.lsp.diagnostic.disable()* +- *vim.lsp.diagnostic.display()* Use |vim.diagnostic.show()| instead. +- *vim.lsp.diagnostic.enable()* +- *vim.lsp.diagnostic.get()* +- *vim.lsp.diagnostic.get_all()* Use |vim.diagnostic.get()| instead. +- *vim.lsp.diagnostic.get_count()* Use |vim.diagnostic.get()| instead. +- *vim.lsp.diagnostic.get_line_diagnostics()* Use |vim.diagnostic.get()| instead. +- *vim.lsp.diagnostic.get_next()* +- *vim.lsp.diagnostic.get_next_pos()* +- *vim.lsp.diagnostic.get_prev()* +- *vim.lsp.diagnostic.get_prev_pos()* +- *vim.lsp.diagnostic.get_virtual_text_chunks_for_line()* No replacement. Use + options provided by |vim.diagnostic.config()| to customize virtual text. +- *vim.lsp.diagnostic.goto_next()* +- *vim.lsp.diagnostic.goto_prev()* +- *vim.lsp.diagnostic.redraw()* Use |vim.diagnostic.show()| instead. +- *vim.lsp.diagnostic.reset()* +- *vim.lsp.diagnostic.save()* Use |vim.diagnostic.set()| instead. +- *vim.lsp.diagnostic.set_loclist()* Use |vim.diagnostic.setloclist()| instead. +- *vim.lsp.diagnostic.set_qflist()* Use |vim.diagnostic.setqflist()| instead. +- *vim.lsp.diagnostic.show_line_diagnostics()* Use |vim.diagnostic.open_float()| instead. +- *vim.lsp.diagnostic.show_position_diagnostics()* Use |vim.diagnostic.open_float()| instead. The following are deprecated without replacement. These functions are moved internally and are no longer exposed as part of the API. Instead, use |vim.diagnostic.config()| and |vim.diagnostic.show()|. -*vim.lsp.diagnostic.set_signs()* -*vim.lsp.diagnostic.set_underline()* -*vim.lsp.diagnostic.set_virtual_text()* - -LSP Functions ~ - -*vim.lsp.util.diagnostics_to_items()* Use |vim.diagnostic.toqflist()| instead. -*vim.lsp.util.set_qflist()* Use |setqflist()| instead. -*vim.lsp.util.set_loclist()* Use |setloclist()| instead. -*vim.lsp.buf_get_clients()* Use |vim.lsp.get_active_clients()| with +- *vim.lsp.diagnostic.set_signs()* +- *vim.lsp.diagnostic.set_underline()* +- *vim.lsp.diagnostic.set_virtual_text()* + +LSP FUNCTIONS +- *vim.lsp.range_code_action* Use |vim.lsp.buf.code_action()| with + the `range` parameter. +- *vim.lsp.util.diagnostics_to_items()* Use |vim.diagnostic.toqflist()| instead. +- *vim.lsp.util.set_qflist()* Use |setqflist()| instead. +- *vim.lsp.util.set_loclist()* Use |setloclist()| instead. +- *vim.lsp.buf_get_clients()* Use |vim.lsp.get_active_clients()| with {buffer = bufnr} instead. - -Lua ~ -*vim.register_keystroke_callback()* Use |vim.on_key()| instead. - -Modifiers ~ -*cpo-<* -*:menu-<special>* -*:menu-special* <> notation is always enabled. -*:map-<special>* -*:map-special* <> notation is always enabled. - -Normal commands ~ -*]f* -*[f* Same as "gf". - -Options ~ -*'cscopeverbose'* Enabled by default. Use |:silent| instead. -*'exrc'* *'ex'* Security risk: downloaded files could include +- *vim.lsp.buf.formatting()* Use |vim.lsp.buf.format()| with + {async = true} instead. +- *vim.lsp.buf.range_formatting()* Use |vim.lsp.formatexpr()| + or |vim.lsp.buf.format()| instead. + +LUA +- *vim.register_keystroke_callback()* Use |vim.on_key()| instead. + +NORMAL COMMANDS +- *]f* *[f* Same as "gf". + +OPTIONS +- *cpo-<* *:menu-<special>* *:menu-special* *:map-<special>* *:map-special* + `<>` notation is always enabled. +- *'cscopeverbose'* Enabled by default. Use |:silent| instead. +- *'exrc'* *'ex'* Security risk: downloaded files could include a malicious .nvimrc or .exrc file. See 'secure'. Recommended alternative: define an autocommand in your |vimrc| to set options for a matching directory. -'gd' -'gdefault' Enables the |:substitute| flag 'g' by default. -*'fe'* 'fenc'+'enc' before Vim 6.0; no longer used. -*'highlight'* *'hl'* Names of builtin |highlight-groups| cannot be changed. -*'langnoremap'* Deprecated alias to 'nolangremap'. -'sessionoptions' Flags "unix", "slash" are ignored and always enabled. -*'vi'* -'viewoptions' Flags "unix", "slash" are ignored and always enabled. -*'viminfo'* Deprecated alias to 'shada' option. -*'viminfofile'* Deprecated alias to 'shadafile' option. - -UI extensions~ -*ui-wildmenu* Use |ui-cmdline| with |ui-popupmenu| instead. Enabled +- 'gdefault' Enables the |:substitute| flag 'g' by default. +- *'fe'* 'fenc'+'enc' before Vim 6.0; no longer used. +- *'highlight'* *'hl'* Names of builtin |highlight-groups| cannot be changed. +- *'langnoremap'* Deprecated alias to 'nolangremap'. +- 'sessionoptions' Flags "unix", "slash" are ignored and always enabled. +- *'vi'* +- 'viewoptions' Flags "unix", "slash" are ignored and always enabled. +- *'viminfo'* Deprecated alias to 'shada' option. +- *'viminfofile'* Deprecated alias to 'shadafile' option. + +UI EXTENSIONS +- *ui-wildmenu* Use |ui-cmdline| with |ui-popupmenu| instead. Enabled by the `ext_wildmenu` |ui-option|. Emits these events: - ["wildmenu_show", items] - ["wildmenu_select", selected] - ["wildmenu_hide"] + - `["wildmenu_show", items]` + - `["wildmenu_select", selected]` + - `["wildmenu_hide"]` -Variables~ -*b:terminal_job_pid* PID of the top-level process in a |:terminal|. +VARIABLES +- *b:terminal_job_pid* PID of the top-level process in a |:terminal|. Use `jobpid(&channel)` instead. + vim:noet:tw=78:ts=8:ft=help:norl: diff --git a/runtime/doc/develop.txt b/runtime/doc/develop.txt index b31ac47bda..1ba6ae757b 100644 --- a/runtime/doc/develop.txt +++ b/runtime/doc/develop.txt @@ -131,6 +131,7 @@ DOCUMENTATION *dev-doc* (docstrings, user manual, website materials, newsletters, …). Don't mince words. Personality and flavor, used sparingly, are welcome--but in general, optimize for the reader's time and energy: be "precise yet concise". + - See https://developers.google.com/style/tone - Prefer the active voice: "Foo does X", not "X is done by Foo". - Vim differences: - Do not prefix help tags with "nvim-". Use |vim_diff.txt| to catalog @@ -144,13 +145,33 @@ DOCUMENTATION *dev-doc* - Use "tui-" to prefix help tags related to the host terminal, and "TUI" in prose if possible. - Docstrings: do not start parameter descriptions with "The" or "A" unless it - is critical to avoid ambiguity. - GOOD: > - /// @param dirname Path fragment before `pend` -< BAD: > - /// @param dirname The path fragment before `pend` + is critical to avoid ambiguity. > + GOOD: + /// @param dirname Path fragment before `pend` + BAD: + /// @param dirname The path fragment before `pend` < +Documentation format ~ + +For Nvim-owned docs, use the following strict subset of "vimdoc" to ensure +the help doc renders nicely in other formats (such as HTML: +https://neovim.io/doc/user ). + +Strict "vimdoc" subset: + +- Use lists (like this!) prefixed with "-", "*", or "•", for adjacent lines + that you don't want auto-wrapped. Lists are always rendered with "flow" + (soft-wrapped) layout instead of preformatted (hard-wrapped) layout common + in legacy :help docs. + - Limitation: currently the parser https://github.com/neovim/tree-sitter-vimdoc + does not understand numbered listitems, so use a bullet symbol (- or •) + before numbered items, e.g. "- 1." instead of "1.". +- Separate blocks (paragraphs) of content by a blank line(s). +- Do not use indentation in random places—that prevents the page from using + "flow" layout. If you need a preformatted section, put it in + a |help-codeblock| starting with ">". + C docstrings ~ Nvim API documentation lives in the source code, as docstrings (Doxygen @@ -163,7 +184,7 @@ Docstring format: `@note`, `@param`, `@returns` - Limited markdown is supported. - List-items start with `-` (useful to nest or "indent") -- Use `<pre>` for code samples. +- Use `<pre>` for code samples. Example: the help for |nvim_open_win()| is generated from a docstring defined in src/nvim/api/win_config.c like this: > @@ -201,7 +222,7 @@ Docstring format: `---@see`, `---@param`, `---@returns` - Limited markdown is supported. - List-items start with `-` (useful to nest or "indent") -- Use `<pre>` for code samples. +- Use `<pre>` for code samples. Example: the help for |vim.paste()| is generated from a docstring decorating vim.paste in runtime/lua/vim/_editor.lua like this: > @@ -234,7 +255,8 @@ LUA *dev-lua* API *dev-api* -Use this template to name new RPC |API| functions: +Use this format to name new RPC |API| functions: + nvim_{thing}_{action}_{arbitrary-qualifiers} If the function acts on an object then {thing} is the name of that object @@ -243,31 +265,50 @@ If the function acts on an object then {thing} is the name of that object with a {thing} that groups functions under a common concept). Use existing common {action} names if possible: - add Append to, or insert into, a collection - create Create a new thing - del Delete a thing (or group of things) - exec Execute code - get Get a thing (or group of things by query) - list Get all things - set Set a thing (or group of things) - -Use consistent names for {thing} in all API functions. E.g. a buffer is called + - add Append to, or insert into, a collection + - call Call a function + - create Create a new (non-trivial) thing + - del Delete a thing (or group of things) + - eval Evaluate an expression + - exec Execute code + - fmt Format + - get Get things (often by a query) + - open Open + - parse Parse something into a structured form + - set Set a thing (or group of things) + +Do NOT use these deprecated verbs: + - list Redundant with "get" + +Use consistent names for {thing} (nouns) in API functions: buffer is called "buf" everywhere, not "buffer" in some places and "buf" in others. + - buf Buffer + - chan |channel| + - cmd Command + - cmdline Command-line UI or input + - fn Function + - hl Highlight + - pos Position + - proc System process + - tabpage Tabpage + - win Window + +Do NOT use these deprecated nouns: + - buffer + - command + - window Example: - `nvim_get_current_line` acts on the global editor state; the common - {action} "get" is used but {thing} is omitted. - -Example: - `nvim_buf_add_highlight` acts on a `Buffer` object (the first parameter) - and uses the common {action} "add". + `nvim_get_keymap('v')` operates in a global context (first parameter is not + a Buffer). The "get" {action} indicates that it gets anything matching the + given filter parameter. There is no need for a "list" action because + `nvim_get_keymap('')` (i.e., empty filter) returns all items. Example: - `nvim_list_bufs` operates in a global context (first parameter is not - a Buffer). The common {action} "list" indicates that it lists all bufs - (plural) in the global context. + `nvim_buf_del_mark` acts on a `Buffer` object (the first parameter) + and uses the "del" {action}. -Use this template to name new API events: +Use this format to name new API events: nvim_{thing}_{event}_event Example: @@ -309,10 +350,10 @@ a good name: it's idiomatic and unambiguous. If the package is named "neovim", it confuses users, and complicates documentation and discussions. Examples of API-client package names: - GOOD: nvim-racket - GOOD: pynvim - BAD: python-client - BAD: neovim +- GOOD: nvim-racket +- GOOD: pynvim +- BAD: python-client +- BAD: neovim API client implementation guidelines ~ @@ -378,4 +419,4 @@ Use the "on_" prefix to name event handlers and also the interface for a confused collection of naming conventions for these related concepts. - vim:tw=78:ts=8:noet:ft=help:norl: + vim:tw=78:ts=8:sw=4:et:ft=help:norl: diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt index e1b52746be..828093ddd4 100644 --- a/runtime/doc/diagnostic.txt +++ b/runtime/doc/diagnostic.txt @@ -295,10 +295,18 @@ option in the "signs" table of |vim.diagnostic.config()| or 10 if unset). EVENTS *diagnostic-events* *DiagnosticChanged* -DiagnosticChanged After diagnostics have changed. +DiagnosticChanged After diagnostics have changed. When used from Lua, + the new diagnostics are passed to the autocmd + callback in the "data" table. Example: > - autocmd DiagnosticChanged * lua vim.diagnostic.setqflist({ open = false }) + + vim.api.nvim_create_autocmd('DiagnosticChanged', { + callback = function(args) + local diagnostics = args.data.diagnostics + vim.pretty_print(diagnostics) + end, + }) < ============================================================================== Lua module: vim.diagnostic *diagnostic-api* @@ -334,7 +342,7 @@ config({opts}, {namespace}) *vim.diagnostic.config()* any of the above. Parameters: ~ - {opts} (table|nil) When omitted or "nil", retrieve the current + • {opts} (table|nil) When omitted or "nil", retrieve the current configuration. Otherwise, a configuration table with the following keys: • underline: (default true) Use underline for @@ -389,32 +397,32 @@ 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} (number|nil) Update the options for the given namespace. + • {namespace} (number|nil) Update the options for the given namespace. When omitted, update the global diagnostic options. disable({bufnr}, {namespace}) *vim.diagnostic.disable()* Disable diagnostics in the given buffer. Parameters: ~ - {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. When omitted, disable diagnostics in all buffers. - {namespace} (number|nil) Only disable diagnostics for the given + • {namespace} (number|nil) Only disable diagnostics for the given namespace. enable({bufnr}, {namespace}) *vim.diagnostic.enable()* Enable diagnostics in the given buffer. Parameters: ~ - {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. When omitted, enable diagnostics in all buffers. - {namespace} (number|nil) Only enable diagnostics for the given + • {namespace} (number|nil) 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) A list of quickfix items from |getqflist()| or + • {list} (table) A list of quickfix items from |getqflist()| or |getloclist()|. Return: ~ @@ -424,9 +432,9 @@ get({bufnr}, {opts}) *vim.diagnostic.get()* Get current diagnostics. Parameters: ~ - {bufnr} (number|nil) Buffer number to get diagnostics from. Use 0 for + • {bufnr} (number|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: + • {opts} (table|nil) A table with the following keys: • namespace: (number) Limit diagnostics to the given namespace. • lnum: (number) Limit diagnostics to the given line number. @@ -439,7 +447,7 @@ get_namespace({namespace}) *vim.diagnostic.get_namespace()* Get namespace metadata. Parameters: ~ - {namespace} (number) Diagnostic namespace + • {namespace} (number) Diagnostic namespace Return: ~ (table) Namespace metadata @@ -454,7 +462,7 @@ get_next({opts}) *vim.diagnostic.get_next()* Get the next diagnostic closest to the cursor position. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table) See |vim.diagnostic.goto_next()| Return: ~ (table) Next diagnostic @@ -463,7 +471,7 @@ get_next_pos({opts}) *vim.diagnostic.get_next_pos()* Return the position of the next diagnostic in the current buffer. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table) See |vim.diagnostic.goto_next()| Return: ~ (table) Next diagnostic position as a (row, col) tuple. @@ -472,7 +480,7 @@ get_prev({opts}) *vim.diagnostic.get_prev()* Get the previous diagnostic closest to the cursor position. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table) See |vim.diagnostic.goto_next()| Return: ~ (table) Previous diagnostic @@ -481,7 +489,7 @@ get_prev_pos({opts}) *vim.diagnostic.get_prev_pos()* Return the position of the previous diagnostic in the current buffer. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table) See |vim.diagnostic.goto_next()| Return: ~ (table) Previous diagnostic position as a (row, col) tuple. @@ -490,7 +498,7 @@ goto_next({opts}) *vim.diagnostic.goto_next()* Move to the next diagnostic. Parameters: ~ - {opts} (table|nil) Configuration table with the following keys: + • {opts} (table|nil) Configuration table with the following keys: • namespace: (number) Only consider diagnostics from the given namespace. • cursor_position: (cursor position) Cursor position as a @@ -511,7 +519,7 @@ goto_prev({opts}) *vim.diagnostic.goto_prev()* Move to the previous diagnostic in the current buffer. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table) See |vim.diagnostic.goto_next()| hide({namespace}, {bufnr}) *vim.diagnostic.hide()* Hide currently displayed diagnostics. @@ -524,9 +532,9 @@ hide({namespace}, {bufnr}) *vim.diagnostic.hide()* |vim.diagnostic.disable()|. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, hide + • {namespace} (number|nil) Diagnostic namespace. When omitted, hide diagnostics from all namespaces. - {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. When omitted, hide diagnostics in all buffers. *vim.diagnostic.match()* @@ -547,13 +555,13 @@ 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 + • {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 + • {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|nil) Table of default values for any fields not listed in {groups}. When omitted, numeric values default to 0 and "severity" defaults to ERROR. @@ -565,7 +573,7 @@ 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|nil) 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. @@ -623,27 +631,27 @@ reset({namespace}, {bufnr}) *vim.diagnostic.reset()* re-displayed, use |vim.diagnostic.hide()|. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, remove + • {namespace} (number|nil) Diagnostic namespace. When omitted, remove diagnostics from all namespaces. - {bufnr} (number|nil) Remove diagnostics for the given buffer. + • {bufnr} (number|nil) 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} (number) The diagnostic namespace - {bufnr} (number) Buffer number - {diagnostics} (table) A list of diagnostic items + • {namespace} (number) The diagnostic namespace + • {bufnr} (number) Buffer number + • {diagnostics} (table) A list of diagnostic items |diagnostic-structure| - {opts} (table|nil) Display options to pass to + • {opts} (table|nil) 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|nil) Configuration table with the following keys: • namespace: (number) Only add diagnostics from the given namespace. • winnr: (number, default 0) Window number to set location @@ -658,7 +666,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|nil) Configuration table with the following keys: • namespace: (number) Only add diagnostics from the given namespace. • open: (boolean, default true) Open quickfix list after @@ -672,17 +680,17 @@ show({namespace}, {bufnr}, {diagnostics}, {opts}) Display diagnostics for the given namespace and buffer. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, show + • {namespace} (number|nil) Diagnostic namespace. When omitted, show diagnostics from all namespaces. - {bufnr} (number|nil) Buffer number, or 0 for current buffer. + • {bufnr} (number|nil) 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|nil) 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|nil) Display options. See |vim.diagnostic.config()|. toqflist({diagnostics}) *vim.diagnostic.toqflist()* @@ -690,7 +698,7 @@ 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: ~ array of quickfix list items |setqflist-what| diff --git a/runtime/doc/editing.txt b/runtime/doc/editing.txt index dcb0bf8a2e..21a30ca429 100644 --- a/runtime/doc/editing.txt +++ b/runtime/doc/editing.txt @@ -941,7 +941,7 @@ WRITING WITH MULTIPLE BUFFERS *buffer-write* Vim will warn you if you try to overwrite a file that has been changed -elsewhere. See |timestamp|. +elsewhere (unless "!" was used). See |timestamp|. *backup* *E207* *E506* *E507* *E508* *E509* *E510* If you write to an existing file (but do not append) while the 'backup', @@ -1481,8 +1481,8 @@ doing something there and closing it should be OK (if there are no side effects from other autocommands). Closing unrelated windows and buffers will get you into trouble. -Before writing a file the timestamp is checked. If it has changed, Vim will -ask if you really want to overwrite the file: +Before writing a file, the timestamp is checked (unless "!" was used). +If it has changed, Vim will ask if you really want to overwrite the file: WARNING: The file has been changed since reading it!!! Do you really want to write to it (y/n)? diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt index 376adfec7f..6a9fb6d03c 100644 --- a/runtime/doc/eval.txt +++ b/runtime/doc/eval.txt @@ -40,7 +40,7 @@ List An ordered sequence of items, see |List| for details. Dictionary An associative, unordered array: Each entry has a key and a value. |Dictionary| Examples: - {'blue': "#0000ff", 'red': "#ff0000"} + {"blue": "#0000ff", "red": "#ff0000"} #{blue: "#0000ff", red: "#ff0000"} Blob Binary Large Object. Stores any sequence of bytes. See |Blob| @@ -457,7 +457,7 @@ String automatically. Thus the String '4' and the number 4 will find the same entry. Note that the String '04' and the Number 04 are different, since the Number will be converted to the String '4', leading zeros are dropped. The empty string can also be used as a key. - *literal-Dict* + *literal-Dict* *#{}* To avoid having to put quotes around every key the #{} form can be used. This does require the key to consist only of ASCII letters, digits, '-' and '_'. Example: > @@ -681,7 +681,7 @@ similar to -1. > :let shortblob = myblob[2:2] " Blob with one byte: 0z22 :let otherblob = myblob[:] " make a copy of the Blob -If the first index is beyond the last byte of the Blob or the second byte is +If the first index is beyond the last byte of the Blob or the second index is before the first index, the result is an empty Blob. There is no error message. @@ -704,8 +704,8 @@ The length of the replaced bytes must be exactly the same as the value provided. *E972* To change part of a blob you can specify the first and last byte to be -modified. The value must at least have the number of bytes in the range: > - :let blob[3:5] = [3, 4, 5] +modified. The value must have the same number of bytes in the range: > + :let blob[3:5] = 0z334455 You can also use the functions |add()|, |remove()| and |insert()|. @@ -1228,7 +1228,10 @@ And NOT: > \ ->map(mapexpr) \ ->sort() \ ->join() -< + +When using the lambda form there must be no white space between the } and the +(. + *expr9* number @@ -2309,397 +2312,10 @@ help file: |builtin-functions|. 5. Defining functions *user-function* New functions can be defined. These can be called just like builtin -functions. The function executes a sequence of Ex commands. Normal mode -commands can be executed with the |:normal| command. - -The function name must start with an uppercase letter, to avoid confusion with -builtin functions. To prevent from using the same name in different scripts -avoid obvious, short names. A good habit is to start the function name with -the name of the script, e.g., "HTMLcolor()". - -It's also possible to use curly braces, see |curly-braces-names|. And the -|autoload| facility is useful to define a function only when it's called. - - *local-function* -A function local to a script must start with "s:". A local script function -can only be called from within the script and from functions, user commands -and autocommands defined in the script. It is also possible to call the -function from a mapping defined in the script, but then |<SID>| must be used -instead of "s:" when the mapping is expanded outside of the script. -There are only script-local functions, no buffer-local or window-local -functions. - - *:fu* *:function* *E128* *E129* *E123* -:fu[nction] List all functions and their arguments. - -:fu[nction][!] {name} List function {name}, annotated with line numbers - unless "!" is given. - {name} may be a |Dictionary| |Funcref| entry: > - :function dict.init - -:fu[nction] /{pattern} List functions with a name matching {pattern}. - Example that lists all functions ending with "File": > - :function /File$ -< - *:function-verbose* -When 'verbose' is non-zero, listing a function will also display where it was -last defined. Example: > - - :verbose function SetFileTypeSH - function SetFileTypeSH(name) - Last set from /usr/share/vim/vim-7.0/filetype.vim -< -See |:verbose-cmd| for more information. - - *E124* *E125* *E853* *E884* -:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure] - Define a new function by the name {name}. The body of - the function follows in the next lines, until the - matching |:endfunction|. - - The name must be made of alphanumeric characters and - '_', and must start with a capital or "s:" (see - above). Note that using "b:" or "g:" is not allowed. - (since patch 7.4.260 E884 is given if the function - name has a colon in the name, e.g. for "foo:bar()". - Before that patch no error was given). - - {name} can also be a |Dictionary| entry that is a - |Funcref|: > - :function dict.init(arg) -< "dict" must be an existing dictionary. The entry - "init" is added if it didn't exist yet. Otherwise [!] - is required to overwrite an existing function. The - result is a |Funcref| to a numbered function. The - function can only be used with a |Funcref| and will be - deleted if there are no more references to it. - *E127* *E122* - When a function by this name already exists and [!] is - not used an error message is given. There is one - exception: When sourcing a script again, a function - that was previously defined in that script will be - silently replaced. - When [!] is used, an existing function is silently - replaced. Unless it is currently being executed, that - is an error. - NOTE: Use ! wisely. If used without care it can cause - an existing function to be replaced unexpectedly, - which is hard to debug. - - For the {arguments} see |function-argument|. - - *:func-range* *a:firstline* *a:lastline* - When the [range] argument is added, the function is - expected to take care of a range itself. The range is - passed as "a:firstline" and "a:lastline". If [range] - is excluded, ":{range}call" will call the function for - each line in the range, with the cursor on the start - of each line. See |function-range-example|. - The cursor is still moved to the first line of the - range, as is the case with all Ex commands. - *:func-abort* - When the [abort] argument is added, the function will - abort as soon as an error is detected. - *:func-dict* - When the [dict] argument is added, the function must - be invoked through an entry in a |Dictionary|. The - local variable "self" will then be set to the - dictionary. See |Dictionary-function|. - *:func-closure* *E932* - When the [closure] argument is added, the function - can access variables and arguments from the outer - scope. This is usually called a closure. In this - example Bar() uses "x" from the scope of Foo(). It - remains referenced even after Foo() returns: > - :function! Foo() - : let x = 0 - : function! Bar() closure - : let x += 1 - : return x - : endfunction - : return funcref('Bar') - :endfunction - - :let F = Foo() - :echo F() -< 1 > - :echo F() -< 2 > - :echo F() -< 3 - - *function-search-undo* - The last used search pattern and the redo command "." - will not be changed by the function. This also - implies that the effect of |:nohlsearch| is undone - when the function returns. - - *:endf* *:endfunction* *E126* *E193* *W22* -:endf[unction] [argument] - The end of a function definition. Best is to put it - on a line by its own, without [argument]. - - [argument] can be: - | command command to execute next - \n command command to execute next - " comment always ignored - anything else ignored, warning given when - 'verbose' is non-zero - The support for a following command was added in Vim - 8.0.0654, before that any argument was silently - ignored. - - To be able to define a function inside an `:execute` - command, use line breaks instead of |:bar|: > - :exe "func Foo()\necho 'foo'\nendfunc" -< - *:delf* *:delfunction* *E131* *E933* -:delf[unction][!] {name} - Delete function {name}. - {name} can also be a |Dictionary| entry that is a - |Funcref|: > - :delfunc dict.init -< This will remove the "init" entry from "dict". The - function is deleted if there are no more references to - it. - With the ! there is no error if the function does not - exist. - *:retu* *:return* *E133* -:retu[rn] [expr] Return from a function. When "[expr]" is given, it is - evaluated and returned as the result of the function. - If "[expr]" is not given, the number 0 is returned. - When a function ends without an explicit ":return", - the number 0 is returned. - Note that there is no check for unreachable lines, - thus there is no warning if commands follow ":return". - - If the ":return" is used after a |:try| but before the - matching |:finally| (if present), the commands - following the ":finally" up to the matching |:endtry| - are executed first. This process applies to all - nested ":try"s inside the function. The function - returns at the outermost ":endtry". - - *function-argument* *a:var* -An argument can be defined by giving its name. In the function this can then -be used as "a:name" ("a:" for argument). - *a:0* *a:1* *a:000* *E740* *...* -Up to 20 arguments can be given, separated by commas. After the named -arguments an argument "..." can be specified, which means that more arguments -may optionally be following. In the function the extra arguments can be used -as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which -can be 0). "a:000" is set to a |List| that contains these arguments. Note -that "a:1" is the same as "a:000[0]". - *E742* -The a: scope and the variables in it cannot be changed, they are fixed. -However, if a composite type is used, such as |List| or |Dictionary| , you can -change their contents. Thus you can pass a |List| to a function and have the -function add an item to it. If you want to make sure the function cannot -change a |List| or |Dictionary| use |:lockvar|. - -It is also possible to define a function without any arguments. You must -still supply the () then. - -It is allowed to define another function inside a function body. - - *optional-function-argument* -You can provide default values for positional named arguments. This makes -them optional for function calls. When a positional argument is not -specified at a call, the default expression is used to initialize it. -This only works for functions declared with |function|, not for -lambda expressions |expr-lambda|. - -Example: > - function Something(key, value = 10) - echo a:key .. ": " .. a:value - endfunction - call Something('empty') "empty: 10" - call Something('key', 20) "key: 20" - -The argument default expressions are evaluated at the time of the function -call, not definition. Thus it is possible to use an expression which is -invalid the moment the function is defined. The expressions are also only -evaluated when arguments are not specified during a call. - - *E989* -Optional arguments with default expressions must occur after any mandatory -arguments. You can use "..." after all optional named arguments. - -It is possible for later argument defaults to refer to prior arguments, -but not the other way around. They must be prefixed with "a:", as with all -arguments. - -Example that works: > - :function Okay(mandatory, optional = a:mandatory) - :endfunction -Example that does NOT work: > - :function NoGood(first = a:second, second = 10) - :endfunction -< -When not using "...", the number of arguments in a function call must be at -least equal to the number of mandatory named arguments. When using "...", the -number of arguments may be larger than the total of mandatory and optional -arguments. - - *local-variables* -Inside a function local variables can be used. These will disappear when the -function returns. Global variables need to be accessed with "g:". - -Example: > - :function Table(title, ...) - : echohl Title - : echo a:title - : echohl None - : echo a:0 .. " items:" - : for s in a:000 - : echon ' ' .. s - : endfor - :endfunction - -This function can then be called with: > - call Table("Table", "line1", "line2") - call Table("Empty Table") - -To return more than one value, return a |List|: > - :function Compute(n1, n2) - : if a:n2 == 0 - : return ["fail", 0] - : endif - : return ["ok", a:n1 / a:n2] - :endfunction - -This function can then be called with: > - :let [success, div] = Compute(102, 6) - :if success == "ok" - : echo div - :endif -< - *:cal* *:call* *E107* *E117* -:[range]cal[l] {name}([arguments]) - Call a function. The name of the function and its arguments - are as specified with `:function`. Up to 20 arguments can be - used. The returned value is discarded. - Without a range and for functions that accept a range, the - function is called once. When a range is given the cursor is - positioned at the start of the first line before executing the - function. - When a range is given and the function doesn't handle it - itself, the function is executed for each line in the range, - with the cursor in the first column of that line. The cursor - is left at the last line (possibly moved by the last function - call). The arguments are re-evaluated for each line. Thus - this works: - *function-range-example* > - :function Mynumber(arg) - : echo line(".") .. " " .. a:arg - :endfunction - :1,5call Mynumber(getline(".")) -< - The "a:firstline" and "a:lastline" are defined anyway, they - can be used to do something different at the start or end of - the range. - - Example of a function that handles the range itself: > - - :function Cont() range - : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ ' - :endfunction - :4,8call Cont() -< - This function inserts the continuation character "\" in front - of all the lines in the range, except the first one. - - When the function returns a composite value it can be further - dereferenced, but the range will not be used then. Example: > - :4,8call GetDict().method() -< Here GetDict() gets the range but method() does not. - - *E132* -The recursiveness of user functions is restricted with the |'maxfuncdepth'| -option. +functions. The function takes arguments, executes a sequence of Ex commands +and can return a value. -It is also possible to use `:eval`. It does not support a range, but does -allow for method chaining, e.g.: > - eval GetList()->Filter()->append('$') - - -AUTOMATICALLY LOADING FUNCTIONS ~ - *autoload-functions* -When using many or large functions, it's possible to automatically define them -only when they are used. There are two methods: with an autocommand and with -the "autoload" directory in 'runtimepath'. - - -Using an autocommand ~ - -This is introduced in the user manual, section |41.14|. - -The autocommand is useful if you have a plugin that is a long Vim script file. -You can define the autocommand and quickly quit the script with `:finish`. -That makes Vim startup faster. The autocommand should then load the same file -again, setting a variable to skip the `:finish` command. - -Use the FuncUndefined autocommand event with a pattern that matches the -function(s) to be defined. Example: > - - :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim - -The file "~/vim/bufnetfuncs.vim" should then define functions that start with -"BufNet". Also see |FuncUndefined|. - - -Using an autoload script ~ - *autoload* *E746* -This is introduced in the user manual, section |41.15|. - -Using a script in the "autoload" directory is simpler, but requires using -exactly the right file name. A function that can be autoloaded has a name -like this: > - - :call filename#funcname() - -When such a function is called, and it is not defined yet, Vim will search the -"autoload" directories in 'runtimepath' for a script file called -"filename.vim". For example "~/.config/nvim/autoload/filename.vim". That -file should then define the function like this: > - - function filename#funcname() - echo "Done!" - endfunction - -The file name and the name used before the # in the function must match -exactly, and the defined function must have the name exactly as it will be -called. - -It is possible to use subdirectories. Every # in the function name works like -a path separator. Thus when calling a function: > - - :call foo#bar#func() - -Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'. - -This also works when reading a variable that has not been set yet: > - - :let l = foo#bar#lvar - -However, when the autoload script was already loaded it won't be loaded again -for an unknown variable. - -When assigning a value to such a variable nothing special happens. This can -be used to pass settings to the autoload script before it's loaded: > - - :let foo#bar#toggle = 1 - :call foo#bar#func() - -Note that when you make a mistake and call a function that is supposed to be -defined in an autoload script, but the script doesn't actually define the -function, you will get an error message for the missing function. If you fix -the autoload script it won't be automatically loaded again. Either restart -Vim or manually source the script. - -Also note that if you have two script files, and one calls a function in the -other and vice versa, before the used function is defined, it won't work. -Avoid using the autoload functionality at the toplevel. +You can find most information about defining functions in |userfunc.txt|. ============================================================================== 6. Curly braces names *curly-braces-names* @@ -2915,7 +2531,7 @@ text... echo 'done' endif END -< Results in: ["if ok", " echo 'done'", "endif"] +< Results in: `["if ok", " echo 'done'", "endif"]` The marker must line up with "let" and the indentation of the first line is removed from all the text lines. Specifically: all the leading indentation exactly @@ -3167,6 +2783,9 @@ text... iterate over. Unlike with |List|, modifying the |Blob| does not affect the iteration. + When {object} is a |String| each item is a string with + one character, plus any combining characters. + :for [{var1}, {var2}, ...] in {listlist} :endfo[r] Like `:for` above, but each item in {listlist} must be @@ -4500,7 +4119,7 @@ This example sorts lines with a specific compare function. > As a one-liner: > :call setline(1, sort(getline(1, '$'), function("Strcmp"))) - +< scanf() replacement ~ *sscanf* diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index 7fff74a963..ac54a6b6ca 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -178,7 +178,7 @@ If a file type that you want to use is not detected yet, there are a few ways to add it. In any way, it's better not to modify the $VIMRUNTIME/filetype.lua or $VIMRUNTIME/filetype.vim files. They will be overwritten when installing a new version of Nvim. The following explains the legacy Vim mechanism (enabled -if |do_legacy_filetype| is set). For Nvim's default mechanism, see +if |g:do_legacy_filetype| is set). For Nvim's default mechanism, see |vim.filetype.add()|. A. If you want to overrule all default file type checks. @@ -586,12 +586,12 @@ Local mappings: to the end of the file in Normal mode. This means "> " is inserted in each line. -MAN *ft-man-plugin* *:Man* *man.vim* +MAN *ft-man-plugin* *:Man* *man.lua* View manpages in Nvim. Supports highlighting, completion, locales, and navigation. Also see |find-manpage|. -man.vim will always attempt to reuse the closest man window (above/left) but +man.lua will always attempt to reuse the closest man window (above/left) but otherwise create a split. The case sensitivity of completion is controlled by 'fileignorecase'. diff --git a/runtime/doc/fold.txt b/runtime/doc/fold.txt index 9e3d78faff..e97a0a6459 100644 --- a/runtime/doc/fold.txt +++ b/runtime/doc/fold.txt @@ -491,7 +491,7 @@ is evaluated to obtain the text displayed for a closed fold. Example: > This shows the first line of the fold, with "/*", "*/" and "{{{" removed. Note the use of backslashes to avoid some characters to be interpreted by the -":set" command. It's simpler to define a function and call that: > +":set" command. It is much simpler to define a function and call it: > :set foldtext=MyFoldText() :function MyFoldText() diff --git a/runtime/doc/ft_ada.txt b/runtime/doc/ft_ada.txt index f6dfa708fb..e4ac37a86e 100644 --- a/runtime/doc/ft_ada.txt +++ b/runtime/doc/ft_ada.txt @@ -51,7 +51,7 @@ for a complete list. To enable them, assign a value to the option. For example, to turn one on: > > let g:ada_standard_types = 1 -> + To disable them use ":unlet". Example: > > unlet g:ada_standard_types @@ -288,7 +288,7 @@ g:ada_rainbow_color bool (true when exists) rainbow_parenthesis for this to work. *g:ada_folding* -g:ada_folding set ('sigpft') +g:ada_folding set ("sigpft") Use folding for Ada sources. 's': activate syntax folding on load 'p': fold packages @@ -296,10 +296,10 @@ g:ada_folding set ('sigpft') 't': fold types 'c': fold conditionals 'g': activate gnat pretty print folding on load - 'i': lone 'is' folded with line above - 'b': lone 'begin' folded with line above - 'p': lone 'private' folded with line above - 'x': lone 'exception' folded with line above + 'i': lone "is" folded with line above + 'b': lone "begin" folded with line above + 'p': lone "private" folded with line above + 'x': lone "exception" folded with line above 'i': activate indent folding on load Note: Syntax folding is in an early (unusable) stage and @@ -334,10 +334,10 @@ g:ada_omni_with_keywords completion (|i_CTRL-X_CTRL-U|). *g:ada_extended_tagging* -g:ada_extended_tagging enum ('jump', 'list') +g:ada_extended_tagging enum ("jump", "list") use extended tagging, two options are available - 'jump': use tjump to jump. - 'list': add tags quick fix list. + "jump": use tjump to jump. + "list": add tags quick fix list. Normal tagging does not support function or operator overloading as these features are not available in C and tagging was originally developed for C. @@ -359,8 +359,8 @@ g:ada_with_gnat_project_files bool (true when exists) *g:ada_default_compiler* g:ada_default_compiler string - set default compiler. Currently supported are 'gnat' and - 'decada'. + set default compiler. Currently supported are "gnat" and + "decada". An "exists" type is a boolean considered true when the variable is defined and false when the variable is undefined. The value to which the variable is set @@ -406,14 +406,14 @@ makes no difference. g:gnat object Control object which manages GNAT compiles. The object is created when the first Ada source code is loaded provided - that |g:ada_default_compiler| is set to 'gnat'. See + that |g:ada_default_compiler| is set to "gnat". See |gnat_members| for details. *g:decada* g:decada object Control object which manages Dec Ada compiles. The object is created when the first Ada source code is loaded provided - that |g:ada_default_compiler| is set to 'decada'. See + that |g:ada_default_compiler| is set to "decada". See |decada_members| for details. ------------------------------------------------------------------------------ @@ -459,11 +459,11 @@ ada#List_Tag([{line}, {col}]) *ada#Listtags()* ada#Jump_Tag ({ident}, {mode}) *ada#Jump_Tag()* List all occurrences of the Ada entity under the cursor (or at given line/column) in the tag jump list. Mode can either be - 'tjump' or 'stjump'. + "tjump" or "stjump". ada#Create_Tags ({option}) *ada#Create_Tags()* - Creates tag file using Ctags. The option can either be 'file' - for the current file, 'dir' for the directory of the current + Creates tag file using Ctags. The option can either be "file" + for the current file, "dir" for the directory of the current file or a file name. gnat#Insert_Tags_Header() *gnat#Insert_Tags_Header()* @@ -489,7 +489,7 @@ backup.vim http://www.vim.org/scripts/script.php?script_id=1537 Keeps as many backups as you like so you don't have to. -rainbow_parenthsis.vim +rainbow_parenthesis.vim http://www.vim.org/scripts/script.php?script_id=1561 Very helpful since Ada uses only '(' and ')'. diff --git a/runtime/doc/ft_rust.txt b/runtime/doc/ft_rust.txt index 5c8782ec7a..3a0bf2293e 100644 --- a/runtime/doc/ft_rust.txt +++ b/runtime/doc/ft_rust.txt @@ -92,8 +92,8 @@ g:ftplugin_rust_source_path~ *g:rustfmt_command* g:rustfmt_command~ - Set this option to the name of the 'rustfmt' executable in your $PATH. If - not specified it defaults to 'rustfmt' : > + Set this option to the name of the "rustfmt" executable in your $PATH. If + not specified it defaults to "rustfmt" : > let g:rustfmt_command = 'rustfmt' < *g:rustfmt_autosave* @@ -104,14 +104,14 @@ g:rustfmt_autosave~ < *g:rustfmt_fail_silently* g:rustfmt_fail_silently~ - Set this option to 1 to prevent 'rustfmt' from populating the + Set this option to 1 to prevent "rustfmt" from populating the |location-list| with errors. If not specified it defaults to 0: > let g:rustfmt_fail_silently = 0 < *g:rustfmt_options* g:rustfmt_options~ - Set this option to a string of options to pass to 'rustfmt'. The - write-mode is already set to 'overwrite'. If not specified it + Set this option to a string of options to pass to "rustfmt". The + write-mode is already set to "overwrite". If not specified it defaults to '' : > let g:rustfmt_options = '' < diff --git a/runtime/doc/ft_sql.txt b/runtime/doc/ft_sql.txt index 335faf266e..03d9082aab 100644 --- a/runtime/doc/ft_sql.txt +++ b/runtime/doc/ft_sql.txt @@ -244,7 +244,7 @@ key to complete the optional parameter. After typing the function name and a space, you can use the completion to supply a parameter. The function takes the name of the Vim script you want to source. Using the |cmdline-completion| feature, the SQLSetType function will -search the |'runtimepath'| for all Vim scripts with a name containing 'sql'. +search the |'runtimepath'| for all Vim scripts with a name containing "sql". This takes the guess work out of the spelling of the names. The following are examples: > :SQLSetType @@ -757,7 +757,7 @@ the syntax items for Perl. Step 2 ------ -Manually setting the filetype to 'sql' will also fire the appropriate filetype +Manually setting the filetype to "sql" will also fire the appropriate filetype files ftplugin/sql.vim. This file will define a number of buffer specific maps for SQL completion, see |sql-completion-maps|. Now these maps have been created and the SQL completion plugin has been initialized. All SQL diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt index 04e31e0680..a1bedfa500 100644 --- a/runtime/doc/help.txt +++ b/runtime/doc/help.txt @@ -98,7 +98,6 @@ General subjects ~ |help.txt| overview and quick reference (this file) |helphelp.txt| about using the help files |index.txt| alphabetical index of all commands -|help-tags| all the tags you can jump to (index of tags) |tips.txt| various tips on using Vim |message.txt| (error) messages and explanations |develop.txt| development of Nvim @@ -131,6 +130,7 @@ Advanced editing ~ |autocmd.txt| automatically executing commands on an event |eval.txt| expression evaluation, conditional commands |builtin.txt| builtin functions +|userfunc.txt| defining user functions |fold.txt| hide (fold) ranges of lines |lua.txt| Lua API |api.txt| Nvim API via RPC, Lua and VimL diff --git a/runtime/doc/helphelp.txt b/runtime/doc/helphelp.txt index 569995d319..4758cd37c6 100644 --- a/runtime/doc/helphelp.txt +++ b/runtime/doc/helphelp.txt @@ -212,12 +212,6 @@ This is done when viewing the file in Vim, the file itself is not changed. It is done by going through all help files and obtaining the first line of each file. The files in $VIMRUNTIME/doc are skipped. - *help-xterm-window* -If you want to have the help in another xterm window, you could use this -command: > - :!xterm -e vim +help & -< - *:helpt* *:helptags* *E150* *E151* *E152* *E153* *E154* *E670* *E856* :helpt[ags] [++t] {dir} @@ -372,6 +366,7 @@ To separate sections in a help file, place a series of '=' characters in a line starting from the first column. The section separator line is highlighted differently. + *help-codeblock* To quote a block of ex-commands verbatim, place a greater than (>) character at the end of the line before the block and a less than (<) character as the first non-blank on a line following the block. Any line starting in column 1 diff --git a/runtime/doc/indent.txt b/runtime/doc/indent.txt index 1a1d8e30b0..c5411b5f16 100644 --- a/runtime/doc/indent.txt +++ b/runtime/doc/indent.txt @@ -979,25 +979,38 @@ indentation: > PYTHON *ft-python-indent* The amount of indent can be set for the following situations. The examples -given are the defaults. Note that the variables are set to an expression, so -that you can change the value of 'shiftwidth' later. +given are the defaults. Note that the dictionary values are set to an +expression, so that you can change the value of 'shiftwidth' later. Indent after an open paren: > - let g:pyindent_open_paren = 'shiftwidth() * 2' + let g:python_indent.open_paren = 'shiftwidth() * 2' Indent after a nested paren: > - let g:pyindent_nested_paren = 'shiftwidth()' + let g:python_indent.nested_paren = 'shiftwidth()' Indent for a continuation line: > - let g:pyindent_continue = 'shiftwidth() * 2' + let g:python_indent.continue = 'shiftwidth() * 2' + +By default, the closing paren on a multiline construct lines up under the first +non-whitespace character of the previous line. +If you prefer that it's lined up under the first character of the line that +starts the multiline construct, reset this key: > + let g:python_indent.closed_paren_align_last_line = v:false The method uses |searchpair()| to look back for unclosed parentheses. This can sometimes be slow, thus it timeouts after 150 msec. If you notice the indenting isn't correct, you can set a larger timeout in msec: > - let g:pyindent_searchpair_timeout = 500 + let g:python_indent.searchpair_timeout = 500 If looking back for unclosed parenthesis is still too slow, especially during a copy-paste operation, or if you don't need indenting inside multi-line parentheses, you can completely disable this feature: > - let g:pyindent_disable_parentheses_indenting = 1 + let g:python_indent.disable_parentheses_indenting = 1 + +For backward compatibility, these variables are also supported: > + g:pyindent_open_paren + g:pyindent_nested_paren + g:pyindent_continue + g:pyindent_searchpair_timeout + g:pyindent_disable_parentheses_indenting R *ft-r-indent* diff --git a/runtime/doc/index.txt b/runtime/doc/index.txt index 7f3ef20762..7318bc7f34 100644 --- a/runtime/doc/index.txt +++ b/runtime/doc/index.txt @@ -13,7 +13,6 @@ to look for deleting something, use: "/delete". For an overview of options see |option-list|. For an overview of built-in functions see |functions|. For a list of Vim variables see |vim-variable|. -For a complete listing of all help items see |help-tags|. Type |gO| to see the table of contents. @@ -22,6 +21,7 @@ For a complete listing of all help items see |help-tags|. tag char action in Insert mode ~ ----------------------------------------------------------------------- + |i_CTRL-@| CTRL-@ insert previously inserted text and stop insert |i_CTRL-A| CTRL-A insert previously inserted text @@ -61,7 +61,7 @@ tag char action in Insert mode ~ |i_CTRL-Q| CTRL-Q same as CTRL-V, unless used for terminal control flow |i_CTRL-SHIFT-Q| CTRL-SHIFT-Q {char} - like CTRL-Q unless |modifyOtherKeys| is active + like CTRL-Q unless |tui-modifyOtherKeys| is active |i_CTRL-R| CTRL-R {register} insert the contents of a register |i_CTRL-R_CTRL-R| CTRL-R CTRL-R {register} @@ -79,7 +79,7 @@ tag char action in Insert mode ~ line |i_CTRL-V| CTRL-V {char} insert next non-digit literally |i_CTRL-SHIFT-V| CTRL-SHIFT-V {char} - like CTRL-V unless |modifyOtherKeys| is active + like CTRL-V unless |tui-modifyOtherKeys| is active |i_CTRL-V_digit| CTRL-V {number} insert three digit decimal number as a single byte. |i_CTRL-W| CTRL-W delete word before the cursor @@ -185,6 +185,7 @@ note: 1 = cursor movement command; 2 = can be undone/redone tag char note action in Normal mode ~ ------------------------------------------------------------------------------ + CTRL-@ not used |CTRL-A| CTRL-A 2 add N to number at/after cursor |CTRL-B| CTRL-B 1 scroll N screens Backwards @@ -454,14 +455,14 @@ tag char note action in Normal mode ~ |<S-Up>| <S-Up> 1 same as CTRL-B |<Undo>| <Undo> 2 same as "u" |<Up>| <Up> 1 same as "k" -|<ScrollWheelDown>| <ScrollWheelDown> move window three lines down -|<S-ScrollWheelDown>| <S-ScrollWheelDown> move window one page down -|<ScrollWheelUp>| <ScrollWheelUp> move window three lines up -|<S-ScrollWheelUp>| <S-ScrollWheelUp> move window one page up -|<ScrollWheelLeft>| <ScrollWheelLeft> move window six columns left -|<S-ScrollWheelLeft>| <S-ScrollWheelLeft> move window one page left -|<ScrollWheelRight>| <ScrollWheelRight> move window six columns right -|<S-ScrollWheelRight>| <S-ScrollWheelRight> move window one page right +*<ScrollWheelDown>* <ScrollWheelDown> move window three lines down +*<S-ScrollWheelDown>* <S-ScrollWheelDown> move window one page down +*<ScrollWheelUp>* <ScrollWheelUp> move window three lines up +*<S-ScrollWheelUp>* <S-ScrollWheelUp> move window one page up +*<ScrollWheelLeft>* <ScrollWheelLeft> move window six columns left +*<S-ScrollWheelLeft>* <S-ScrollWheelLeft> move window one page left +*<ScrollWheelRight>* <ScrollWheelRight> move window six columns right +*<S-ScrollWheelRight>* <S-ScrollWheelRight> move window one page right ============================================================================== 2.1 Text objects *objects* @@ -470,6 +471,7 @@ These can be used after an operator or in Visual mode to select an object. tag command action in op-pending and Visual mode ~ ------------------------------------------------------------------------------ + |v_aquote| a" double quoted string |v_a'| a' single quoted string |v_a(| a( same as ab @@ -512,6 +514,7 @@ tag command action in op-pending and Visual mode ~ tag command action in Normal mode ~ ------------------------------------------------------------------------------ + |CTRL-W_CTRL-B| CTRL-W CTRL-B same as "CTRL-W b" |CTRL-W_CTRL-C| CTRL-W CTRL-C same as "CTRL-W c" |CTRL-W_CTRL-D| CTRL-W CTRL-D same as "CTRL-W d" @@ -610,6 +613,7 @@ tag command action in Normal mode ~ tag char note action in Normal mode ~ ------------------------------------------------------------------------------ + |[_CTRL-D| [ CTRL-D jump to first #define found in current and included files matching the word under the cursor, start searching at beginning of @@ -700,7 +704,8 @@ tag char note action in Normal mode ~ tag char note action in Normal mode ~ ------------------------------------------------------------------------------ -|g_CTRL-A| g CTRL-A dump a memory profile + +g_CTRL-A g CTRL-A dump a memory profile |g_CTRL-G| g CTRL-G show information about current cursor position |g_CTRL-H| g CTRL-H start Select block mode @@ -803,6 +808,7 @@ tag char note action in Normal mode ~ tag char note action in Normal mode ~ ------------------------------------------------------------------------------ + |z<CR>| z<CR> redraw, cursor line to top of window, cursor on first non-blank |zN<CR>| z{height}<CR> redraw, make window {height} lines high @@ -877,6 +883,7 @@ These can be used after an operator, but before a {motion} has been entered. tag char action in Operator-pending mode ~ ----------------------------------------------------------------------- + |o_v| v force operator to work charwise |o_V| V force operator to work linewise |o_CTRL-V| CTRL-V force operator to work blockwise @@ -889,6 +896,7 @@ here are those that are different. tag command note action in Visual mode ~ ------------------------------------------------------------------------------ + |v_CTRL-\_CTRL-N| CTRL-\ CTRL-N stop Visual mode |v_CTRL-\_CTRL-G| CTRL-\ CTRL-G go to Normal mode |v_CTRL-A| CTRL-A 2 add N to number in highlighted text @@ -1009,6 +1017,7 @@ file names, tags, commands etc. as appropriate. tag command action in Command-line editing mode ~ ------------------------------------------------------------------------------ + CTRL-@ not used |c_CTRL-A| CTRL-A do completion on the pattern in front of the cursor and insert all matches @@ -1111,7 +1120,7 @@ to terminal mode. You found it, Arthur! *holy-grail* ============================================================================== -6. EX commands *ex-cmd-index* *:index* +6. EX commands *ex-commands* *ex-cmd-index* *:index* This is a brief but complete listing of all the ":" commands, without mentioning any arguments. The optional part of the command name is inside []. @@ -1119,6 +1128,7 @@ The commands are sorted on the non-optional part of their name. tag command action ~ ------------------------------------------------------------------------------ + |:| : nothing |:range| :{range} go to last line in {range} |:!| :! filter lines or execute an external command diff --git a/runtime/doc/insert.txt b/runtime/doc/insert.txt index 6b0899334b..792c6ee6f4 100644 --- a/runtime/doc/insert.txt +++ b/runtime/doc/insert.txt @@ -650,9 +650,9 @@ When the popup menu is displayed there are a few more special keys, see |popupmenu-keys|. Note: The keys that are valid in CTRL-X mode are not mapped. This allows for -":map ^F ^X^F" to work (where ^F is CTRL-F and ^X is CTRL-X). The key that -ends CTRL-X mode (any key that is not a valid CTRL-X mode command) is mapped. -Also, when doing completion with 'complete' mappings apply as usual. +`:map <C-F> <C-X><C-F>` to work. The key that ends CTRL-X mode (any key that +is not a valid CTRL-X mode command) is mapped. Also, when doing completion +with 'complete' mappings apply as usual. *E565* Note: While completion is active Insert mode can't be used recursively and @@ -661,10 +661,10 @@ will generate an E565 error. The following mappings are suggested to make typing the completion commands a bit easier (although they will hide other commands): > - :inoremap ^] ^X^] - :inoremap ^F ^X^F - :inoremap ^D ^X^D - :inoremap ^L ^X^L + :inoremap <C-]> <C-X><C-]> + :inoremap <C-F> <C-X><C-F> + :inoremap <C-D> <C-X><C-D> + :inoremap <C-L> <C-X><C-L> As a special case, typing CTRL-R to perform register insertion (see |i_CTRL-R|) will not exit CTRL-X mode. This is primarily to allow the use of @@ -1126,7 +1126,8 @@ that contains the List. The Dict can have these items: leading text is changed. Other items are ignored. -For acting upon end of completion, see the |CompleteDone| autocommand event. +For acting upon end of completion, see the |CompleteDonePre| and +|CompleteDone| autocommand event. For example, the function can contain this: > let matches = ... list of words ... @@ -1519,7 +1520,7 @@ RUBY *ft-ruby-omni* NOTE: |compl-omni| for Ruby code requires |provider-ruby| to be installed. Ruby completion will parse your buffer on demand in order to provide a list of -completions. These completions will be drawn from modules loaded by 'require' +completions. These completions will be drawn from modules loaded by "require" and modules defined in the current buffer. The completions provided by CTRL-X CTRL-O are sensitive to the context: @@ -1533,7 +1534,7 @@ The completions provided by CTRL-X CTRL-O are sensitive to the context: 3. After '.', '::' or ':' Methods applicable to the object being dereferenced - 4. After ':' or ':foo' Symbol name (beginning with 'foo') + 4. After ':' or ':foo' Symbol name (beginning with "foo") Notes: - Vim will load/evaluate code in order to provide completions. This may @@ -1759,7 +1760,7 @@ In the example four special elements are visible: dialect. 2. If the list containing possible values of attributes has one element and this element is equal to the name of the attribute this attribute will be - treated as boolean and inserted as 'attrname' and not as 'attrname="' + treated as boolean and inserted as "attrname" and not as 'attrname="' 3. "vimxmltaginfo" - a special key with a Dictionary containing tag names as keys and two element List as values, for additional menu info and the long description. diff --git a/runtime/doc/intro.txt b/runtime/doc/intro.txt index ae80935032..60c2b4c5dd 100644 --- a/runtime/doc/intro.txt +++ b/runtime/doc/intro.txt @@ -308,7 +308,7 @@ These names for keys are used in the documentation. They can also be used with the ":map" command. notation meaning equivalent decimal value(s) ~ ------------------------------------------------------------------------ +----------------------------------------------------------------------- ~ <Nul> zero CTRL-@ 0 (stored as 10) *<Nul>* <BS> backspace CTRL-H 8 *backspace* <Tab> tab CTRL-I 9 *tab* *Tab* @@ -416,6 +416,10 @@ one always works. To get a literal "<lt>" in a mapping: > :map <C-L> <lt>lt> +The notation can be used in a double quoted strings, using "\<" at the start, +e.g. "\<C-Space>". This results in a special key code. To convert this back +to readable text use `keytrans()`. + ============================================================================== Modes, introduction *vim-modes-intro* *vim-modes* @@ -526,29 +530,29 @@ Ex :vi -- -- -- -- -- -- not possible -*1 Go from Normal mode to Insert mode by giving the command "i", "I", "a", - "A", "o", "O", "c", "C", "s" or S". -*2 Go from Visual mode to Normal mode by giving a non-movement command, which - causes the command to be executed, or by hitting <Esc> "v", "V" or "CTRL-V" - (see |v_v|), which just stops Visual mode without side effects. -*3 Go from Command-line mode to Normal mode by: - - Hitting <CR> or <NL>, which causes the entered command to be executed. - - Deleting the complete line (e.g., with CTRL-U) and giving a final <BS>. - - Hitting CTRL-C or <Esc>, which quits the command-line without executing - the command. - In the last case <Esc> may be the character defined with the 'wildchar' - option, in which case it will start command-line completion. You can - ignore that and type <Esc> again. -*4 Go from Normal to Select mode by: - - use the mouse to select text while 'selectmode' contains "mouse" - - use a non-printable command to move the cursor while keeping the Shift - key pressed, and the 'selectmode' option contains "key" - - use "v", "V" or "CTRL-V" while 'selectmode' contains "cmd" - - use "gh", "gH" or "g CTRL-H" |g_CTRL-H| -*5 Go from Select mode to Normal mode by using a non-printable command to move - the cursor, without keeping the Shift key pressed. -*6 Go from Select mode to Insert mode by typing a printable character. The - selection is deleted and the character is inserted. +* 1 Go from Normal mode to Insert mode by giving the command "i", "I", "a", + "A", "o", "O", "c", "C", "s" or S". +* 2 Go from Visual mode to Normal mode by giving a non-movement command, which + causes the command to be executed, or by hitting <Esc> "v", "V" or "CTRL-V" + (see |v_v|), which just stops Visual mode without side effects. +* 3 Go from Command-line mode to Normal mode by: + - Hitting <CR> or <NL>, which causes the entered command to be executed. + - Deleting the complete line (e.g., with CTRL-U) and giving a final <BS>. + - Hitting CTRL-C or <Esc>, which quits the command-line without executing + the command. + In the last case <Esc> may be the character defined with the 'wildchar' + option, in which case it will start command-line completion. You can + ignore that and type <Esc> again. +* 4 Go from Normal to Select mode by: + - use the mouse to select text while 'selectmode' contains "mouse" + - use a non-printable command to move the cursor while keeping the Shift + key pressed, and the 'selectmode' option contains "key" + - use "v", "V" or "CTRL-V" while 'selectmode' contains "cmd" + - use "gh", "gH" or "g CTRL-H" |g_CTRL-H| +* 5 Go from Select mode to Normal mode by using a non-printable command to move + the cursor, without keeping the Shift key pressed. +* 6 Go from Select mode to Insert mode by typing a printable character. The + selection is deleted and the character is inserted. *CTRL-\_CTRL-N* *i_CTRL-\_CTRL-N* *c_CTRL-\_CTRL-N* *v_CTRL-\_CTRL-N* *t_CTRL-\_CTRL-N* diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 7fc0daa0ca..139f4c6bc5 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -40,7 +40,7 @@ Follow these steps to get LSP features: root_dir = vim.fs.dirname(vim.fs.find({'setup.py', 'pyproject.toml'}, { upward = true })[1]), }) < - See |vim.lsp.start| for details. + See |vim.lsp.start()| for details. 3. Configure keymaps and autocmds to utilize LSP features. See |lsp-config|. @@ -48,19 +48,19 @@ Follow these steps to get LSP features: *lsp-config* Starting a LSP client will automatically report diagnostics via -|vim.diagnostic|. Read |vim.diagnostic.config| to learn how to customize the +|vim.diagnostic|. Read |vim.diagnostic.config()| to learn how to customize the display. It also sets some buffer options if the options are otherwise empty and if the language server supports the functionality. -- |omnifunc| is set to |vim.lsp.omnifunc|. This allows to trigger completion - using |i_CTRL-X_CTRL-o| -- |tagfunc| is set to |vim.lsp.tagfunc|. This enables features like +- 'omnifunc' is set to |vim.lsp.omnifunc()|. This allows to trigger completion + using |i_CTRL-X_CTRL-O| +- 'tagfunc' is set to |vim.lsp.tagfunc()|. This enables features like go-to-definition, |:tjump|, and keymaps like |CTRL-]|, |CTRL-W_]|, |CTRL-W_}| to utilize the language server. -- |formatexpr| is set to |vim.lsp.formatexpr| if both |formatprg| and - |formatexpr| are empty. This allows to format lines via |gq| if the language +- 'formatexpr' is set to |vim.lsp.formatexpr()| if both 'formatprg' and + 'formatexpr' are empty. This allows to format lines via |gq| if the language server supports it. To use other LSP features like hover, rename, etc. you can setup some @@ -126,13 +126,14 @@ FAQ *lsp-faq* "after/ftplugin/python.vim". - Q: How do I run a request synchronously (e.g. for formatting on file save)? - A: Use the `_sync` variant of the function provided by |lsp-buf|, if it - exists. + A: Check if the function has an `async` parameter and set the value to + false. E.g. code formatting: > " Auto-format *.rs (rust) files prior to saving them - autocmd BufWritePre *.rs lua vim.lsp.buf.formatting_sync(nil, 1000) + " (async = false is the default for format) + autocmd BufWritePre *.rs lua vim.lsp.buf.format({ async = false }) < *lsp-vs-treesitter* @@ -189,6 +190,7 @@ specification. These LSP requests/notifications are defined by default: textDocument/typeDefinition* window/logMessage window/showMessage + window/showDocument window/showMessageRequest workspace/applyEdit workspace/symbol @@ -244,7 +246,7 @@ For |lsp-request|, each |lsp-handler| has this signature: > Where `err` must be shaped like an RPC error: `{ code, message, data? }` - You can use |vim.lsp.rpc_response_error()| to create this object. + You can use |vim.lsp.rpc.rpc_response_error()| to create this object. For |lsp-notification|, each |lsp-handler| has this signature: > @@ -337,8 +339,8 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method } < Some handlers do not have an explicitly named handler function (such as - |on_publish_diagnostics()|). To override these, first create a reference - to the existing handler: > + ||vim.lsp.diagnostic.on_publish_diagnostics()|). To override these, first + create a reference to the existing handler: > local on_references = vim.lsp.handlers["textDocument/references"] vim.lsp.handlers["textDocument/references"] = vim.lsp.with( @@ -359,7 +361,7 @@ Handlers can be set by: vim.lsp.handlers["textDocument/definition"] = my_custom_default_definition < -- The {handlers} parameter for |vim.lsp.start_client|. +- The {handlers} parameter for |vim.lsp.start_client()|. This will set the |lsp-handler| as the default handler for this server. For example: > @@ -468,7 +470,7 @@ LspCodeLens |nvim_buf_set_extmark()|. LspCodeLensSeparator *hl-LspCodeLensSeparator* - Used to color the separator between two or more code lens. + Used to color the separator between two or more code lenses. *lsp-highlight-signature* @@ -513,7 +515,7 @@ callback in the "data" table. Example: > end, }) < -In addition, the following |User| |autocommands| are provided: +Also the following |User| |autocommand|s are provided: LspProgressUpdate *LspProgressUpdate* Upon receipt of a progress notification from the server. See @@ -538,8 +540,8 @@ 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} (number) Buffer handle, or 0 for current - {client_id} (number) Client id + • {bufnr} (number) Buffer handle, or 0 for current + • {client_id} (number) Client id buf_detach_client({bufnr}, {client_id}) *vim.lsp.buf_detach_client()* Detaches client from the specified buffer. Note: While the server is @@ -547,23 +549,23 @@ buf_detach_client({bufnr}, {client_id}) *vim.lsp.buf_detach_client()* send notifications should it ignore this notification. Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current - {client_id} (number) Client id + • {bufnr} (number) Buffer handle, or 0 for current + • {client_id} (number) 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} (number) Buffer handle, or 0 for current - {client_id} (number) the client id + • {bufnr} (number) Buffer handle, or 0 for current + • {client_id} (number) the client id buf_notify({bufnr}, {method}, {params}) *vim.lsp.buf_notify()* Send a notification to a server Parameters: ~ - {bufnr} [number] (optional): The number of the buffer - {method} [string]: Name of the request method - {params} [string]: Arguments to send to the server + • {bufnr} [number] (optional): The number of the buffer + • {method} [string]: Name of the request method + • {params} [string]: Arguments to send to the server Return: ~ true if any client returns true; false otherwise @@ -575,10 +577,10 @@ buf_request_all({bufnr}, {method}, {params}, {callback}) |vim.lsp.buf_request()| but the return result and callback are different. Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current. - {method} (string) LSP method name - {params} (optional, table) Parameters to send to the server - {callback} (function) The callback to call when all requests are + • {bufnr} (number) Buffer handle, or 0 for current. + • {method} (string) LSP method name + • {params} (optional, table) Parameters to send to the server + • {callback} (function) The callback to call when all requests are finished. Return: ~ @@ -594,10 +596,10 @@ buf_request_sync({bufnr}, {method}, {params}, {timeout_ms}) result is different. Wait maximum of {timeout_ms} (default 1000) ms. Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current. - {method} (string) LSP method name - {params} (optional, table) Parameters to send to the server - {timeout_ms} (optional, number, default=1000) Maximum time in + • {bufnr} (number) Buffer handle, or 0 for current. + • {method} (string) LSP method name + • {params} (optional, table) Parameters to send to the server + • {timeout_ms} (optional, number, default=1000) Maximum time in milliseconds to wait for a result. Return: ~ @@ -665,7 +667,7 @@ client_is_stopped({client_id}) *vim.lsp.client_is_stopped()* Checks whether a client is stopped. Parameters: ~ - {client_id} (Number) + • {client_id} (Number) Return: ~ true if client is stopped, false otherwise. @@ -675,8 +677,8 @@ for_each_buffer_client({bufnr}, {fn}) Invokes a function for each LSP client attached to a buffer. Parameters: ~ - {bufnr} (number) Buffer number - {fn} (function) Function to run on each client attached to buffer + • {bufnr} (number) Buffer number + • {fn} (function) Function to run on each client attached to buffer {bufnr}. The function takes the client, client ID, and buffer number as arguments. Example: > @@ -695,7 +697,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. @@ -704,7 +706,7 @@ get_active_clients({filter}) *vim.lsp.get_active_clients()* Get active clients. Parameters: ~ - {filter} (table|nil) A table with key-value pairs used to filter the + • {filter} (table|nil) 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 @@ -719,17 +721,17 @@ get_buffers_by_client_id({client_id}) Returns list of buffers attached to client_id. Parameters: ~ - {client_id} (number) client id + • {client_id} (number) client id Return: ~ - list of buffer ids + (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} (number) client id + • {client_id} (number) client id Return: ~ |vim.lsp.client| object, or nil @@ -744,8 +746,8 @@ omnifunc({findstart}, {base}) *vim.lsp.omnifunc()* Implements 'omnifunc' compatible LSP completion. Parameters: ~ - {findstart} 0 or 1, decides behavior - {base} If findstart=0, text to match against + • {findstart} 0 or 1, decides behavior + • {base} If findstart=0, text to match against Return: ~ (number) Decided by {findstart}: @@ -767,7 +769,7 @@ set_log_level({level}) *vim.lsp.set_log_level()* Use `lsp.log_levels` for reverse lookup. Parameters: ~ - {level} [number|string] the case insensitive level name or number + • {level} [number|string] the case insensitive level name or number See also: ~ |vim.lsp.log_levels| @@ -787,7 +789,8 @@ start({config}, {opts}) *vim.lsp.start()* }) < - See |lsp.start_client| for all available options. The most important are: + See |vim.lsp.start_client()| for all available options. The most important + are: `name` is an arbitrary name for the LSP client. It should be unique per language server. @@ -797,9 +800,9 @@ start({config}, {opts}) *vim.lsp.start()* constructs like `~` are NOT expanded. `root_dir` path to the project root. By default this is used to decide if - an existing client should be re-used. The example above uses |vim.fs.find| - and |vim.fs.dirname| to detect the root by traversing the file system - upwards starting from the current directory until either a + an existing client should be re-used. The example above uses + |vim.fs.find()| and |vim.fs.dirname()| to detect the root by traversing + the file system upwards starting from the current directory until either a `pyproject.toml` or `setup.py` file is found. `workspace_folders` a list of { uri:string, name: string } tables. The @@ -811,21 +814,23 @@ start({config}, {opts}) *vim.lsp.start()* the project folder. To ensure a language server is only started for languages it can handle, - make sure to call |vim.lsp.start| within a |FileType| autocmd. Either use - |:au|, |nvim_create_autocmd()| or put the call in a + make sure to call |vim.lsp.start()| within a |FileType| autocmd. Either + use |:au|, |nvim_create_autocmd()| or put the call in a `ftplugin/<filetype_name>.lua` (See |ftplugin-name|) Parameters: ~ - {config} (table) Same configuration as documented in - |lsp.start_client()| - {opts} nil|table Optional keyword arguments: + • {config} (table) Same configuration as documented in + |vim.lsp.start_client()| + • {opts} nil|table 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 re-uses a client if name and root_dir matches. + • bufnr (number) Buffer handle to attach to if starting or + re-using a client (0 for current). Return: ~ - (number) client_id + (number|nil) client_id start_client({config}) *vim.lsp.start_client()* Starts and initializes a client with the given configuration. @@ -835,29 +840,37 @@ start_client({config}) *vim.lsp.start_client()* The following parameters describe fields in the {config} table. Parameters: ~ - {cmd} (required, string or list treated like - |jobstart()|) Base command that initiates the LSP - client. - {cmd_cwd} (string, default=|getcwd()|) Directory to launch + • {cmd} (table|string|fun(dispatchers: table):table) + command string or list treated like |jobstart()|. + The command must launch the language server + process. `cmd` can also be a function that + creates an RPC client. The function receives a + dispatchers table and must return a table with + the functions `request`, `notify`, `is_closing` + and `terminate` See |vim.lsp.rpc.request()| and + |vim.lsp.rpc.notify()| For TCP there is a + built-in rpc client factory: + |vim.lsp.rpc.connect()| + • {cmd_cwd} (string, default=|getcwd()|) Directory to launch the `cmd` process. Not related to `root_dir`. - {cmd_env} (table) Environment flags to pass to the LSP on + • {cmd_env} (table) Environment flags to pass to the LSP on spawn. Can be specified using keys like a map or as a list with `k=v` pairs or both. Non-string values are coerced to string. Example: > { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; } < - {detached} (boolean, default true) Daemonize the server + • {detached} (boolean, default true) Daemonize the server process so that it runs in a separate process group from Nvim. Nvim will shutdown the process on exit, but if Nvim fails to exit cleanly this could leave behind orphaned server processes. - {workspace_folders} (table) List of workspace folders passed to the + • {workspace_folders} (table) List of workspace folders passed to the language server. For backwards compatibility rootUri and rootPath will be derived from the first workspace folder in this list. See `workspaceFolders` in the LSP spec. - {capabilities} Map overriding the default capabilities defined + • {capabilities} Map overriding the default capabilities defined by |vim.lsp.protocol.make_client_capabilities()|, passed to the language server on initialization. Hint: use make_client_capabilities() and modify @@ -865,44 +878,44 @@ start_client({config}) *vim.lsp.start_client()* • Note: To send an empty dictionary use `{[vim.type_idx]=vim.types.dictionary}`, else it will be encoded as an array. - {handlers} Map of language server method names to + • {handlers} Map of language server method names to |lsp-handler| - {settings} Map with language server specific settings. These + • {settings} Map with language server specific settings. These are returned to the language server if requested via `workspace/configuration`. Keys are case-sensitive. - {commands} (table) Table that maps string of clientside + • {commands} (table) Table that maps string of clientside commands to user-defined functions. Commands passed to start_client take precedence over the global command registry. Each key must be a unique command name, and the value is a function which is called if any LSP action (code action, code lenses, ...) triggers the command. - {init_options} Values to pass in the initialization request as + • {init_options} Values to pass in the initialization request as `initializationOptions`. See `initialize` in the LSP spec. - {name} (string, default=client-id) Name in log messages. - {get_language_id} function(bufnr, filetype) -> language ID as + • {name} (string, default=client-id) Name in log messages. + • {get_language_id} function(bufnr, filetype) -> language ID as string. Defaults to the filetype. - {offset_encoding} (default="utf-16") One of "utf-8", "utf-16", or + • {offset_encoding} (default="utf-16") One of "utf-8", "utf-16", or "utf-32" which is the encoding that the LSP server expects. Client does not verify this is correct. - {on_error} Callback with parameters (code, ...), invoked + • {on_error} Callback with parameters (code, ...), invoked when the client operation throws an error. `code` is a number describing the error. Other arguments may be passed depending on the error kind. See - |vim.lsp.rpc.client_errors| for possible errors. + `vim.lsp.rpc.client_errors` for possible errors. Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name. - {before_init} Callback with parameters (initialize_params, + • {before_init} Callback with parameters (initialize_params, config) invoked before the LSP "initialize" phase, where `params` contains the parameters being sent to the server and `config` is the config that was passed to |vim.lsp.start_client()|. You can use this to modify parameters before they are sent. - {on_init} Callback (client, initialize_result) invoked + • {on_init} Callback (client, initialize_result) invoked after LSP "initialize", where `result` is a table of `capabilities` and anything else the server may send. For example, clangd sends @@ -915,19 +928,19 @@ start_client({config}) *vim.lsp.start_client()* make this assumption. A `workspace/didChangeConfiguration` notification should be sent to the server during on_init. - {on_exit} Callback (code, signal, client_id) invoked on + • {on_exit} Callback (code, signal, client_id) invoked on client exit. • code: exit code of the process • signal: number describing the signal used to terminate (if any) • client_id: client handle - {on_attach} Callback (client, bufnr) invoked when client + • {on_attach} Callback (client, bufnr) invoked when client attaches to a buffer. - {trace} "off" | "messages" | "verbose" | nil passed + • {trace} "off" | "messages" | "verbose" | nil passed directly to the language server in the initialize request. Invalid/empty values will default to "off" - {flags} A table with flags for the client. The current + • {flags} A table with flags for the client. The current (experimental) flags are: • allow_incremental_sync (bool, default true): Allow using incremental sync for buffer edits @@ -937,11 +950,11 @@ start_client({config}) *vim.lsp.start_client()* debounce occurs if nil • exit_timeout (number|boolean, default false): Milliseconds to wait for server to exit cleanly - after sending the 'shutdown' request before + after sending the "shutdown" request before sending kill -15. If set to false, nvim exits - immediately after sending the 'shutdown' + immediately after sending the "shutdown" request to the server. - {root_dir} (string) Directory where the LSP server will base + • {root_dir} (string) Directory where the LSP server will base its workspaceFolders, rootUri, and rootPath on initialization. @@ -964,8 +977,8 @@ stop_client({client_id}, {force}) *vim.lsp.stop_client()* for this client, then force-shutdown is attempted. Parameters: ~ - {client_id} client id or |vim.lsp.client| object, or list thereof - {force} (boolean) (optional) shutdown forcefully + • {client_id} client id or |vim.lsp.client| object, or list thereof + • {force} (boolean) (optional) shutdown forcefully tagfunc({...}) *vim.lsp.tagfunc()* Provides an interface between the built-in client and 'tagfunc'. @@ -976,8 +989,8 @@ tagfunc({...}) *vim.lsp.tagfunc()* LSP servers, falls back to using built-in tags. Parameters: ~ - {pattern} Pattern used to find a workspace symbol - {flags} See |tag-function| + • {pattern} Pattern used to find a workspace symbol + • {flags} See |tag-function| Return: ~ A list of matching tags @@ -986,8 +999,8 @@ with({handler}, {override_config}) *vim.lsp.with()* Function to manage overriding defaults for LSP handlers. Parameters: ~ - {handler} (function) See |lsp-handler| - {override_config} (table) Table containing the keys to override + • {handler} (function) See |lsp-handler| + • {override_config} (table) Table containing the keys to override behavior of the {handler} @@ -1006,7 +1019,7 @@ 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|nil) Optional table which holds the following optional fields: • context: (table|nil) Corresponds to `CodeActionContext` of the LSP specification: • diagnostics (table|nil): LSP`Diagnostic[]` . Inferred from the current position if not provided. @@ -1033,13 +1046,13 @@ completion({context}) *vim.lsp.buf.completion()* called in Insert mode. Parameters: ~ - {context} (context support not yet implemented) Additional + • {context} (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) See also: ~ - |vim.lsp.protocol.constants.CompletionTriggerKind| + vim.lsp.protocol.constants.CompletionTriggerKind declaration({options}) *vim.lsp.buf.declaration()* Jumps to the declaration of the symbol under the cursor. @@ -1048,7 +1061,7 @@ declaration({options}) *vim.lsp.buf.declaration()* |vim.lsp.buf.definition()| instead. Parameters: ~ - {options} (table|nil) additional options + • {options} (table|nil) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) handler for list results. See @@ -1058,7 +1071,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|nil) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) handler for list results. See @@ -1076,13 +1089,14 @@ document_highlight() *vim.lsp.buf.document_highlight()* Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups to be defined or you won't be able to see the actual - highlights. |LspReferenceText| |LspReferenceRead| |LspReferenceWrite| + highlights. |hl-LspReferenceText| |hl-LspReferenceRead| + |hl-LspReferenceWrite| 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|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1090,7 +1104,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 @@ -1100,7 +1114,7 @@ format({options}) *vim.lsp.buf.format()* server clients. Parameters: ~ - {options} table|nil Optional table which holds the following optional + • {options} table|nil Optional table which holds the following optional fields: • formatting_options (table|nil): Can be used to specify FormattingOptions. Some unspecified options will be @@ -1128,59 +1142,11 @@ format({options}) *vim.lsp.buf.format()* ID (client.id) matching this field. • name (string|nil): Restrict formatting to the client with name (client.name) matching this field. - -formatting({options}) *vim.lsp.buf.formatting()* - Formats the current buffer. - - Parameters: ~ - {options} (table|nil) Can be used to specify FormattingOptions. Some - unspecified options will be automatically derived from the - current Neovim options. - - See also: ~ - https://microsoft.github.io/language-server-protocol/specification#textDocument_formatting - - *vim.lsp.buf.formatting_seq_sync()* -formatting_seq_sync({options}, {timeout_ms}, {order}) - Formats the current buffer by sequentially requesting formatting from - attached clients. - - Useful when multiple clients with formatting capability are attached. - - Since it's synchronous, can be used for running on save, to make sure - buffer is formatted prior to being saved. {timeout_ms} is passed on to the - |vim.lsp.client| `request_sync` method. Example: > - - vim.api.nvim_command[[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_seq_sync()]] -< - - Parameters: ~ - {options} (table|nil) `FormattingOptions` entries - {timeout_ms} (number|nil) Request timeout - {order} (table|nil) List of client names. Formatting is - requested from clients in the following order: first all - clients that are not in the `order` list, then the - remaining clients in the order as they occur in the - `order` list. - - *vim.lsp.buf.formatting_sync()* -formatting_sync({options}, {timeout_ms}) - Performs |vim.lsp.buf.formatting()| synchronously. - - Useful for running on save, to make sure buffer is formatted prior to - being saved. {timeout_ms} is passed on to |vim.lsp.buf_request_sync()|. - Example: -> - - autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync() -< - - Parameters: ~ - {options} (table|nil) with valid `FormattingOptions` entries - {timeout_ms} (number) Request timeout - - See also: ~ - |vim.lsp.buf.formatting_seq_sync| + • range (table|nil) Range to format. Table must contain + `start` and `end` keys with {row, col} tuples using (1,0) + indexing. Defaults to current selection in visual mode + Defaults to `nil` in other modes, formatting the full + buffer hover() *vim.lsp.buf.hover()* Displays hover information about the symbol under the cursor in a floating @@ -1191,14 +1157,14 @@ implementation({options}) *vim.lsp.buf.implementation()* quickfix window. Parameters: ~ - {options} (table|nil) additional options + • {options} (table|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| incoming_calls() *vim.lsp.buf.incoming_calls()* Lists all the call sites of the symbol under the cursor in the |quickfix| window. If the symbol can resolve to multiple items, the user can pick one - in the |inputlist|. + in the |inputlist()|. list_workspace_folders() *vim.lsp.buf.list_workspace_folders()* List workspace folders. @@ -1206,41 +1172,15 @@ list_workspace_folders() *vim.lsp.buf.list_workspace_folders()* outgoing_calls() *vim.lsp.buf.outgoing_calls()* Lists all the items that are called by the symbol under the cursor in the |quickfix| window. If the symbol can resolve to multiple items, the user - can pick one in the |inputlist|. - - *vim.lsp.buf.range_code_action()* -range_code_action({context}, {start_pos}, {end_pos}) - Performs |vim.lsp.buf.code_action()| for a given range. - - Parameters: ~ - {context} (table|nil) `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 - filter the code actions. Most language servers support - values like `refactor` or `quickfix`. - {start_pos} ({number, number}, optional) mark-indexed position. - Defaults to the start of the last visual selection. - {end_pos} ({number, number}, optional) mark-indexed position. - Defaults to the end of the last visual selection. - - *vim.lsp.buf.range_formatting()* -range_formatting({options}, {start_pos}, {end_pos}) - Formats a given range. - - Parameters: ~ - {options} Table with valid `FormattingOptions` entries. - {start_pos} ({number, number}, optional) mark-indexed position. - Defaults to the start of the last visual selection. - {end_pos} ({number, number}, optional) mark-indexed position. - Defaults to the end of the last visual selection. + can pick one in the |inputlist()|. references({context}, {options}) *vim.lsp.buf.references()* Lists all the references to the symbol under the cursor in the quickfix window. Parameters: ~ - {context} (table) Context for the request - {options} (table|nil) additional options + • {context} (table) Context for the request + • {options} (table|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1256,9 +1196,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 + • {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 + • {options} (table|nil) 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. @@ -1280,7 +1220,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|nil) additional options • reuse_win: (boolean) Jump to existing window if buffer is already open. • on_list: (function) handler for list results. See @@ -1294,8 +1234,8 @@ workspace_symbol({query}, {options}) *vim.lsp.buf.workspace_symbol()* string means no filtering is done. Parameters: ~ - {query} (string, optional) - {options} (table|nil) additional options + • {query} (string, optional) + • {options} (table|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1308,7 +1248,7 @@ get_namespace({client_id}) *vim.lsp.diagnostic.get_namespace()* |vim.diagnostic|. Parameters: ~ - {client_id} (number) The id of the LSP client + • {client_id} (number) The id of the LSP client *vim.lsp.diagnostic.on_publish_diagnostics()* on_publish_diagnostics({_}, {result}, {ctx}, {config}) @@ -1337,7 +1277,7 @@ on_publish_diagnostics({_}, {result}, {ctx}, {config}) < Parameters: ~ - {config} (table) Configuration table (see |vim.diagnostic.config()|). + • {config} (table) Configuration table (see |vim.diagnostic.config()|). ============================================================================== @@ -1347,15 +1287,15 @@ display({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.display()* Display the lenses using virtual text Parameters: ~ - {lenses} (table) of lenses to display (`CodeLens[] | null`) - {bufnr} (number) - {client_id} (number) + • {lenses} (table) of lenses to display (`CodeLens[] | null`) + • {bufnr} (number) + • {client_id} (number) get({bufnr}) *vim.lsp.codelens.get()* Return all lenses for the given buffer Parameters: ~ - {bufnr} (number) Buffer number. 0 can be used for the current buffer. + • {bufnr} (number) Buffer number. 0 can be used for the current buffer. Return: ~ (table) (`CodeLens[]`) @@ -1379,9 +1319,9 @@ save({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.save()* Store lenses for a specific buffer and client Parameters: ~ - {lenses} (table) of lenses to store (`CodeLens[] | null`) - {bufnr} (number) - {client_id} (number) + • {lenses} (table) of lenses to store (`CodeLens[] | null`) + • {bufnr} (number) + • {client_id} (number) ============================================================================== @@ -1399,7 +1339,7 @@ hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()* < Parameters: ~ - {config} (table) Configuration table. + • {config} (table) Configuration table. • border: (default=nil) • Add borders to the floating window • See |nvim_open_win()| @@ -1418,10 +1358,10 @@ signature_help({_}, {result}, {ctx}, {config}) < Parameters: ~ - {config} (table) Configuration table. + • {config} (table) Configuration table. • border: (default=nil) • Add borders to the floating window - • See |vim.api.nvim_open_win()| + • See |nvim_open_win()| ============================================================================== @@ -1433,8 +1373,8 @@ apply_text_document_edit({text_document_edit}, {index}, {offset_encoding}) document. Parameters: ~ - {text_document_edit} table: a `TextDocumentEdit` object - {index} number: Optional index of the edit, if from a + • {text_document_edit} (table) a `TextDocumentEdit` object + • {index} (number) Optional index of the edit, if from a list of edits (or nil, if not from a list) See also: ~ @@ -1445,9 +1385,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} (number) Buffer id - {offset_encoding} (string) utf-8|utf-16|utf-32 + • {text_edits} (table) list of `TextEdit` objects + • {bufnr} (number) Buffer id + • {offset_encoding} (string) utf-8|utf-16|utf-32 See also: ~ https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit @@ -1457,24 +1397,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} (number) Buffer id + • {bufnr} (number) 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} (number) Buffer id - {references} (table) List of `DocumentHighlight` objects to + • {bufnr} (number) 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/specifications/specification-3-17/#documentHighlight @@ -1484,10 +1424,10 @@ character_offset({buf}, {row}, {col}, {offset_encoding}) Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. Parameters: ~ - {buf} (number) 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|nil defaults to + • {buf} (number) 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|nil defaults to `offset_encoding` of first client of `buf` Return: ~ @@ -1502,8 +1442,8 @@ convert_input_to_markdown_lines({input}, {contents}) `textDocument/signatureHelp`, and potentially others. Parameters: ~ - {input} (`MarkedString` | `MarkedString[]` | `MarkupContent`) - {contents} (table, optional, default `{}`) List of strings to extend + • {input} (`MarkedString` | `MarkedString[]` | `MarkupContent`) + • {contents} (table, optional, default `{}`) List of strings to extend with converted lines Return: ~ @@ -1517,14 +1457,14 @@ convert_signature_help_to_markdown_lines({signature_help}, {ft}, {triggers}) Converts `textDocument/SignatureHelp` response to markdown lines. Parameters: ~ - {signature_help} Response of `textDocument/SignatureHelp` - {ft} optional filetype that will be use as the `lang` for + • {signature_help} Response of `textDocument/SignatureHelp` + • {ft} optional filetype that will be use as the `lang` for the label markdown code block - {triggers} optional list of trigger characters from the lsp + • {triggers} optional list of trigger characters from the lsp server. used to better determine parameter offsets Return: ~ - list of lines of converted markdown. + (list) of lines of converted markdown. See also: ~ https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp @@ -1534,7 +1474,7 @@ extract_completion_items({result}) Can be used to extract the completion items from a `textDocument/completion` request, which may return one of `CompletionItem[]` , `CompletionList` or null. Parameters: ~ - {result} (table) The result of a `textDocument/completion` request + • {result} (table) The result of a `textDocument/completion` request Return: ~ (table) List of completion items @@ -1546,26 +1486,26 @@ get_effective_tabstop({bufnr}) *vim.lsp.util.get_effective_tabstop()* Returns indentation size. Parameters: ~ - {bufnr} (number|nil): Buffer handle, defaults to current + • {bufnr} (number|nil) Buffer handle, defaults to current Return: ~ (number) indentation size See also: ~ - |shiftwidth| + 'shiftwidth' *vim.lsp.util.jump_to_location()* jump_to_location({location}, {offset_encoding}, {reuse_win}) Jumps to a location. Parameters: ~ - {location} (table) (`Location`|`LocationLink`) - {offset_encoding} (string) utf-8|utf-16|utf-32 (required) - {reuse_win} (boolean) Jump to existing window if buffer is - already opened. + • {location} (table) (`Location`|`LocationLink`) + • {offset_encoding} "utf-8" | "utf-16" | "utf-32" + • {reuse_win} (boolean) Jump to existing window if buffer is + already open. Return: ~ - `true` if the jump succeeded + (boolean) `true` if the jump succeeded *vim.lsp.util.locations_to_items()* locations_to_items({locations}, {offset_encoding}) @@ -1576,8 +1516,8 @@ locations_to_items({locations}, {offset_encoding}) |setloclist()|. Parameters: ~ - {locations} (table) list of `Location`s or `LocationLink`s - {offset_encoding} (string) offset_encoding for locations + • {locations} (table) list of `Location`s or `LocationLink`s + • {offset_encoding} (string) offset_encoding for locations utf-8|utf-16|utf-32 Return: ~ @@ -1587,8 +1527,8 @@ lookup_section({settings}, {section}) *vim.lsp.util.lookup_section()* Helper function to return nested values in language server settings Parameters: ~ - {settings} a table of language server settings - {section} a string indicating the field of the settings table + • {settings} a table of language server settings + • {section} a string indicating the field of the settings table Return: ~ (table or string) The value of settings accessed via section @@ -1599,9 +1539,9 @@ make_floating_popup_options({width}, {height}, {opts}) table can be passed to |nvim_open_win()|. Parameters: ~ - {width} (number) window width (in character cells) - {height} (number) window height (in character cells) - {opts} (table, optional) + • {width} (number) window width (in character cells) + • {height} (number) window height (in character cells) + • {opts} (table, optional) • offset_x (number) offset to add to `col` • offset_y (number) offset to add to `row` • border (string or table) override `border` @@ -1617,7 +1557,7 @@ make_formatting_params({options}) cursor position. Parameters: ~ - {options} (table|nil) with valid `FormattingOptions` entries + • {options} (table|nil) with valid `FormattingOptions` entries Return: ~ `DocumentFormattingParams` object @@ -1631,13 +1571,13 @@ make_given_range_params({start_pos}, {end_pos}, {bufnr}, {offset_encoding}) similar to |vim.lsp.util.make_range_params()|. Parameters: ~ - {start_pos} number[]|nil {row, col} mark-indexed position. + • {start_pos} number[]|nil {row, col} mark-indexed position. Defaults to the start of the last visual selection. - {end_pos} number[]|nil {row, col} mark-indexed position. + • {end_pos} number[]|nil {row, col} mark-indexed position. Defaults to the end of the last visual selection. - {bufnr} (number|nil) buffer handle or 0 for current, + • {bufnr} (number|nil) 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"|nil defaults to `offset_encoding` of first client of `bufnr` Return: ~ @@ -1650,9 +1590,9 @@ make_position_params({window}, {offset_encoding}) cursor position. Parameters: ~ - {window} number|nil: window handle or 0 for current, + • {window} (number|nil) window handle or 0 for current, defaults to current - {offset_encoding} (string) 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` @@ -1670,9 +1610,9 @@ make_range_params({window}, {offset_encoding}) `textDocument/rangeFormatting`. Parameters: ~ - {window} number|nil: window handle or 0 for current, + • {window} (number|nil) 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"|nil defaults to `offset_encoding` of first client of buffer of `window` @@ -1685,7 +1625,7 @@ make_text_document_params({bufnr}) Creates a `TextDocumentIdentifier` object for the current buffer. Parameters: ~ - {bufnr} number|nil: Buffer handle, defaults to current + • {bufnr} (number|nil) Buffer handle, defaults to current Return: ~ `TextDocumentIdentifier` @@ -1698,18 +1638,18 @@ make_workspace_params({added}, {removed}) Create the workspace params Parameters: ~ - {added} - {removed} + • {added} + • {removed} *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 passed - on to |vim.api.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 passed + on to |nvim_open_win()|) • height: (number) height of floating window • width: (number) width of floating window • wrap: (boolean, default true) wrap long lines @@ -1737,7 +1677,7 @@ parse_snippet({input}) *vim.lsp.util.parse_snippet()* Parses snippets in a completion entry. Parameters: ~ - {input} (string) unparsed snippet + • {input} (string) unparsed snippet Return: ~ (string) parsed snippet @@ -1751,7 +1691,7 @@ preview_location({location}, {opts}) *vim.lsp.util.preview_location()* definition) Parameters: ~ - {location} a single `Location` or `LocationLink` + • {location} a single `Location` or `LocationLink` Return: ~ (bufnr,winnr) buffer and window number of floating window or nil @@ -1760,7 +1700,7 @@ rename({old_fname}, {new_fname}, {opts}) *vim.lsp.util.rename()* Rename old_fname to new_fname Parameters: ~ - {opts} (table) + • {opts} (table) set_lines({lines}, {A}, {B}, {new_lines}) *vim.lsp.util.set_lines()* Replaces text in a range with new text. @@ -1768,14 +1708,30 @@ set_lines({lines}, {A}, {B}, {new_lines}) *vim.lsp.util.set_lines()* CAUTION: Changes in-place! Parameters: ~ - {lines} (table) Original list of strings - {A} (table) Start position; a 2-tuple of {line, col} numbers - {B} (table) End position; a 2-tuple of {line, col} numbers - {new_lines} A list of strings to replace the original + • {lines} (table) Original list of strings + • {A} (table) Start position; a 2-tuple of {line, col} numbers + • {B} (table) End position; a 2-tuple of {line, col} numbers + • {new_lines} A list of strings to replace the original Return: ~ (table) The modified {lines} object + *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} "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 + *vim.lsp.util.stylize_markdown()* stylize_markdown({bufnr}, {contents}, {opts}) Converts markdown into syntax highlighted regions by stripping the code @@ -1789,8 +1745,8 @@ stylize_markdown({bufnr}, {contents}, {opts}) `open_floating_preview` instead Parameters: ~ - {contents} (table) of lines to show in window - {opts} dictionary with optional fields + • {contents} (table) of lines to show in window + • {opts} dictionary with optional fields • height of floating window • width of floating window • wrap_at character to wrap at for computing height @@ -1807,7 +1763,7 @@ symbols_to_items({symbols}, {bufnr}) *vim.lsp.util.symbols_to_items()* Converts symbols to quickfix list items. Parameters: ~ - {symbols} DocumentSymbol[] or SymbolInformation[] + • {symbols} DocumentSymbol[] or SymbolInformation[] *vim.lsp.util.text_document_completion_list_to_complete_items()* text_document_completion_list_to_complete_items({result}, {prefix}) @@ -1815,10 +1771,10 @@ text_document_completion_list_to_complete_items({result}, {prefix}) vim-compatible |complete-items|. Parameters: ~ - {result} The result of a `textDocument/completion` call, e.g. from + • {result} The result of a `textDocument/completion` call, e.g. from |vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, `CompletionList` or `null` - {prefix} (string) the prefix to filter the completion items + • {prefix} (string) the prefix to filter the completion items Return: ~ { matches = complete-items table, incomplete = bool } @@ -1830,7 +1786,7 @@ trim_empty_lines({lines}) *vim.lsp.util.trim_empty_lines()* Removes empty lines from the beginning and end. Parameters: ~ - {lines} (table) list of lines to trim + • {lines} (table) list of lines to trim Return: ~ (table) trimmed list of lines @@ -1843,10 +1799,10 @@ try_trim_markdown_code_blocks({lines}) CAUTION: Modifies the input in-place! Parameters: ~ - {lines} (table) list of lines + • {lines} (table) list of lines Return: ~ - (string) filetype or 'markdown' if it was unchanged. + (string) filetype or "markdown" if it was unchanged. ============================================================================== @@ -1868,20 +1824,20 @@ 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 or number) One of `vim.lsp.log.levels` + • {level} (string or number) One of `vim.lsp.log.levels` should_log({level}) *vim.lsp.log.should_log()* Checks whether the level is sufficient for logging. Parameters: ~ - {level} (number) log level + • {level} (number) log level Return: ~ (bool) true if would log, false if not @@ -1890,11 +1846,22 @@ should_log({level}) *vim.lsp.log.should_log()* ============================================================================== Lua module: vim.lsp.rpc *lsp-rpc* +connect({host}, {port}) *vim.lsp.rpc.connect()* + Create a LSP RPC client factory that connects via TCP to the given host + and port + + Parameters: ~ + • {host} (string) + • {port} (number) + + Return: ~ + (function) + 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 @@ -1903,8 +1870,8 @@ 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|nil) Parameters for the invoked LSP method Return: ~ (bool) `true` if notification could be sent, `false` if not @@ -1914,10 +1881,11 @@ 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 - {callback} (function) Callback to invoke - {notify_reply_callback} (function|nil) Callback to invoke as soon as + • {method} (string) The invoked LSP method + • {params} (table|nil) Parameters for the invoked LSP + method + • {callback} (function) Callback to invoke + • {notify_reply_callback} (function|nil) Callback to invoke as soon as a request is no longer pending Return: ~ @@ -1929,28 +1897,29 @@ rpc_response_error({code}, {message}, {data}) Creates an RPC response object/table. Parameters: ~ - {code} (number) RPC error code defined in + • {code} (number) RPC error code defined in `vim.lsp.protocol.ErrorCodes` - {message} (string|nil) arbitrary message to send to server - {data} any|nil arbitrary data to send to server + • {message} (string|nil) arbitrary message to send to server + • {data} any|nil arbitrary data to send to server *vim.lsp.rpc.start()* start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) Starts an LSP server process and create an LSP RPC client object to - interact with it. Communication with the server is currently limited to - stdio. + interact with it. Communication with the spawned process happens via + stdio. For communication via TCP, spawn a process manually and use + |vim.lsp.rpc.connect()| Parameters: ~ - {cmd} (string) Command to start the LSP server. - {cmd_args} (table) List of additional string arguments to + • {cmd} (string) Command to start the LSP server. + • {cmd_args} (table) List of additional string arguments to pass to {cmd}. - {dispatchers} (table|nil) Dispatchers for LSP message types. + • {dispatchers} (table|nil) 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 + • {extra_spawn_params} (table|nil) Additional context for the LSP server process. May contain: • {cwd} (string) Working directory for the LSP server process @@ -1962,11 +1931,8 @@ start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) Methods: • `notify()` |vim.lsp.rpc.notify()| • `request()` |vim.lsp.rpc.request()| - - Members: - • {pid} (number) The LSP server's PID. - • {handle} A handle for low-level interaction with the LSP server - process |vim.loop|. + • `is_closing()` returns a boolean indicating if the RPC is closing. + • `terminate()` terminates the RPC client. ============================================================================== @@ -1977,14 +1943,14 @@ compute_diff({___MissingCloseParenHere___}) Returns the range table for the difference between prev and curr lines Parameters: ~ - {prev_lines} (table) list of lines - {curr_lines} (table) list of lines - {firstline} (number) line to begin search for first difference - {lastline} (number) line to begin search in old_lines for last + • {prev_lines} (table) list of lines + • {curr_lines} (table) list of lines + • {firstline} (number) line to begin search for first difference + • {lastline} (number) line to begin search in old_lines for last difference - {new_lastline} (number) line to begin search in new_lines for last + • {new_lastline} (number) line to begin search in new_lines for last difference - {offset_encoding} (string) encoding requested by language server + • {offset_encoding} (string) encoding requested by language server Return: ~ (table) TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentContentChangeEvent @@ -2003,7 +1969,7 @@ resolve_capabilities({server_capabilities}) Creates a normalized object describing LSP server capabilities. Parameters: ~ - {server_capabilities} (table) Table of capabilities supported by the + • {server_capabilities} (table) Table of capabilities supported by the server Return: ~ diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 42f3a5e432..7330453778 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -11,30 +11,126 @@ Lua engine *lua* *Lua* ============================================================================== INTRODUCTION *lua-intro* -The Lua 5.1 language is builtin and always available. Try this command to get -an idea of what lurks beneath: > +The Lua 5.1 script engine is builtin and always available. Try this command to +get an idea of what lurks beneath: > :lua print(vim.inspect(package.loaded)) + +Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the +"editor stdlib" (|builtin-functions| and |Ex-commands|) and the |API|, all of +which can be used from Lua code (|lua-vimscript| |vim.api|). Together these +"namespaces" form the Nvim programming interface. + +The |:source| and |:runtime| commands can run Lua scripts. Lua modules can be +loaded with `require('name')`, which by convention usually returns a table. +See |lua-require| for how Nvim finds and loads Lua modules. + +See this page for more insight into Nvim Lua: + https://github.com/nanotee/nvim-lua-guide + + *lua-compat* +Lua 5.1 is the permanent interface for Nvim Lua. Plugins need only consider +Lua 5.1, not worry about forward-compatibility with future Lua versions. If +Nvim ever ships with Lua 5.4+, a Lua 5.1 compatibility shim will be provided +so that old plugins continue to work transparently. + +------------------------------------------------------------------------------ +LUA CONCEPTS AND IDIOMS *lua-concepts* + +Lua is very simple: this means that, while there are some quirks, once you +internalize those quirks, everything works the same everywhere. Scopes +(closures) in particular are very consistent, unlike JavaScript or most other +languages. + +Lua has three fundamental mechanisms—one for "each major aspect of +programming": tables, closures, and coroutines. +https://www.lua.org/doc/cacm2018.pdf +- Tables are the "object" or container datastructure: they represent both + lists and maps, you can extend them to represent your own datatypes and + change their behavior using |luaref-metatable| (like Python's "datamodel"). +- EVERY scope in Lua is a closure: a function is a closure, a module is + a closure, a `do` block (|luaref-do|) is a closure--and they all work the + same. A Lua module is literally just a big closure discovered on the "path" + (where your modules are found: |package.cpath|). +- Stackful coroutines enable cooperative multithreading, generators, and + versatile control for both Lua and its host (Nvim). + + *lua-call-function* +Lua functions can be called in multiple ways. Consider the function: > + local foo = function(a, b) + print("A: ", a) + print("B: ", b) + end + +The first way to call this function is: > + foo(1, 2) + -- ==== Result ==== + -- A: 1 + -- B: 2 + +This way of calling a function is familiar from most scripting languages. +In Lua, any missing arguments are passed as `nil`. Example: > + foo(1) + -- ==== Result ==== + -- A: 1 + -- B: nil + +Furthermore it is not an error if extra parameters are passed, they are just +discarded. + +It is also allowed to omit the parentheses (only) if the function takes +exactly one string (`"foo"`) or table literal (`{1,2,3}`). The latter is often +used to approximate the "named parameters" feature of languages like Python +("kwargs" or "keyword args"). Example: > + local func_with_opts = function(opts) + local will_do_foo = opts.foo + local filename = opts.filename + + ... + end + + func_with_opts { foo = true, filename = "hello.world" } < -Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the -"editor stdlib" (|builtin-functions| and Ex commands) and the |API|, all of -which can be used from Lua code. A good overview of using Lua in neovim is -given by https://github.com/nanotee/nvim-lua-guide. +There is nothing special going on here except that parentheses are treated as +whitespace. But visually, this small bit of sugar gets reasonably close to +a "keyword args" interface. -The |:source| and |:runtime| commands can run Lua scripts as well as Vim -scripts. Lua modules can be loaded with `require('name')`, which -conventionally returns a table but can return any value. +It is of course also valid to call the function with parentheses: > -See |lua-require| for details on how Nvim finds and loads Lua modules. -See |lua-require-example| for an example of how to write and use a module. + func_with_opts({ foo = true, filename = "hello.world" }) +< +Nvim tends to prefer the keyword args style. + +------------------------------------------------------------------------------ +LUA PATTERNS *lua-patterns* + +Lua intentionally does not support regular expressions, instead it has limited +"patterns" which avoid the performance pitfalls of extended regex. +|luaref-patterns| + +Examples using |string.match()|: > + + print(string.match("foo123bar123", "%d+")) + -- 123 + + print(string.match("foo123bar123", "[^%d]+")) + -- foo + + print(string.match("foo123bar123", "[abc]+")) + -- ba + + print(string.match("foo.bar", "%.bar")) + -- .bar + +For more complex matching you can use Vim regex from Lua via |vim.regex()|. ============================================================================== IMPORTING LUA MODULES *lua-require* Modules are searched for under the directories specified in 'runtimepath', in -the order they appear. Any `.` in the module name is treated as a directory -separator when searching. For a module `foo.bar`, each directory is searched -for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found, +the order they appear. Any "." in the module name is treated as a directory +separator when searching. For a module `foo.bar`, each directory is searched +for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found, the directories are searched again for a shared library with a name matching `lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from the initial value of |package.cpath|. If still no files are found, Nvim falls @@ -48,8 +144,7 @@ documentation at https://www.lua.org/manual/5.1/manual.html#pdf-require. For example, if 'runtimepath' is `foo,bar` and |package.cpath| was `./?.so;./?.dll` at startup, `require('mod')` searches these paths in order -and loads the first module found: - +and loads the first module found ("first wins"): > foo/lua/mod.lua foo/lua/mod/init.lua bar/lua/mod.lua @@ -58,10 +153,11 @@ and loads the first module found: foo/lua/mod.dll bar/lua/mod.so bar/lua/mod.dll - +< + *lua-package-path* Nvim automatically adjusts |package.path| and |package.cpath| according to the effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is -changed. |package.path| is adjusted by simply appending `/lua/?.lua` and +changed. `package.path` is adjusted by simply appending `/lua/?.lua` and `/lua/?/init.lua` to each directory from 'runtimepath' (`/` is actually the first character of `package.config`). @@ -70,37 +166,33 @@ added to |package.cpath|. In this case, instead of appending `/lua/?.lua` and `/lua/?/init.lua` to each runtimepath, all unique `?`-containing suffixes of the existing |package.cpath| are used. Example: -1. Given that +- 1. Given that - 'runtimepath' contains `/foo/bar,/xxx;yyy/baz,/abc`; - - initial (defined at compile-time or derived from - `$LUA_CPATH`/`$LUA_INIT`) |package.cpath| contains - `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`. -2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in - order: parts of the path starting from the first path component containing - question mark and preceding path separator. -3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same - as the suffix of the first path from |package.path| (i.e. `./?.so`). Which - leaves `/?.so` and `/a?d/j/g.elf`, in this order. -4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The - second one contains a semicolon which is a paths separator so it is out, - leaving only `/foo/bar` and `/abc`, in order. -5. The cartesian product of paths from 4. and suffixes from 3. is taken, - giving four variants. In each variant, a `/lua` path segment is inserted - between path and suffix, leaving: - - - `/foo/bar/lua/?.so` - - `/foo/bar/lua/a?d/j/g.elf` - - `/abc/lua/?.so` - - `/abc/lua/a?d/j/g.elf` - -6. New paths are prepended to the original |package.cpath|. - -The result will look like this: - - `/foo/bar,/xxx;yyy/baz,/abc` ('runtimepath') - × `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so` (`package.cpath`) - - = `/foo/bar/lua/?.so;/foo/bar/lua/a?d/j/g.elf;/abc/lua/?.so;/abc/lua/a?d/j/g.elf;./?.so;/def/ghi/a?d/j/g.elf;/def/?.so` + - initial |package.cpath| (defined at compile-time or derived from + `$LUA_CPATH` / `$LUA_INIT`) contains `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`. +- 2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in + order: parts of the path starting from the first path component containing + question mark and preceding path separator. +- 3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same + as the suffix of the first path from |package.path| (i.e. `./?.so`). Which + leaves `/?.so` and `/a?d/j/g.elf`, in this order. +- 4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The + second one contains a semicolon which is a paths separator so it is out, + leaving only `/foo/bar` and `/abc`, in order. +- 5. The cartesian product of paths from 4. and suffixes from 3. is taken, + giving four variants. In each variant a `/lua` path segment is inserted + between path and suffix, leaving: + - `/foo/bar/lua/?.so` + - `/foo/bar/lua/a?d/j/g.elf` + - `/abc/lua/?.so` + - `/abc/lua/a?d/j/g.elf` +- 6. New paths are prepended to the original |package.cpath|. + +The result will look like this: > + + /foo/bar,/xxx;yyy/baz,/abc ('runtimepath') + × ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so (package.cpath) + = /foo/bar/lua/?.so;/foo/bar/lua/a?d/j/g.elf;/abc/lua/?.so;/abc/lua/a?d/j/g.elf;./?.so;/def/ghi/a?d/j/g.elf;/def/?.so Note: @@ -122,170 +214,13 @@ Note: it is better to not have them in 'runtimepath' at all. ============================================================================== -Lua Syntax Information *lua-syntax-help* - -While Lua has a simple syntax, there are a few things to understand, -particularly when looking at the documentation above. - - *lua-syntax-call-function* - -Lua functions can be called in multiple ways. Consider the function: > - - local example_func = function(a, b) - print("A is: ", a) - print("B is: ", b) - end -< -The first way to call this function is: > - - example_func(1, 2) - -- ==== Result ==== - -- A is: 1 - -- B is: 2 -< -This way of calling a function is familiar from most scripting languages. -In Lua, it's important to understand that any function arguments that are -not supplied are automatically set to `nil`. For example: > - - example_func(1) - -- ==== Result ==== - -- A is: 1 - -- B is: nil -< -Additionally, if any extra parameters are passed, they are discarded -completely. - -In Lua, it is also possible to omit the parentheses (only) if the function -takes a single string or table literal (`"foo"` or "`{1,2,3}`", respectively). -The latter is most often used to approximate "keyword-style" arguments with a -single dictionary, for example: > - - local func_with_opts = function(opts) - local will_do_foo = opts.foo - local filename = opts.filename - - ... - end - - func_with_opts { foo = true, filename = "hello.world" } -< -In this style, each "parameter" is passed via keyword. It is still valid -to call the function in the standard style: > - - func_with_opts({ foo = true, filename = "hello.world" }) -< -But often in the documentation, you will see the former rather than the -latter style due to its brevity. - -============================================================================== -Lua Patterns *lua-patterns* - -For performance reasons, Lua does not support regular expressions natively. -Instead, the Lua `string` standard library allows manipulations using a -restricted set of "patterns", see |luaref-patterns|. - -Examples (`string.match` extracts the first match): > - - print(string.match("foo123bar123", "%d+")) - -- -> 123 - - print(string.match("foo123bar123", "[^%d]+")) - -- -> foo - - print(string.match("foo123bar123", "[abc]+")) - -- -> ba - - print(string.match("foo.bar", "%.bar")) - -- -> .bar - -For more complex matching, Vim regular expressions can be used from Lua -through |vim.regex()|. - ------------------------------------------------------------------------------- -LUA PLUGIN EXAMPLE *lua-require-example* - -The following example plugin adds a command `:MakeCharBlob` which transforms -current buffer into a long `unsigned char` array. Lua contains transformation -function in a module `lua/charblob.lua` which is imported in -`autoload/charblob.vim` (`require("charblob")`). Example plugin is supposed -to be put into any directory from 'runtimepath', e.g. `~/.config/nvim` (in -this case `lua/charblob.lua` means `~/.config/nvim/lua/charblob.lua`). - -autoload/charblob.vim: > - - function charblob#encode_buffer() - call setline(1, luaeval( - \ 'require("charblob").encode(unpack(_A))', - \ [getline(1, '$'), &textwidth, ' '])) - endfunction -< -plugin/charblob.vim: > - - if exists('g:charblob_loaded') - finish - endif - let g:charblob_loaded = 1 - - command MakeCharBlob :call charblob#encode_buffer() -< -lua/charblob.lua: > - - local function charblob_bytes_iter(lines) - local init_s = { - next_line_idx = 1, - next_byte_idx = 1, - lines = lines, - } - local function next(s, _) - if lines[s.next_line_idx] == nil then - return nil - end - if s.next_byte_idx > #(lines[s.next_line_idx]) then - s.next_line_idx = s.next_line_idx + 1 - s.next_byte_idx = 1 - return ('\n'):byte() - end - local ret = lines[s.next_line_idx]:byte(s.next_byte_idx) - if ret == ('\n'):byte() then - ret = 0 -- See :h NL-used-for-NUL. - end - s.next_byte_idx = s.next_byte_idx + 1 - return ret - end - return next, init_s, nil - end - - local function charblob_encode(lines, textwidth, indent) - local ret = { - 'const unsigned char blob[] = {', - indent, - } - for byte in charblob_bytes_iter(lines) do - -- .- space + number (width 3) + comma - if #(ret[#ret]) + 5 > textwidth then - ret[#ret + 1] = indent - else - ret[#ret] = ret[#ret] .. ' ' - end - ret[#ret] = ret[#ret] .. (('%3u,'):format(byte)) - end - ret[#ret + 1] = '};' - return ret - end - - return { - bytes_iter = charblob_bytes_iter, - encode = charblob_encode, - } -< -============================================================================== COMMANDS *lua-commands* These commands execute a Lua chunk from either the command line (:lua, :luado) or a file (:luafile) on the given line [range]. As always in Lua, each chunk has its own scope (closure), so only global variables are shared between command calls. The |lua-stdlib| modules, user modules, and anything else on -|lua-package-path| are available. +|package.path| are available. The Lua print() function redirects its output to the Nvim message area, with arguments separated by " " (space) instead of "\t" (tab). @@ -339,7 +274,7 @@ arguments separated by " " (space) instead of "\t" (tab). :lua require"lpeg" :lua -- balanced parenthesis grammar: :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" } - :luado if bp:match(line) then return "-->\t" .. line end + :luado if bp:match(line) then return "=>\t" .. line end < *:luafile* :luafile {file} @@ -617,7 +552,7 @@ A subset of the `vim.*` API is available in threads. This includes: - `vim.loop` with a separate event loop per thread. - `vim.mpack` and `vim.json` (useful for serializing messages between threads) -- `require` in threads can use lua packages from the global |lua-package-path| +- `require` in threads can use lua packages from the global |package.path| - `print()` and `vim.inspect` - `vim.diff` - most utility functions in `vim.*` for working with pure lua values @@ -656,14 +591,14 @@ vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts}) Apply highlight group to range of text. Parameters: ~ - {bufnr} buffer number - {ns} namespace for highlights - {hlgroup} highlight group name - {start} starting position (tuple {line,col}) - {finish} finish position (tuple {line,col}) - {opts} optional parameters: + • {bufnr} buffer number + • {ns} namespace for highlights + • {hlgroup} highlight group name + • {start} starting position (tuple {line,col}) + • {finish} finish position (tuple {line,col}) + • {opts} optional parameters: • `regtype`: type of range (characterwise, linewise, - or blockwise, see |setreg|), default `'v'` + or blockwise, see |setreg()|), default `'v'` • `inclusive`: range includes end position, default `false` • `priority`: priority of highlight, default @@ -714,22 +649,22 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* Examples: > vim.diff('a\n', 'b\nc\n') - --> + => @@ -1 +1,2 @@ -a +b +c vim.diff('a\n', 'b\nc\n', {result_type = 'indices'}) - --> + => { {1, 1, 1, 2} } < Parameters: ~ - {a} First string to compare - {b} Second string to compare - {opts} Optional parameters: + • {a} First string to compare + • {b} Second string to compare + • {opts} Optional parameters: • `on_hunk` (callback): Invoked for each hunk in the diff. Return a negative number to cancel the callback for any remaining hunks. @@ -795,13 +730,13 @@ vim.spell.check({str}) *vim.spell.check()* Example: > vim.spell.check("the quik brown fox") - --> + => { {'quik', 'bad', 4} } < Parameters: ~ - {str} String to spell check. + • {str} String to spell check. Return: ~ List of tuples with three items: @@ -881,6 +816,22 @@ vim.str_byteindex({str}, {index} [, {use_utf16}]) *vim.str_byteindex()* An {index} in the middle of a UTF-16 sequence is rounded upwards to the end of that sequence. +vim.iconv({str}, {from}, {to}[, {opts}]) *vim.iconv()* + The result is a String, which is the text {str} converted from + encoding {from} to encoding {to}. When the conversion fails `nil` is + returned. When some characters could not be converted they + are replaced with "?". + The encoding names are whatever the iconv() library function + can accept, see ":Man 3 iconv". + + Parameters: ~ + • {str} (string) Text to convert + • {from} (string) Encoding of {str} + • {to} (string) Target encoding + + Returns: ~ + Converted string if conversion succeeds, `nil` otherwise. + vim.schedule({callback}) *vim.schedule()* Schedules {callback} to be invoked soon by the main event-loop. Useful to avoid |textlock| or other temporary restrictions. @@ -890,12 +841,12 @@ vim.defer_fn({fn}, {timeout}) *vim.defer_fn* Defers calling {fn} until {timeout} ms passes. Use to do a one-shot timer that calls {fn}. - Note: The {fn} is |schedule_wrap|ped automatically, so API functions are + Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are safe to call. Parameters: ~ - {fn} Callback to call once {timeout} expires - {timeout} Time in ms to wait before calling {fn} + • {fn} Callback to call once {timeout} expires + • {timeout} Time in ms to wait before calling {fn} Returns: ~ |vim.loop|.new_timer() object @@ -908,10 +859,10 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* this time. Parameters: ~ - {time} Number of milliseconds to wait - {callback} Optional callback. Waits until {callback} returns true - {interval} (Approximate) number of milliseconds to wait between polls - {fast_only} If true, only |api-fast| events will be processed. + • {time} Number of milliseconds to wait + • {callback} Optional callback. Waits until {callback} returns true + • {interval} (Approximate) number of milliseconds to wait between polls + • {fast_only} If true, only |api-fast| events will be processed. If called from while in an |api-fast| event, will automatically be set to `true`. @@ -951,6 +902,43 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* end < +vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* + Attach to ui events, similar to |nvim_ui_attach()| but receive events + as lua callback. Can be used to implement screen elements like + popupmenu or message handling in lua. + + {options} should be a dictionary-like table, where `ext_...` options should + be set to true to receive events for the respective external element. + + {callback} receives event name plus additional parameters. See |ui-popupmenu| + and the sections below for event format for respective events. + + WARNING: This api is considered experimental. Usability will vary for + different screen elements. In particular `ext_messages` behavior is subject + to further changes and usability improvements. This is expected to be + used to handle messages when setting 'cmdheight' to zero (which is + likewise experimental). + + Example (stub for a |ui-popupmenu| implementation): > + + ns = vim.api.nvim_create_namespace('my_fancy_pum') + + vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...) + if event == "popupmenu_show" then + local items, selected, row, col, grid = ... + print("display pum ", #items) + elseif event == "popupmenu_select" then + local selected = ... + print("selected", selected) + elseif event == "popupmenu_hide" then + print("FIN") + end + end) + +vim.ui_detach({ns}) *vim.ui_detach()* + Detach a callback previously attached with |vim.ui_attach()| for the + given namespace {ns}. + vim.type_idx *vim.type_idx* Type index for use in |lua-special-tbl|. Specifying one of the values from |vim.types| allows typing the empty table (it is unclear whether empty Lua @@ -1000,6 +988,7 @@ LUA-VIMSCRIPT BRIDGE *lua-vimscript* Nvim Lua provides an interface to Vimscript variables and functions, and editor commands and options. + See also https://github.com/nanotee/nvim-lua-guide. vim.call({func}, {...}) *vim.call()* @@ -1043,6 +1032,20 @@ Example: > vim.g.foo = nil -- Delete (:unlet) the Vimscript variable. vim.b[2].foo = 6 -- Set b:foo for buffer 2 < + +Note that setting dictionary fields directly will not write them back into +Nvim. This is because the index into the namespace simply returns a copy. +Instead the whole dictionary must be written as one. This can be achieved by +creating a short-lived temporary. + +Example: > + + vim.g.my_dict.field1 = 'value' -- Does not work + + local my_dict = vim.g.my_dict -- + my_dict.field1 = 'value' -- Instead do + vim.g.my_dict = my_dict -- + vim.g *vim.g* Global (|g:|) editor variables. Key with no value returns `nil`. @@ -1075,81 +1078,149 @@ vim.env *vim.env* print(vim.env.TERM) < + *lua-options* *lua-vim-options* - *lua-vim-opt* *lua-vim-set* - *lua-vim-optlocal* *lua-vim-setlocal* -In Vimscript, there is a way to set options |set-option|. In Lua, the -corresponding method is `vim.opt`. - -`vim.opt` provides several conveniences for setting and controlling options -from within Lua. +Vim options can be accessed through |vim.o|, which behaves like Vimscript +|:set|. Examples: ~ To set a boolean toggle: - In Vimscript: - `set number` + Vimscript: `set number` + Lua: `vim.o.number = true` + + To set a string value: + Vimscript: `set wildignore=*.o,*.a,__pycache__` + Lua: `vim.o.wildignore = '*.o,*.a,__pycache__'` + +Similarly, there is |vim.bo| and |vim.wo| for setting buffer-scoped and +window-scoped options. Note that this must NOT be confused with +|local-options| and |:setlocal|. There is also |vim.go| that only accesses the +global value of a |global-local| option, see |:setglobal|. + +vim.o *vim.o* + Get or set |options|. Like `:set`. Invalid key is an error. - In Lua: - `vim.opt.number = true` + Note: this works on both buffer-scoped and window-scoped options using the + current buffer and window. + + Example: > + vim.o.cmdheight = 4 + print(vim.o.columns) + print(vim.o.foo) -- error: invalid key +< +vim.go *vim.go* + Get or set global |options|. Like `:setglobal`. Invalid key is + an error. - To set an array of values: + Note: this is different from |vim.o| because this accesses the global + option value and thus is mostly useful for use with |global-local| + options. + + Example: > + vim.go.cmdheight = 4 + print(vim.go.columns) + print(vim.go.bar) -- error: invalid key +< +vim.bo[{bufnr}] *vim.bo* + Get or set buffer-scoped |options| for the buffer with number {bufnr}. + Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current + buffer is used. Invalid {bufnr} or key is an error. + + Note: this is equivalent to both `:set` and `:setlocal`. + + Example: > + local bufnr = vim.api.nvim_get_current_buf() + vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true + print(vim.bo.comments) + print(vim.bo.baz) -- error: invalid key +< +vim.wo[{winid}] *vim.wo* + Get or set window-scoped |options| for the window with handle {winid}. + Like `:set`. If [{winid}] is omitted then the current window is used. + Invalid {winid} or key is an error. + + Note: this does not access |local-options| (`:setlocal`) instead use: > + nvim_get_option_value(OPTION, { scope = 'local', win = winid }) + nvim_set_option_value(OPTION, VALUE, { scope = 'local', win = winid } +< + Example: > + local winid = vim.api.nvim_get_current_win() + vim.wo[winid].number = true -- same as vim.wo.number = true + print(vim.wo.foldmarker) + print(vim.wo.quux) -- error: invalid key +< + + + + *lua-vim-opt* + *lua-vim-optlocal* + *lua-vim-optglobal* + *vim.opt* + + +A special interface |vim.opt| exists for conveniently interacting with list- +and map-style option from Lua: It allows accessing them as Lua tables and +offers object-oriented method for adding and removing entries. + + Examples: ~ + + The following methods of setting a list-style option are equivalent: In Vimscript: `set wildignore=*.o,*.a,__pycache__` - In Lua, there are two ways you can do this now. One is very similar to - the Vimscript form: - `vim.opt.wildignore = '*.o,*.a,__pycache__'` + In Lua using `vim.o`: + `vim.o.wildignore = '*.o,*.a,__pycache__'` - However, vim.opt also supports a more elegent way of setting - list-style options by using lua tables: + In Lua using `vim.opt`: `vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }` To replicate the behavior of |:set+=|, use: > - -- vim.opt supports appending options via the "+" operator - vim.opt.wildignore = vim.opt.wildignore + { "*.pyc", "node_modules" } - - -- or using the `:append(...)` method vim.opt.wildignore:append { "*.pyc", "node_modules" } < To replicate the behavior of |:set^=|, use: > - -- vim.opt supports prepending options via the "^" operator - vim.opt.wildignore = vim.opt.wildignore ^ { "new_first_value" } - - -- or using the `:prepend(...)` method vim.opt.wildignore:prepend { "new_first_value" } < To replicate the behavior of |:set-=|, use: > - -- vim.opt supports removing options via the "-" operator - vim.opt.wildignore = vim.opt.wildignore - { "node_modules" } - - -- or using the `:remove(...)` method vim.opt.wildignore:remove { "node_modules" } < - To set a map of values: + The following methods of setting a map-style option are equivalent: In Vimscript: `set listchars=space:_,tab:>~` - In Lua: + In Lua using `vim.o`: + `vim.o.listchars = 'space:_,tab:>~'` + + In Lua using `vim.opt`: `vim.opt.listchars = { space = '_', tab = '>~' }` -In any of the above examples, to replicate the behavior |setlocal|, use -`vim.opt_local`. Additionally, to replicate the behavior of |setglobal|, use -`vim.opt_global`. - *vim.opt* +Note that |vim.opt| returns an `Option` object, not the value of the option, +which is accessed through |vim.opt:get()|: -|vim.opt| returns an Option object. + Examples: ~ -For example: `local listchar_object = vim.opt.listchars` + The following methods of getting a list-style option are equivalent: + In Vimscript: + `echo wildignore` + + In Lua using `vim.o`: + `print(vim.o.wildignore)` + + In Lua using `vim.opt`: + `vim.pretty_print(vim.opt.wildignore:get())` + + +In any of the above examples, to replicate the behavior |:setlocal|, use +`vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use +`vim.opt_global`. -An `Option` has the following methods: *vim.opt:get()* @@ -1162,7 +1233,7 @@ Option:get() the values as entries in the array: > vim.cmd [[set wildignore=*.pyc,*.o]] - print(vim.inspect(vim.opt.wildignore:get())) + vim.pretty_print(vim.opt.wildignore:get()) -- { "*.pyc", "*.o", } for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do @@ -1175,18 +1246,18 @@ Option:get() the names as keys and the values as entries: > vim.cmd [[set listchars=space:_,tab:>~]] - print(vim.inspect(vim.opt.listchars:get())) + vim.pretty_print(vim.opt.listchars:get()) -- { space = "_", tab = ">~", } for char, representation in pairs(vim.opt.listchars:get()) do - print(char, "->", representation) + print(char, "=>", representation) end < For values that are lists of flags, a set will be returned with the flags as keys and `true` as entries. > vim.cmd [[set formatoptions=njtcroql]] - print(vim.inspect(vim.opt.formatoptions:get())) + vim.pretty_print(vim.opt.formatoptions:get()) -- { n = true, j = true, c = true, ... } local format_opts = vim.opt.formatoptions:get() @@ -1222,71 +1293,6 @@ Option:remove(value) `vim.opt.wildignore = vim.opt.wildignore - '*.pyc'` -In general, using `vim.opt` will provide the expected result when the user is -used to interacting with editor |options| via `set`. There are still times -where the user may want to set particular options via a shorthand in Lua, -which is where |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| come into play. - -The behavior of |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| is designed to -follow that of |:set|, |:setlocal|, and |:setglobal| which can be seen in the -table below: - - lua command global_value local_value ~ -vim.o :set set set -vim.bo/vim.wo :setlocal - set -vim.go :setglobal set - - -vim.o *vim.o* - Get or set editor options, like |:set|. Invalid key is an error. - - Example: > - vim.o.cmdheight = 4 - print(vim.o.columns) - print(vim.o.foo) -- error: invalid key -< -vim.go *vim.go* - Get or set an |option|. Invalid key is an error. - - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()|. - - NOTE: This is different from |vim.o| because this ONLY sets the global - option, which generally produces confusing behavior for options with - |global-local| values. - - Example: > - vim.go.cmdheight = 4 - print(vim.go.columns) - print(vim.go.bar) -- error: invalid key -< -vim.bo[{bufnr}] *vim.bo* - Get or set buffer-scoped |local-options| for the buffer with number {bufnr}. - If [{bufnr}] is omitted, use the current buffer. Invalid {bufnr} or key is - an error. - - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()| with `opts = {scope = local, buf = bufnr}` . - - Example: > - local bufnr = vim.api.nvim_get_current_buf() - vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true - print(vim.bo.comments) - print(vim.bo.baz) -- error: invalid key -< -vim.wo[{winid}] *vim.wo* - Get or set window-scoped |local-options| for the window with handle {winid}. - If [{winid}] is omitted, use the current window. Invalid {winid} or key - is an error. - - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()| with `opts = {scope = local, win = winid}` . - - Example: > - local winid = vim.api.nvim_get_current_win() - vim.wo[winid].number = true -- same as vim.wo.number = true - print(vim.wo.foldmarker) - print(vim.wo.quux) -- error: invalid key -< ============================================================================== Lua module: vim *lua-vim* @@ -1325,7 +1331,7 @@ cmd({command}) *vim.cmd()* < Parameters: ~ - {command} string|table Command(s) to execute. If a string, executes + • {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_exec()|, where `output` is set to false. Thus it works identical to |:source|. If a table, executes @@ -1342,31 +1348,31 @@ connection_failure_errmsg({consequence}) defer_fn({fn}, {timeout}) *vim.defer_fn()* Defers calling `fn` until `timeout` ms passes. - Use to do a one-shot timer that calls `fn` Note: The {fn} is |schedule_wrap|ped automatically, so API functions are - safe to call. + Use to do a one-shot timer that calls `fn` Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions + are safe to call. Parameters: ~ - {fn} Callback to call once `timeout` expires - {timeout} Number of milliseconds to wait before calling `fn` + • {fn} (function) Callback to call once `timeout` expires + • {timeout} integer Number of milliseconds to wait before calling `fn` Return: ~ - timer luv timer object + (table) timer luv timer object *vim.deprecate()* deprecate({name}, {alternative}, {version}, {plugin}, {backtrace}) Display a deprecation notification to the user. Parameters: ~ - {name} string Deprecated function. - {alternative} (string|nil) Preferred alternative function. - {version} string Version in which the deprecated function will be + • {name} string Deprecated function. + • {alternative} (string|nil) Preferred alternative function. + • {version} string Version in which the deprecated function will be removed. - {plugin} string|nil Plugin name that the function will be + • {plugin} string|nil Plugin name that the function will be removed from. Defaults to "Nvim". - {backtrace} boolean|nil Prints backtrace. Defaults to true. + • {backtrace} boolean|nil Prints backtrace. Defaults to true. inspect({object}, {options}) *vim.inspect()* - Return a human-readable representation of the given object. + Gets a human-readable representation of the given object. See also: ~ https://github.com/kikito/inspect.lua @@ -1380,9 +1386,9 @@ notify({msg}, {level}, {opts}) *vim.notify()* writes to |:messages|. Parameters: ~ - {msg} (string) Content of the notification to show to the user. - {level} (number|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} (number|nil) One of the values from |vim.log.levels|. + • {opts} (table|nil) Optional parameters. Unused by default. notify_once({msg}, {level}, {opts}) *vim.notify_once()* Display a notification only one time. @@ -1391,9 +1397,9 @@ notify_once({msg}, {level}, {opts}) *vim.notify_once()* display a notification. Parameters: ~ - {msg} (string) Content of the notification to show to the user. - {level} (number|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} (number|nil) One of the values from |vim.log.levels|. + • {opts} (table|nil) Optional parameters. Unused by default. Return: ~ (boolean) true if message was displayed, else false @@ -1412,11 +1418,11 @@ on_key({fn}, {ns_id}) *vim.on_key()* {fn} will receive the keys after mappings have been evaluated Parameters: ~ - {fn} function: Callback function. It should take one string + • {fn} (function) Callback function. It should take one string argument. On each key press, Nvim passes the key char to fn(). |i_CTRL-V| If {fn} is nil, it removes the callback for the associated {ns_id} - {ns_id} number? Namespace ID. If nil or 0, generates and returns a + • {ns_id} number? Namespace ID. If nil or 0, generates and returns a new |nvim_create_namespace()| id. Return: ~ @@ -1444,18 +1450,19 @@ paste({lines}, {phase}) *vim.paste()* < Parameters: ~ - {lines} |readfile()|-style list of lines to paste. |channel-lines| - {phase} -1: "non-streaming" paste: the call contains all lines. If - paste is "streamed", `phase` indicates the stream state: + • {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: • 1: starts the paste (exactly once) • 2: continues the paste (zero or more times) • 3: ends the paste (exactly once) Return: ~ - false if client should cancel the paste. + (boolean) # false if client should cancel the paste. See also: ~ - |paste| + |paste| @alias paste_phase -1 | 1 | 2 | 3 pretty_print({...}) *vim.pretty_print()* Prints given arguments in human-readable format. Example: > @@ -1464,7 +1471,7 @@ pretty_print({...}) *vim.pretty_print()* < Return: ~ - given arguments. + any # given arguments. See also: ~ |vim.inspect()| @@ -1474,19 +1481,27 @@ region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) *vim.region()* points Parameters: ~ - {bufnr} (number) of buffer - {pos1} (line, column) tuple marking beginning of region - {pos2} (line, column) tuple marking end of region - {regtype} type of selection (:help setreg) - {inclusive} (boolean) indicating whether the selection is + • {bufnr} (number) of buffer + • {pos1} integer[] (line, column) tuple marking beginning of + region + • {pos2} integer[] (line, column) tuple marking end of region + • {regtype} (string) type of selection, see |setreg()| + • {inclusive} (boolean) indicating whether the selection is end-inclusive Return: ~ - region lua table of the form {linenr = {startcol,endcol}} + table<integer, {}> region lua table of the form {linenr = + {startcol,endcol}} schedule_wrap({cb}) *vim.schedule_wrap()* Defers callback `cb` until the Nvim API is safe to call. + Parameters: ~ + • {cb} (function) + + Return: ~ + (function) + See also: ~ |lua-loop-callbacks| |vim.schedule()| @@ -1501,8 +1516,8 @@ deep_equal({a}, {b}) *vim.deep_equal()* 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` @@ -1515,17 +1530,39 @@ deepcopy({orig}) *vim.deepcopy()* not copied and will throw an error. Parameters: ~ - {orig} (table) Table to copy + • {orig} (table) Table to copy Return: ~ (table) Table of copied keys and (nested) values. +defaulttable({create}) *vim.defaulttable()* + Creates a table whose members are automatically created when accessed, if + they don't already exist. + + They mimic defaultdict in python. + + If {create} is `nil`, this will create a defaulttable whose constructor + function is this function, effectively allowing to create nested tables on + the fly: +> + + local a = vim.defaulttable() + a.b.c = 1 +< + + Parameters: ~ + • {create} (function|nil) The function called to create a missing + value. + + Return: ~ + (table) Empty table with metamethod + 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` @@ -1534,9 +1571,9 @@ gsplit({s}, {sep}, {plain}) *vim.gsplit()* Splits a string at each instance of a separator. Parameters: ~ - {s} (string) String to split - {sep} (string) Separator or pattern - {plain} (boolean) If `true` use `sep` literally (passed to + • {s} (string) String to split + • {sep} (string) Separator or pattern + • {plain} (boolean) If `true` use `sep` literally (passed to string.find) Return: ~ @@ -1551,7 +1588,7 @@ 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` @@ -1562,10 +1599,10 @@ 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} (number) Start index on src. Defaults to 1 - {finish} (number) 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} (number|nil) Start index on src. Defaults to 1 + • {finish} (number|nil) Final index on src. Defaults to `#src` Return: ~ (table) dst @@ -1578,18 +1615,18 @@ list_slice({list}, {start}, {finish}) *vim.list_slice()* (inclusive) Parameters: ~ - {list} (table) Table - {start} (number) Start range of slice - {finish} (number) End range of slice + • {list} (list) Table + • {start} (number) Start range of slice + • {finish} (number) End range of slice Return: ~ - (table) Copy of table sliced from start to finish (inclusive) + (list) Copy of table sliced from start to finish (inclusive) 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 @@ -1602,33 +1639,35 @@ split({s}, {sep}, {kwargs}) *vim.split()* Examples: > - split(":aa::b:", ":") --> {'','aa','','b',''} - split("axaby", "ab?") --> {'','x','y'} - split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} - split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} + split(":aa::b:", ":") => {'','aa','','b',''} + split("axaby", "ab?") => {'','x','y'} + split("x*yz*o", "*", {plain=true}) => {'x','yz','o'} + split("|x|y|z|", "|", {trimempty=true}) => {'x', 'y', 'z'} < + @alias split_kwargs {plain: boolean, trimempty: boolean} | boolean | nil + + See also: ~ + |vim.gsplit()| + Parameters: ~ - {s} (string) String to split - {sep} (string) Separator or pattern - {kwargs} (table) Keyword arguments: + • {s} (string) String to split + • {sep} (string) Separator or pattern + • {kwargs} (table|nil) Keyword arguments: • plain: (boolean) If `true` use `sep` literally (passed to string.find) • trimempty: (boolean) If `true` remove empty items from the front and back of the list Return: ~ - (table) List of split components - - See also: ~ - |vim.gsplit()| + string[] List of split components 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` @@ -1640,7 +1679,7 @@ 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 @@ -1649,8 +1688,8 @@ tbl_contains({t}, {value}) *vim.tbl_contains()* Checks if a list-like (vector) table contains `value`. Parameters: ~ - {t} (table) Table to check - {value} any Value to compare + • {t} (table) Table to check + • {value} any Value to compare Return: ~ (boolean) `true` if `t` contains `value` @@ -1664,7 +1703,7 @@ tbl_count({t}) *vim.tbl_count()* < Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ (number) Number of non-nil values in table @@ -1676,29 +1715,29 @@ tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()* Merges recursively two or more map-like tables. Parameters: ~ - {behavior} (string) Decides what to do if a key is found in more than + • {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 map-like tables + • {...} (table) Two or more map-like tables Return: ~ (table) Merged table See also: ~ - |tbl_extend()| + |vim.tbl_extend()| tbl_extend({behavior}, {...}) *vim.tbl_extend()* Merges two or more map-like tables. Parameters: ~ - {behavior} (string) Decides what to do if a key is found in more than + • {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 map-like tables + • {...} (table) Two or more map-like tables Return: ~ (table) Merged table @@ -1710,8 +1749,8 @@ tbl_filter({func}, {t}) *vim.tbl_filter()* Filter a table using a predicate function Parameters: ~ - {func} function|table Function or callable table - {t} (table) Table + • {func} (function) Function + • {t} (table) Table Return: ~ (table) Table of filtered values @@ -1721,7 +1760,7 @@ tbl_flatten({t}) *vim.tbl_flatten()* "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 @@ -1740,8 +1779,8 @@ tbl_get({o}, {...}) *vim.tbl_get()* < Parameters: ~ - {o} (table) Table to index - {...} (string) Optional strings (0 or more, variadic) via which to + • {o} (table) Table to index + • {...} (string) Optional strings (0 or more, variadic) via which to index the table Return: ~ @@ -1751,7 +1790,7 @@ 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 @@ -1767,7 +1806,7 @@ tbl_islist({t}) *vim.tbl_islist()* for example from |rpcrequest()| or |vim.fn|. Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ (boolean) `true` if array-like table, else `false` @@ -1777,10 +1816,10 @@ tbl_keys({t}) *vim.tbl_keys()* return table of keys is not guaranteed. Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ - (table) List of keys + (list) List of keys See also: ~ From https://github.com/premake/premake-core/blob/master/src/base/table.lua @@ -1789,8 +1828,8 @@ tbl_map({func}, {t}) *vim.tbl_map()* Apply a function to all values of a table. Parameters: ~ - {func} function|table Function or callable table - {t} (table) Table + • {func} (function) Function + • {t} (table) Table Return: ~ (table) Table of transformed values @@ -1800,16 +1839,16 @@ tbl_values({t}) *vim.tbl_values()* return table of values is not guaranteed. Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ - (table) List of values + (list) List of values 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 @@ -1854,7 +1893,7 @@ 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 @@ -1879,7 +1918,7 @@ uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()* Get a URI from a bufnr Parameters: ~ - {bufnr} (number) + • {bufnr} (number) Return: ~ (string) URI @@ -1888,7 +1927,7 @@ uri_from_fname({path}) *vim.uri_from_fname()* Get a URI from a file path. Parameters: ~ - {path} (string) Path to file + • {path} (string) Path to file Return: ~ (string) URI @@ -1898,7 +1937,7 @@ uri_to_bufnr({uri}) *vim.uri_to_bufnr()* the uri already exists. Parameters: ~ - {uri} (string) + • {uri} (string) Return: ~ (number) bufnr @@ -1907,7 +1946,7 @@ uri_to_fname({uri}) *vim.uri_to_fname()* Get a filename from a URI Parameters: ~ - {uri} (string) + • {uri} (string) Return: ~ (string) filename or unchanged URI for non-file URIs @@ -1927,7 +1966,7 @@ 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 @@ -1936,7 +1975,7 @@ 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. `nil` if the user aborted the dialog. @@ -1960,8 +1999,8 @@ 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 @@ -1971,7 +2010,7 @@ 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. @@ -1999,7 +2038,10 @@ add({filetypes}) *vim.filetype.add()* Filename patterns can specify an optional priority to resolve cases when a file path matches multiple patterns. Higher priorities are matched first. - When omitted, the priority defaults to 0. + When omitted, the priority defaults to 0. A pattern can contain + environment variables of the form "${SOME_VAR}" that will be automatically + expanded. If the environment variable is not set, the pattern won't be + matched. See $VIMRUNTIME/lua/vim/filetype.lua for more examples. @@ -2029,6 +2071,8 @@ add({filetypes}) *vim.filetype.add()* ['.*/etc/foo/.*'] = 'fooscript', -- Using an optional priority ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, + -- A pattern containing an environment variable + ['${XDG_CONFIG_HOME}/foo/git'] = 'git', ['README.(a+)$'] = function(path, bufnr, ext) if ext == 'md' then return 'markdown' @@ -2060,7 +2104,7 @@ 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). match({args}) *vim.filetype.match()* @@ -2095,7 +2139,7 @@ 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} @@ -2129,7 +2173,7 @@ del({modes}, {lhs}, {opts}) *vim.keymap.del()* < Parameters: ~ - {opts} (table) A table of optional arguments: + • {opts} (table|nil) A table of optional arguments: • buffer: (number or boolean) Remove a mapping from the given buffer. When "true" or 0, use the current buffer. @@ -2169,12 +2213,12 @@ set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* < Parameters: ~ - {mode} string|table Same mode short names as |nvim_set_keymap()|. Can + • {mode} string|table Same mode short names as |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 + • {lhs} (string) Left-hand side |{lhs}| of the mapping. + • {rhs} string|function Right-hand side |{rhs}| of the mapping. Can also be a Lua function. - {opts} (table) A table of |:map-arguments|. + • {opts} (table|nil) A table of |:map-arguments|. • Accepts options accepted by the {opts} parameter in |nvim_set_keymap()|, with the following notable differences: • replace_keycodes: Defaults to `true` if "expr" is `true`. @@ -2200,7 +2244,7 @@ basename({file}) *vim.fs.basename()* Return the basename of the given file or directory Parameters: ~ - {file} (string) File or directory + • {file} (string) File or directory Return: ~ (string) Basename of {file} @@ -2209,7 +2253,7 @@ dir({path}) *vim.fs.dir()* Return an iterator over the files and directories 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()|. @@ -2222,7 +2266,7 @@ dirname({file}) *vim.fs.dirname()* Return the parent directory of the given file or directory Parameters: ~ - {file} (string) File or directory + • {file} (string) File or directory Return: ~ (string) Parent directory of {file} @@ -2240,9 +2284,11 @@ find({names}, {opts}) *vim.fs.find()* specifying {type} to be "file" or "directory", respectively. Parameters: ~ - {names} (string|table) Names of the files and directories to find. - Must be base names, paths and globs are not supported. - {opts} (table) Optional keyword arguments: + • {names} (string|table|fun(name: string): boolean) Names of the files + and directories to find. Must be base names, paths and globs + are not supported. If a function it is called per file and + dir within the traversed directories to test if they match. + • {opts} (table) Optional keyword arguments: • path (string): Path to begin searching from. If omitted, the current working directory is used. • upward (boolean, default false): If true, search upward @@ -2279,7 +2325,7 @@ normalize({path}) *vim.fs.normalize()* < Parameters: ~ - {path} (string) Path to normalize + • {path} (string) Path to normalize Return: ~ (string) Normalized path @@ -2303,7 +2349,7 @@ parents({start}) *vim.fs.parents()* < Parameters: ~ - {start} (string) Initial file or directory. + • {start} (string) Initial file or directory. Return: ~ (function) Iterator diff --git a/runtime/doc/luaref.txt b/runtime/doc/luaref.txt index 9dbd2d4de5..ffbb405804 100644 --- a/runtime/doc/luaref.txt +++ b/runtime/doc/luaref.txt @@ -20,76 +20,10 @@ See |luaref-copyright| for copyright and licenses. - CONTENTS - ============ - - 1 INTRODUCTION........................|luaref-intro| - - 2 THE LANGUAGE........................|luaref-language| - 2.1 Lexical Conventions...............|luaref-langLexConv| - 2.2 Values and Types..................|luaref-langValTypes| - 2.2.1 Coercion........................|luaref-langCoercion| - 2.3 Variables.........................|luaref-langVariables| - 2.4 Statements........................|luaref-langStats| - 2.4.1 Chunks..........................|luaref-langChunks| - 2.4.2 Blocks..........................|luaref-langBlocks| - 2.4.3 Assignment......................|luaref-langAssign| - 2.4.4 Control Structures..............|luaref-langContStructs| - 2.4.5 For Statement...................|luaref-langForStat| - 2.4.6 Function Calls as Statements....|luaref-langFuncStat| - 2.4.7 Local Declarations..............|luaref-langLocalDec| - 2.5 Expressions.......................|luaref-langExpressions| - 2.5.1 Arithmetic Operators............|luaref-langArithOp| - 2.5.2 Relational Operators............|luaref-langRelOp| - 2.5.3 Logical Operators...............|luaref-langLogOp| - 2.5.4 Concatenation...................|luaref-langConcat| - 2.5.5 The Length Operator.............|luaref-langLength| - 2.5.6 Precedence......................|luaref-langPrec| - 2.5.7 Table Constructors..............|luaref-langTableConst| - 2.5.8 Function Calls..................|luaref-langFuncCalls| - 2.5.9 Function Definitions............|luaref-langFuncDefs| - 2.6 Visibility Rules..................|luaref-langVisibRules| - 2.7 Error Handling....................|luaref-langError| - 2.8 Metatables........................|luaref-langMetatables| - 2.9 Environments......................|luaref-langEnvironments| - 2.10 Garbage Collection...............|luaref-langGC| - 2.10.1 Garbage-Collection Metamethods.|luaref-langGCMeta| - 2.10.2 Weak Tables....................|luaref-langWeaktables| - 2.11 Coroutines.......................|luaref-langCoro| - - 3 THE APPLICATION PROGRAM INTERFACE...|luaref-api| - 3.1 The Stack.........................|luaref-apiStack| - 3.2 Stack Size........................|luaref-apiStackSize| - 3.3 Pseudo-Indices....................|luaref-apiPseudoIndices| - 3.4 C Closures........................|luaref-apiCClosures| - 3.5 Registry..........................|luaref-apiRegistry| - 3.6 Error Handling in C...............|luaref-apiError| - 3.7 Functions and Types...............|luaref-apiFunctions| - 3.8 The Debug Interface...............|luaref-apiDebug| - - 4 THE AUXILIARY LIBRARY...............|luaref-aux| - 4.1 Functions and Types...............|luaref-auxFunctions| - - 5 STANDARD LIBRARIES..................|luaref-lib| - 5.1 Basic Functions...................|luaref-libBasic| - 5.2 Coroutine Manipulation............|luaref-libCoro| - 5.3 Modules...........................|luaref-libModule| - 5.4 String Manipulation...............|luaref-libString| - 5.4.1 Patterns........................|luaref-libStringPat| - 5.5 Table Manipulation................|luaref-libTable| - 5.6 Mathematical Functions............|luaref-libMath| - 5.7 Input and Output Facilities.......|luaref-libIO| - 5.8 Operating System Facilities.......|luaref-libOS| - 5.9 The Debug Library.................|luaref-libDebug| - - A BIBLIOGRAPHY........................|luaref-bibliography| - B COPYRIGHT & LICENSES................|luaref-copyright| - C LUAREF DOC..........................|luaref-doc| - +Type |gO| to see the table of contents. ============================================================================== 1 INTRODUCTION *luaref-intro* -============================================================================== Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good @@ -120,14 +54,13 @@ Lua means "moon" in Portuguese and is pronounced LOO-ah. ============================================================================== 2 THE LANGUAGE *luaref-language* -============================================================================== This section describes the lexis, the syntax, and the semantics of Lua. In other words, this section describes which tokens are valid, how they can be combined, and what their combinations mean. The language constructs will be explained using the usual extended BNF -notation, in which { `a` } means 0 or more `a`'s, and [ `a` ] means an optional `a`. +notation, in which `{ a }` means 0 or more `a`'s, and `[ a ]` means an optional `a`. ============================================================================== 2.1 Lexical Conventions *luaref-langLexConv* @@ -292,7 +225,7 @@ parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy. The library function `type` returns a string describing the type of a given -value (see |luaref-type|). +value (see |luaref-type()|). ------------------------------------------------------------------------------ 2.2.1 Coercion *luaref-langCoercion* @@ -303,7 +236,7 @@ string to a number, following the usual conversion rules. Conversely, whenever a number is used where a string is expected, the number is converted to a string, in a reasonable format. For complete control of how numbers are converted to strings, use the `format` function from the string library (see -|luaref-string.format|). +|string.format()|). ============================================================================== 2.3 Variables *luaref-langVariables* @@ -344,7 +277,7 @@ has its own reference to an environment, so that all global variables in this function will refer to this environment table. When a function is created, it inherits the environment from the function that created it. To get the environment table of a Lua function, you call `getfenv` (see -|luaref-getfenv|). To replace it, you call `setfenv` (see |luaref-setfenv|). +|lua_getfenv()|). To replace it, you call `setfenv` (see |luaref-setfenv()|). (You can only manipulate the environment of C functions through the debug library; see |luaref-libDebug|.) @@ -515,21 +448,22 @@ through an arithmetic progression. It has the following syntax: < The `block` is repeated for `name` starting at the value of the first `exp`, until it passes the second `exp` by steps of the third `exp`. More precisely, -a `for` statement like +a `for` statement like > - `for var =` `e1, e2, e3` `do` `block` `end` + for var = e1, e2, e3 do block end -is equivalent to the code: +< is equivalent to the code: > - `do` - `local` `var, limit, step` `= tonumber(e1), tonumber(e2), tonumber(e3)` - `if not (` `var` `and` `limit` `and` `step` `) then error() end` - `while (` `step` `>0 and` `var` `<=` `limit` `)` - `or (` `step` `<=0 and` `var` `>=` `limit` `) do` - `block` - `var` `=` `var` `+` `step` - `end` - `end` + do + local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3) + if not ( var and limit and step ) then error() end + while ( step >0 and var <= limit ) + or ( step <=0 and var >= limit ) do + block + var = var + step + end + end +< Note the following: @@ -555,18 +489,18 @@ A `for` statement like `for` `var1, ..., varn` `in` `explist` `do` `block` `end` -is equivalent to the code: - - `do` - `local` `f, s, var` `=` `explist` - `while true do` - `local` `var1, ..., varn` `=` `f(s, var)` - `var` `=` `var1` - `if` `var` `== nil then break end` - `block` - `end` - `end` +is equivalent to the code: > + do + local f, s, var = explist + while true do + local var1, ..., varn = f(s, var) + var = var1 + if var == nil then break end + block + end + end +< Note the following: - `explist` is evaluated only once. Its results are an iterator function, @@ -634,7 +568,7 @@ they are explained in |luaref-langFuncDefs|. Binary operators comprise arithmetic operators (see |luaref-langArithOp|), relational operators (see |luaref-langRelOp|), logical operators (see |luaref-langLogOp|), and the concatenation operator (see |luaref-langConcat|). -Unary operators comprise the unary minus (see |luaref-labgArithOp|), the unary +Unary operators comprise the unary minus (see |luaref-langArithOp|), the unary `not` (see |luaref-langLogOp|), and the unary length operator (see |luaref-langLength|). @@ -1050,13 +984,13 @@ them share the same `x`. Because Lua is an embedded extension language, all Lua actions start from C code in the host program calling a function from the Lua library (see -|luaref-lua_pcall|). Whenever an error occurs during Lua compilation or +|lua_pcall()|). Whenever an error occurs during Lua compilation or execution, control returns to C, which can take appropriate measures (such as print an error message). Lua code can explicitly generate an error by calling the `error` function (see -|luaref-error|). If you need to catch errors in Lua, you can use -the `pcall` function (see |luaref-pcall|). +|luaref-error()|). If you need to catch errors in Lua, you can use +the `pcall` function (see |luaref-pcall()|). ============================================================================== 2.8 Metatables *luaref-metatable* *luaref-langMetatables* @@ -1074,10 +1008,10 @@ previous example, the event is "add" and the metamethod is the function that performs the addition. You can query the metatable of any value through the `getmetatable` function -(see |luaref-getmetatable|). +(see |luaref-getmetatable()|). You can replace the metatable of tables through the `setmetatable` function (see -|luaref-setmetatable|). You cannot change the metatable of other types from Lua +|luaref-setmetatable()|). You cannot change the metatable of other types from Lua (except using the debug library); you must use the C API for that. Tables and userdata have individual metatables (although multiple tables and @@ -1385,8 +1319,8 @@ convenience feature for programmers to associate a table to a userdata. Environments associated with threads are called global environments. They are used as the default environment for their threads and non-nested functions -created by the thread (through `loadfile` |luaref-loadfile|, `loadstring` -|luaref-loadstring| or `load` |luaref-load|) and can be directly accessed by C +created by the thread (through `loadfile` |luaref-loadfile()|, `loadstring` +|luaref-loadstring()| or `load` |luaref-load()|) and can be directly accessed by C code (see |luaref-apiPseudoIndices|). Environments associated with C functions can be directly accessed by C code @@ -1399,10 +1333,10 @@ used as the default environment for other Lua functions created by the function. You can change the environment of a Lua function or the running thread by -calling `setfenv` (see |luaref-setenv|). You can get the environment of a Lua -function or the running thread by calling `getfenv` (see |luaref-getfenv|). To -manipulate the environment of other objects (userdata, C functions, other -threads) you must use the C API. +calling `setfenv`. You can get the environment of a Lua function or the +running thread by calling `getfenv` (see |lua_getfenv()|). To manipulate the +environment of other objects (userdata, C functions, other threads) you must +use the C API. ============================================================================== 2.10 Garbage Collection *luaref-langGC* @@ -1432,8 +1366,8 @@ collector too slow and may result in the collector never finishing a cycle. The default, 2, means that the collector runs at "twice" the speed of memory allocation. -You can change these numbers by calling `lua_gc` (see |luaref-lua_gc|) in C or -`collectgarbage` (see |luaref-collectgarbage|) in Lua. Both get percentage +You can change these numbers by calling `lua_gc` (see |lua_gc()|) in C or +`collectgarbage` (see |luaref-collectgarbage()|) in Lua. Both get percentage points as arguments (so an argument of 100 means a real value of 1). With these functions you can also control the collector directly (e.g., stop and restart it). @@ -1496,12 +1430,12 @@ multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function. You create a coroutine with a call to `coroutine.create` (see -|luaref-coroutine.create|). Its sole argument is a function that is the main +|coroutine.create()|). Its sole argument is a function that is the main function of the coroutine. The `create` function only creates a new coroutine and returns a handle to it (an object of type `thread`); it does not start the coroutine execution. -When you first call `coroutine.resume` (see |luaref-coroutine.resume|), +When you first call `coroutine.resume` (see |coroutine.resume()|), passing as its first argument the thread returned by `coroutine.create`, the coroutine starts its execution, at the first line of its main function. Extra arguments passed to `coroutine.resume` are passed on to the coroutine main @@ -1516,7 +1450,7 @@ main function. In case of errors, `coroutine.resume` returns `false` plus an error message. A coroutine yields by calling `coroutine.yield` (see -|luaref-coroutine.yield|). When a coroutine yields, the corresponding +|coroutine.yield()|). When a coroutine yields, the corresponding `coroutine.resume` returns immediately, even if the yield happens inside nested function calls (that is, not in the main function, but in a function directly or indirectly called by the main function). In the case of a yield, @@ -1526,7 +1460,7 @@ its execution from the point where it yielded, with the call to `coroutine.yield` returning any extra arguments passed to `coroutine.resume`. Like `coroutine.create`, the `coroutine.wrap` function (see -|luaref-coroutine.wrap|) also creates a coroutine, but instead of returning +|coroutine.wrap()|) also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. Any arguments passed to this function go as extra arguments to `coroutine.resume`. `coroutine.wrap` returns all the values returned by @@ -1569,7 +1503,6 @@ When you run it, it produces the following output: ============================================================================== 3 THE APPLICATION PROGRAM INTERFACE *luaref-API* -============================================================================== This section describes the C API for Lua, that is, the set of C functions available to the host program to communicate with Lua. All API functions and @@ -1595,7 +1528,7 @@ Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active. This stack initially contains any arguments to the C function and it is where the C function pushes its results to be returned to the caller (see -|luaref-lua_CFunction|). +|lua_CFunction()|). *luaref-stackindex* For convenience, most query operations in the API do not follow a strict stack @@ -1615,7 +1548,7 @@ if `1 <= abs(index) <= top`). When you interact with Lua API, you are responsible for ensuring consistency. In particular, you are responsible for controlling stack overflow. You can use the function `lua_checkstack` to grow the stack size (see -|luaref-lua_checkstack|). +|lua_checkstack()|). Whenever Lua calls C, it ensures that at least `LUA_MINSTACK` stack positions are available. `LUA_MINSTACK` is defined as 20, so that usually you do not @@ -1656,14 +1589,14 @@ global variable, do When a C function is created, it is possible to associate some values with it, thus creating a C closure; these values are called upvalues and are accessible -to the function whenever it is called (see |luaref-lua_pushcclosure|). +to the function whenever it is called (see |lua_pushcclosure()|). Whenever a C function is called, its upvalues are located at specific pseudo-indices. These pseudo-indices are produced by the macro -`lua_upvalueindex` (see |luaref-lua_upvalueindex|). The first value associated -with a function is at position `lua_upvalueindex(1)`, and so on. Any access to -`lua_upvalueindex(` `n` `)`, where `n` is greater than the number of upvalues of -the current function, produces an acceptable (but invalid) index. +`lua_upvalueindex`. The first value associated with a function is at position +`lua_upvalueindex(1)`, and so on. Any access to `lua_upvalueindex(` `n` `)`, +where `n` is greater than the number of upvalues of the current function, +produces an acceptable (but invalid) index. ============================================================================== 3.5 Registry *luaref-registry* *luaref-apiRegistry* @@ -1694,11 +1627,11 @@ Almost any function in the API may raise an error, for instance due to a memory allocation error. The following functions run in protected mode (that is, they create a protected environment to run), so they never raise an error: `lua_newstate`, `lua_close`, `lua_load`, `lua_pcall`, and `lua_cpcall` (see -|luaref-lua_newstate|, |luaref-lua_close|, |luaref-lua_load|, -|luaref-lua_pcall|, and |luaref-lua_cpcall|). +|lua_newstate()|, |lua_close()|, |lua_load()|, +|lua_pcall()|, and |lua_cpcall()|). Inside a C function you can raise an error by calling `lua_error` (see -|luaref-lua_error|). +|lua_error()|). ============================================================================== 3.7 Functions and Types *luaref-apiFunctions* @@ -1715,7 +1648,7 @@ lua_Alloc *lua_Alloc()* The type of the memory-allocation function used by Lua states. The allocator function must provide a functionality similar to `realloc`, but not exactly the same. Its arguments are `ud`, an opaque pointer - passed to `lua_newstate` (see |luaref-lua_newstate|); `ptr`, a pointer + passed to `lua_newstate` (see |lua_newstate()|); `ptr`, a pointer to the block being allocated/reallocated/freed; `osize`, the original size of the block; `nsize`, the new size of the block. `ptr` is `NULL` if and only if `osize` is zero. When `nsize` is zero, the allocator @@ -1729,7 +1662,7 @@ lua_Alloc *lua_Alloc()* Here is a simple implementation for the allocator function. It is used in the auxiliary library by `luaL_newstate` (see - |luaref-luaL_newstate|). + |luaL_newstate()|). > static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { @@ -1813,7 +1746,7 @@ lua_CFunction *luaref-cfunction* *lua_CFunction()* following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the - function starts, `lua_gettop(L)` (see |luaref-lua_gettop|) returns the + function starts, `lua_gettop(L)` (see |lua_gettop()|) returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index `lua_gettop(L)`. To return values to Lua, a C function just pushes them onto the stack, @@ -1881,7 +1814,7 @@ lua_cpcall *lua_cpcall()* Calls the C function `func` in protected mode. `func` starts with only one element in its stack, a light userdata containing `ud`. In case of errors, `lua_cpcall` returns the same error codes as `lua_pcall` (see - |luaref-lua_pcall|), plus the error object on the top of the stack; + |lua_pcall()|), plus the error object on the top of the stack; otherwise, it returns zero, and does not change the stack. All values returned by `func` are discarded. @@ -1893,7 +1826,7 @@ lua_createtable *lua_createtable()* has space pre-allocated for `narr` array elements and `nrec` non-array elements. This pre-allocation is useful when you know exactly how many elements the table will have. Otherwise you can use the function - `lua_newtable` (see |luaref-lua_newtable|). + `lua_newtable` (see |lua_newtable()|). lua_dump *lua_dump()* > @@ -1903,7 +1836,7 @@ lua_dump *lua_dump()* of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped. As it produces parts of the chunk, `lua_dump` calls function `writer` (see - |luaref-lua_Writer|) with the given `data` to write them. + |lua_Writer()|) with the given `data` to write them. The value returned is the error code returned by the last call to the writer; 0 means no errors. @@ -1925,7 +1858,7 @@ lua_error *lua_error()* < Generates a Lua error. The error message (which can actually be a Lua value of any type) must be on the stack top. This function does a long - jump, and therefore never returns (see |luaref-luaL_error|). + jump, and therefore never returns (see |luaL_error()|). lua_gc *lua_gc()* > @@ -1936,25 +1869,25 @@ lua_gc *lua_gc()* This function performs several tasks, according to the value of the parameter `what`: - `LUA_GCSTOP` stops the garbage collector. - `LUA_GCRESTART` restarts the garbage collector. - `LUA_GCCOLLECT` performs a full garbage-collection cycle. - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in + - `LUA_GCSTOP` stops the garbage collector. + - `LUA_GCRESTART` restarts the garbage collector. + - `LUA_GCCOLLECT` performs a full garbage-collection cycle. + - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in use by Lua. - `LUA_GCCOUNTB` returns the remainder of dividing the current + - `LUA_GCCOUNTB` returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024. - `LUA_GCSTEP` performs an incremental step of garbage collection. + - `LUA_GCSTEP` performs an incremental step of garbage collection. The step "size" is controlled by `data` (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of `data`. The function returns 1 if the step finished a garbage-collection cycle. - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the + - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the `pause` of the collector (see |luaref-langGC|). The function returns the previous value of the pause. - `LUA_GCSETSTEPMUL` sets `data` /100 as the new value for the + - `LUA_GCSETSTEPMUL`sets `data` /100 as the new value for the `step` `multiplier` of the collector (see |luaref-langGC|). The function returns the previous value of the step multiplier. @@ -1965,7 +1898,7 @@ lua_getallocf *lua_getallocf()* < Returns the memory-allocation function of a given state. If `ud` is not `NULL`, Lua stores in `*ud` the opaque pointer passed to - `lua_newstate` (see |luaref-lua_newstate|). + `lua_newstate` (see |lua_newstate()|). lua_getfenv *lua_getfenv()* > @@ -2136,10 +2069,10 @@ lua_load *lua_load()* This function only loads a chunk; it does not run it. `lua_load` automatically detects whether the chunk is text or binary, - and loads it accordingly (see program `luac`, |luaref-luac|). + and loads it accordingly (see program `luac`). The `lua_load` function uses a user-supplied `reader` function to read - the chunk (see |luaref-lua_Reader|). The `data` argument is an opaque + the chunk (see |lua_Reader()|). The `data` argument is an opaque value passed to the reader function. The `chunkname` argument gives a name to the chunk, which is used for @@ -2161,14 +2094,14 @@ lua_newtable *lua_newtable()* < Creates a new empty table and pushes it onto the stack. It is equivalent to `lua_createtable(L, 0, 0)` (see - |luaref-lua_createtable|). + |lua_createtable()|). lua_newthread *lua_newthread()* > lua_State *lua_newthread (lua_State *L); < Creates a new thread, pushes it on the stack, and returns a pointer to - a `lua_State` (see |luaref-lua_State|) that represents this new + a `lua_State` (see |lua_State()|) that represents this new thread. The new state returned by this function shares with the original state all global objects (such as tables), but has an independent execution stack. @@ -2218,7 +2151,7 @@ lua_next *lua_next()* } < While traversing a table, do not call `lua_tolstring` (see - |luaref-lua_tolstring|) directly on a key, unless you know that the + |lua_tolstring()|) directly on a key, unless you know that the key is actually a string. Recall that `lua_tolstring` `changes` the value at the given index; this confuses the next call to `lua_next`. @@ -2248,7 +2181,7 @@ lua_pcall *lua_pcall()* Calls a function in protected mode. Both `nargs` and `nresults` have the same meaning as in `lua_call` - (see |luaref-lua_call|). If there are no errors during the call, + (see |lua_call()|). If there are no errors during the call, `lua_pcall` behaves exactly like `lua_call`. However, if there is any error, `lua_pcall` catches it, pushes a single value on the stack (the error message), and returns an error code. Like `lua_call`, @@ -2314,7 +2247,7 @@ lua_pushcfunction *lua_pushcfunction()* Any function to be registered in Lua must follow the correct protocol to receive its parameters and return its results (see - |luaref-lua_CFunction|). + |lua_CFunction()|). `lua_pushcfunction` is defined as a macro: > @@ -2408,7 +2341,7 @@ lua_pushvfstring *lua_pushvfstring()* const char *fmt, va_list argp); < - Equivalent to `lua_pushfstring` (see |luaref-pushfstring|), except + Equivalent to `lua_pushfstring` (see |lua_pushfstring()|), except that it receives a `va_list` instead of a variable number of arguments. @@ -2425,7 +2358,7 @@ lua_rawget *lua_rawget()* > void lua_rawget (lua_State *L, int index); < - Similar to `lua_gettable` (see |luaref-lua_gettable|), but does a raw + Similar to `lua_gettable` (see |lua_gettable()|), but does a raw access (i.e., without metamethods). lua_rawgeti *lua_rawgeti()* @@ -2440,7 +2373,7 @@ lua_rawset *lua_rawset()* > void lua_rawset (lua_State *L, int index); < - Similar to `lua_settable` (see |luaref-lua_settable|), but does a raw + Similar to `lua_settable` (see |lua_settable()|), but does a raw assignment (i.e., without metamethods). lua_rawseti *lua_rawseti()* @@ -2459,7 +2392,7 @@ lua_Reader *lua_Reader()* void *data, size_t *size); < - The reader function used by `lua_load` (see |luaref-lua_load|). Every + The reader function used by `lua_load` (see |lua_load()|). Every time it needs another piece of the chunk, `lua_load` calls the reader, passing along its `data` parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and set `size` to @@ -2504,15 +2437,15 @@ lua_resume *lua_resume()* Starts and resumes a coroutine in a given thread. To start a coroutine, you first create a new thread (see - |luaref-lua_newthread|); then you push onto its stack the main + |lua_newthread()|); then you push onto its stack the main function plus any arguments; then you call `lua_resume` (see - |luaref-lua_resume|) with `narg` being the number of arguments. This + |lua_resume()|) with `narg` being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, the stack contains all values passed to `lua_yield` - (see |luaref-lua_yield|), or all values returned by the body function. + (see |lua_yield()|), or all values returned by the body function. `lua_resume` returns `LUA_YIELD` if the coroutine yields, 0 if the coroutine finishes its execution without errors, or an error code in - case of errors (see |luaref-lua_pcall|). In case of errors, the stack + case of errors (see |lua_pcall()|). In case of errors, the stack is not unwound, so you can use the debug API over it. The error message is on the top of the stack. To restart a coroutine, you put on its stack only the values to be passed as results from `lua_yield`, @@ -2593,7 +2526,7 @@ lua_State *lua_State()* A pointer to this state must be passed as the first argument to every function in the library, except to `lua_newstate` (see - |luaref-lua_newstate|), which creates a Lua state from scratch. + |lua_newstate()|), which creates a Lua state from scratch. lua_status *lua_status()* > @@ -2614,7 +2547,7 @@ lua_toboolean *lua_toboolean()* any Lua value different from `false` and `nil`; otherwise it returns 0. It also returns 0 when called with a non-valid index. (If you want to accept only actual boolean values, use `lua_isboolean` - |luaref-lua_isboolean| to test the value's type.) + |lua_isboolean()| to test the value's type.) lua_tocfunction *lua_tocfunction()* > @@ -2628,7 +2561,7 @@ lua_tointeger *lua_tointeger()* lua_Integer lua_tointeger (lua_State *L, int idx); < Converts the Lua value at the given acceptable index to the signed - integral type `lua_Integer` (see |luaref-lua_Integer|). The Lua value + integral type `lua_Integer` (see |lua_Integer()|). The Lua value must be a number or a string convertible to a number (see |luaref-langCoercion|); otherwise, `lua_tointeger` returns 0. @@ -2644,7 +2577,7 @@ lua_tolstring *lua_tolstring()* Lua value must be a string or a number; otherwise, the function returns `NULL`. If the value is a number, then `lua_tolstring` also `changes the actual value in the stack to a` `string`. (This change - confuses `lua_next` |luaref-lua_next| when `lua_tolstring` is applied + confuses `lua_next` |lua_next()| when `lua_tolstring` is applied to keys during a table traversal.) `lua_tolstring` returns a fully aligned pointer to a string inside the @@ -2659,7 +2592,7 @@ lua_tonumber *lua_tonumber()* lua_Number lua_tonumber (lua_State *L, int index); < Converts the Lua value at the given acceptable index to the C type - `lua_Number` (see |luaref-lua_Number|). The Lua value must be a number + `lua_Number` (see |lua_Number()|). The Lua value must be a number or a string convertible to a number (see |luaref-langCoercion|); otherwise, `lua_tonumber` returns 0. @@ -2679,7 +2612,7 @@ lua_tostring *lua_tostring()* > const char *lua_tostring (lua_State *L, int index); < - Equivalent to `lua_tolstring` (see |luaref-lua_tolstring|) with `len` + Equivalent to `lua_tolstring` (see |lua_tolstring()|) with `len` equal to `NULL`. lua_tothread *lua_tothread()* @@ -2687,7 +2620,7 @@ lua_tothread *lua_tothread()* lua_State *lua_tothread (lua_State *L, int index); < Converts the value at the given acceptable index to a Lua thread - (represented as `lua_State*` |luaref-lua_State|). This value must be a + (represented as `lua_State*` |lua_State()|). This value must be a thread; otherwise, the function returns `NULL`. lua_touserdata *lua_touserdata()* @@ -2723,7 +2656,7 @@ lua_Writer *lua_Writer()* size_t sz, void* ud); < - The writer function used by `lua_dump` (see |luaref-lua_dump|). Every + The writer function used by `lua_dump` (see |lua_dump()|). Every time it produces another piece of chunk, `lua_dump` calls the writer, passing along the buffer to be written (`p`), its size (`sz`), and the `data` parameter supplied to `lua_dump`. @@ -2753,7 +2686,7 @@ lua_yield *lua_yield()* < When a C function calls `lua_yield` in that way, the running coroutine suspends its execution, and the call to `lua_resume` (see - |luaref-lua_resume|) that started this coroutine returns. The + |lua_resume()|) that started this coroutine returns. The parameter `nresults` is the number of values from the stack that are passed as results to `lua_resume`. @@ -2782,50 +2715,52 @@ need "inside information" from the interpreter. lua_Debug *lua_Debug()* - `typedef struct lua_Debug {` - `int event;` - `const char *name; /* (n) */` - `const char *namewhat; /* (n) */` - `const char *what; /* (S) */` - `const char *source; /* (S) */` - `int currentline; /* (l) */` - `int nups; /* (u) number of upvalues */` - `int linedefined; /* (S) */` - `int lastlinedefined; /* (S) */` - `char short_src[LUA_IDSIZE]; /* (S) */` - `/* private part */` - `other fields` - `} lua_Debug;` +> + typedef struct lua_Debug { + int event; + const char *name; /* (n) */ + const char *namewhat; /* (n) */ + const char *what; /* (S) */ + const char *source; /* (S) */ + int currentline; /* (l) */ + int nups; /* (u) number of upvalues */ + int linedefined; /* (S) */ + int lastlinedefined; /* (S) */ + char short_src[LUA_IDSIZE]; /* (S) */ + /* private part */ + other fields + } lua_Debug; +< A structure used to carry different pieces of information about an active -function. `lua_getstack` (see |luaref-lua_getstack|) fills only the private part +function. `lua_getstack` (see |lua_getstack()|) fills only the private part of this structure, for later use. To fill the other fields of `lua_Debug` with -useful information, call `lua_getinfo` (see |luaref-lua_getinfo|). +useful information, call `lua_getinfo` (see |lua_getinfo()|). The fields of `lua_Debug` have the following meaning: - `source` If the function was defined in a string, then `source` is +- `source` If the function was defined in a string, then `source` is that string. If the function was defined in a file, then `source` starts with a `@` followed by the file name. - `short_src` a "printable" version of `source`, to be used in error messages. - `linedefined` the line number where the definition of the function starts. - `lastlinedefined` the line number where the definition of the function ends. - `what` the string `"Lua"` if the function is a Lua function, +- `short_src` a "printable" version of `source`, to be used in error messages. +- `linedefined` the line number where the definition of the function starts. +- `lastlinedefined` the line number where the definition of the function ends. +- `what` the string `"Lua"` if the function is a Lua function, `"C"` if it is a C function, `"main"` if it is the main part of a chunk, and `"tail"` if it was a function that did a tail call. In the latter case, Lua has no other information about the function. - `currentline` the current line where the given function is executing. +- `currentline` the current line where the given function is executing. When no line information is available, `currentline` is set to -1. - `name` a reasonable name for the given function. Because +- `name` a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions may be the value of multiple global variables, while others may be stored only in a table field. The `lua_getinfo` function checks how the function was called to find a suitable name. If it cannot find a name, then `name` is set to `NULL`. - `namewhat` explains the `name` field. The value of `namewhat` can be +- `namewhat` explains the `name` field. The value of `namewhat` can be `"global"`, `"local"`, `"method"`, `"field"`, `"upvalue"`, or `""` (the empty string), according to how the function was called. (Lua uses the empty string when @@ -2858,8 +2793,8 @@ lua_getinfo *lua_getinfo()* To get information about a function invocation, the parameter `ar` must be a valid activation record that was filled by a previous call - to `lua_getstack` (see |luaref-lua_getstack|) or given as argument to - a hook (see |luaref-lua_Hook|). + to `lua_getstack` (see |lua_getstack()|) or given as argument to + a hook (see |lua_Hook()|). To get information about a function you push it onto the stack and start the `what` string with the character `>`. (In that case, @@ -2896,8 +2831,8 @@ lua_getlocal *lua_getlocal()* < Gets information about a local variable of a given activation record. The parameter `ar` must be a valid activation record that was filled - by a previous call to `lua_getstack` (see |luaref-lua_getstack|) or - given as argument to a hook (see |luaref-lua_Hook|). The index `n` + by a previous call to `lua_getstack` (see |lua_getstack()|) or + given as argument to a hook (see |lua_Hook()|). The index `n` selects which local variable to inspect (1 is the first parameter or active local variable, and so on, until the last active local variable). `lua_getlocal` pushes the variable's value onto the stack @@ -2916,7 +2851,7 @@ lua_getstack *lua_getstack()* < Gets information about the interpreter runtime stack. - This function fills parts of a `lua_Debug` (see |luaref-lua_Debug|) + This function fills parts of a `lua_Debug` (see |lua_Debug()|) structure with an identification of the `activation record` of the function executing at a given level. Level 0 is the current running function, whereas level `n+1` is the function that has called level @@ -2951,7 +2886,7 @@ lua_Hook *lua_Hook()* `LUA_HOOKTAILRET`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for line events, the field `currentline` is also set. To get the value of any other field in `ar`, the hook must call `lua_getinfo` (see - |luaref-lua_getinfo|). For return events, `event` may be + |lua_getinfo()|). For return events, `event` may be `LUA_HOOKRET`, the normal value, or `LUA_HOOKTAILRET`. In the latter case, Lua is simulating a return from a function that did a tail call; in this case, it is useless to call `lua_getinfo`. @@ -2996,7 +2931,7 @@ lua_setlocal *lua_setlocal()* < Sets the value of a local variable of a given activation record. Parameters `ar` and `n` are as in `lua_getlocal` (see - |luaref-lua_getlocal|). `lua_setlocal` assigns the value at the top of + |lua_getlocal()|). `lua_setlocal` assigns the value at the top of the stack to the variable and returns its name. It also pops the value from the stack. @@ -3010,7 +2945,7 @@ lua_setupvalue *lua_setupvalue()* Sets the value of a closure's upvalue. It assigns the value at the top of the stack to the upvalue and returns its name. It also pops the value from the stack. Parameters `funcindex` and `n` are as in the - `lua_getupvalue` (see |luaref-lua_getupvalue|). + `lua_getupvalue` (see |lua_getupvalue()|). Returns `NULL` (and pops nothing) when the index is greater than the number of upvalues. @@ -3042,7 +2977,6 @@ lua_setupvalue *lua_setupvalue()* ============================================================================== 4 THE AUXILIARY LIBRARY *luaref-aux* -============================================================================== The auxiliary library provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all @@ -3071,36 +3005,36 @@ luaL_addchar *luaL_addchar()* > void luaL_addchar (luaL_Buffer *B, char c); < - Adds the character `c` to the buffer `B` (see |luaref-luaL_Buffer|). + Adds the character `c` to the buffer `B` (see |luaL_Buffer()|). luaL_addlstring *luaL_addlstring()* > void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); < Adds the string pointed to by `s` with length `l` to the buffer `B` - (see |luaref-luaL_Buffer|). The string may contain embedded zeros. + (see |luaL_Buffer()|). The string may contain embedded zeros. luaL_addsize *luaL_addsize()* > void luaL_addsize (luaL_Buffer *B, size_t n); < - Adds to the buffer `B` (see |luaref-luaL_Buffer|) a string of length + Adds to the buffer `B` (see |luaL_Buffer()|) a string of length `n` previously copied to the buffer area (see - |luaref-luaL_prepbuffer|). + |luaL_prepbuffer()|). luaL_addstring *luaL_addstring()* > void luaL_addstring (luaL_Buffer *B, const char *s); < Adds the zero-terminated string pointed to by `s` to the buffer `B` - (see |luaref-luaL_Buffer|). The string may not contain embedded zeros. + (see |luaL_Buffer()|). The string may not contain embedded zeros. luaL_addvalue *luaL_addvalue()* > void luaL_addvalue (luaL_Buffer *B); < Adds the value at the top of the stack to the buffer `B` (see - |luaref-luaL_Buffer|). Pops the value. + |luaL_Buffer()|). Pops the value. This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be @@ -3142,11 +3076,11 @@ luaL_Buffer *luaL_Buffer()* - First you declare a variable `b` of type `luaL_Buffer`. - Then you initialize it with a call `luaL_buffinit(L, &b)` (see - |luaref-luaL_buffinit|). + |luaL_buffinit()|). - Then you add string pieces to the buffer calling any of the `luaL_add*` functions. - You finish by calling `luaL_pushresult(&b)` (see - |luaref-luaL_pushresult|). This call leaves the final string on the + |luaL_pushresult()|). This call leaves the final string on the top of the stack. During its normal operation, a string buffer uses a variable number of @@ -3156,7 +3090,7 @@ luaL_Buffer *luaL_Buffer()* that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is `luaL_addvalue` - |luaref-luaL_addvalue|.) After calling `luaL_pushresult` the stack is + |luaL_addvalue()|.) After calling `luaL_pushresult` the stack is back to its level when the buffer was initialized, plus the final string on its top. @@ -3165,7 +3099,7 @@ luaL_buffinit *luaL_buffinit()* void luaL_buffinit (lua_State *L, luaL_Buffer *B); < Initializes a buffer `B`. This function does not allocate any space; - the buffer must be declared as a variable (see |luaref-luaL_Buffer|). + the buffer must be declared as a variable (see |luaL_Buffer()|). luaL_callmeta *luaL_callmeta()* > @@ -3199,7 +3133,7 @@ luaL_checkinteger *luaL_checkinteger()* lua_Integer luaL_checkinteger (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns - this number cast to a `lua_Integer` (see |luaref-lua_Integer|). + this number cast to a `lua_Integer` (see |lua_Integer()|). luaL_checklong *luaL_checklong()* > @@ -3220,7 +3154,7 @@ luaL_checknumber *luaL_checknumber()* lua_Number luaL_checknumber (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns - this number (see |luaref-lua_Number|). + this number (see |lua_Number()|). luaL_checkoption *luaL_checkoption()* > @@ -3262,14 +3196,14 @@ luaL_checktype *luaL_checktype()* void luaL_checktype (lua_State *L, int narg, int t); < Checks whether the function argument `narg` has type `t` (see - |luaref-lua_type|). + |lua_type()|). luaL_checkudata *luaL_checkudata()* > void *luaL_checkudata (lua_State *L, int narg, const char *tname); < Checks whether the function argument `narg` is a userdata of the type - `tname` (see |luaref-luaL_newmetatable|). + `tname` (see |luaL_newmetatable()|). luaL_dofile *luaL_dofile()* > @@ -3297,7 +3231,7 @@ luaL_error *luaL_error()* < Raises an error. The error message format is given by `fmt` plus any extra arguments, following the same rules of `lua_pushfstring` (see - |luaref-lua_pushfstring|). It also adds at the beginning of the + |lua_pushfstring()|). It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available. @@ -3317,7 +3251,7 @@ luaL_getmetatable *luaL_getmetatable()* void luaL_getmetatable (lua_State *L, const char *tname); < Pushes onto the stack the metatable associated with name `tname` in - the registry (see |luaref-luaL_newmetatable|). + the registry (see |luaL_newmetatable()|). luaL_gsub *luaL_gsub()* > @@ -3338,7 +3272,7 @@ luaL_loadbuffer *luaL_loadbuffer()* const char *name); < Loads a buffer as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the buffer pointed to by + |lua_load()|) to load the chunk in the buffer pointed to by `buff` with size `sz`. This function returns the same results as `lua_load`. `name` is the @@ -3349,7 +3283,7 @@ luaL_loadfile *luaL_loadfile()* int luaL_loadfile (lua_State *L, const char *filename); < Loads a file as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the file named `filename`. If + |lua_load()|) to load the chunk in the file named `filename`. If `filename` is `NULL`, then it loads from the standard input. The first line in the file is ignored if it starts with a `#`. @@ -3363,7 +3297,7 @@ luaL_loadstring *luaL_loadstring()* int luaL_loadstring (lua_State *L, const char *s); < Loads a string as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the zero-terminated string + |lua_load()|) to load the chunk in the zero-terminated string `s`. This function returns the same results as `lua_load`. @@ -3387,9 +3321,9 @@ luaL_newstate *luaL_newstate()* lua_State *luaL_newstate (void); < Creates a new Lua state. It calls `lua_newstate` (see - |luaref-lua_newstate|) with an allocator based on the standard C + |lua_newstate()|) with an allocator based on the standard C `realloc` function and then sets a panic function (see - |luaref-lua_atpanic|) that prints an error message to the standard + |lua_atpanic()|) that prints an error message to the standard error output in case of fatal errors. Returns the new state, or `NULL` if there is a memory allocation @@ -3417,7 +3351,7 @@ luaL_optinteger *luaL_optinteger()* lua_Integer d); < If the function argument `narg` is a number, returns this number cast - to a `lua_Integer` (see |luaref-lua_Integer|). If this argument is + to a `lua_Integer` (see |lua_Integer()|). If this argument is absent or is `nil`, returns `d`. Otherwise, raises an error. luaL_optlong *luaL_optlong()* @@ -3464,9 +3398,9 @@ luaL_prepbuffer *luaL_prepbuffer()* char *luaL_prepbuffer (luaL_Buffer *B); < Returns an address to a space of size `LUAL_BUFFERSIZE` where you can - copy a string to be added to buffer `B` (see |luaref-luaL_Buffer|). + copy a string to be added to buffer `B` (see |luaL_Buffer()|). After copying the string into this space you must call `luaL_addsize` - (see |luaref-luaL_addsize|) with the size of the string to actually + (see |luaL_addsize()|) with the size of the string to actually add it to the buffer. luaL_pushresult *luaL_pushresult()* @@ -3486,8 +3420,8 @@ luaL_ref *luaL_ref()* A reference is a unique integer key. As long as you do not manually add integer keys into table `t`, `luaL_ref` ensures the uniqueness of the key it returns. You can retrieve an object referred by reference - `r` by calling `lua_rawgeti(L, t, r)` (see |luaref-lua_rawgeti|). - Function `luaL_unref` (see |luaref-luaL_unref|) frees a reference and + `r` by calling `lua_rawgeti(L, t, r)` (see |lua_rawgeti()|). + Function `luaL_unref` (see |luaL_unref()|) frees a reference and its associated object. If the object at the top of the stack is `nil`, `luaL_ref` returns the @@ -3502,7 +3436,7 @@ luaL_Reg *luaL_Reg()* } luaL_Reg; < Type for arrays of functions to be registered by `luaL_register` (see - |luaref-luaL_register|). `name` is the function name and `func` is a + |luaL_register()|). `name` is the function name and `func` is a pointer to the function. Any array of `luaL_Reg` must end with a sentinel entry in which both `name` and `func` are `NULL`. @@ -3515,7 +3449,7 @@ luaL_register *luaL_register()* Opens a library. When called with `libname` equal to `NULL`, it simply registers all - functions in the list `l` (see |luaref-luaL_Reg|) into the table on + functions in the list `l` (see |luaL_Reg()|) into the table on the top of the stack. When called with a non-null `libname`, `luaL_register` creates a new @@ -3543,7 +3477,7 @@ luaL_typerror *luaL_typerror()* `expected, got` `rt` `)` where `location` is produced by `luaL_where` (see - |luaref-luaL_where|), `func` is the name of the current function, and + |luaL_where()|), `func` is the name of the current function, and `rt` is the type name of the actual argument. luaL_unref *luaL_unref()* @@ -3551,7 +3485,7 @@ luaL_unref *luaL_unref()* void luaL_unref (lua_State *L, int t, int ref); < Releases reference `ref` from the table at index `t` (see - |luaref-luaL_ref|). The entry is removed from the table, so that the + |luaL_ref()|). The entry is removed from the table, so that the referred object can be collected. The reference `ref` is also freed to be used again. @@ -3574,7 +3508,6 @@ luaL_where *luaL_where()* ============================================================================== 5 STANDARD LIBRARIES *luaref-Lib* -============================================================================== The standard libraries provide useful functions that are implemented directly through the C API. Some of these functions provide essential services to the @@ -3601,14 +3534,14 @@ functions as fields of a global table or as methods of its objects. *luaref-openlibs* To have access to these libraries, the C host program should call the `luaL_openlibs` function, which opens all standard libraries (see -|luaref-luaL_openlibs|). Alternatively, the host program can open the libraries +|luaL_openlibs()|). Alternatively, the host program can open the libraries individually by calling `luaopen_base` (for the basic library), `luaopen_package` (for the package library), `luaopen_string` (for the string library), `luaopen_table` (for the table library), `luaopen_math` (for the mathematical library), `luaopen_io` (for the I/O and the Operating System libraries), and `luaopen_debug` (for the debug library). These functions are declared in `lualib.h` and should not be called directly: you must call them -like any other Lua C function, e.g., by using `lua_call` (see |luaref-lua_call|). +like any other Lua C function, e.g., by using `lua_call` (see |lua_call()|). ============================================================================== 5.1 Basic Functions *luaref-libBasic* @@ -3700,11 +3633,11 @@ load({func} [, {chunkname}]) *luaref-load()* information. loadfile([{filename}]) *luaref-loadfile()* - Similar to `load` (see |luaref-load|), but gets the chunk from file + Similar to `load` (see |luaref-load()|), but gets the chunk from file {filename} or from the standard input, if no file name is given. loadstring({string} [, {chunkname}]) *luaref-loadstring()* - Similar to `load` (see |luaref-load|), but gets the chunk from the + Similar to `load` (see |luaref-load()|), but gets the chunk from the given {string}. To load and run a given string, use the idiom @@ -3724,14 +3657,14 @@ next({table} [, {index}]) *luaref-next()* The order in which the indices are enumerated is not specified, `even for` `numeric indices`. (To traverse a table in numeric order, use a - numerical `for` or the `ipairs` |luaref-ipairs| function.) + numerical `for` or the `ipairs` |luaref-ipairs()| function.) The behavior of `next` is `undefined` if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields. pairs({t}) *luaref-pairs()* - Returns three values: the `next` |luaref-next| function, the table + Returns three values: the `next` |luaref-next()| function, the table {t}, and `nil`, so that the construction `for k,v in pairs(t) do` `body` `end` @@ -3749,10 +3682,10 @@ pcall({f}, {arg1}, {...}) *luaref-pcall()* print({...}) *luaref-print()* Receives any number of arguments, and prints their values to `stdout`, - using the `tostring` |luaref-tostring| function to convert them to + using the `tostring` |luaref-tostring()| function to convert them to strings. `print` is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted - output, use `string.format` (see |luaref-string.format|). + output, use `string.format` (see |string.format()|). rawequal({v1}, {v2}) *luaref-rawequal()* Checks whether {v1} is equal to {v2}, without invoking any metamethod. @@ -3807,7 +3740,7 @@ tonumber({e} [, {base}]) *luaref-tonumber()* tostring({e}) *luaref-tostring()* Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, - use `string.format` (see |luaref-string.format|). + use `string.format` (see |string.format()|). *__tostring* If the metatable of {e} has a `"__tostring"` field, `tostring` calls @@ -3836,7 +3769,7 @@ _VERSION *luaref-_VERSION()* `"Lua 5.1"` . xpcall({f}, {err}) *luaref-xpcall()* - This function is similar to `pcall` (see |luaref-pcall|), except that + This function is similar to `pcall` (see |luaref-pcall()|), except that you can set a new error handler. `xpcall` calls function {f} in protected mode, using {err} as the @@ -3901,7 +3834,7 @@ coroutine.yield({...}) *coroutine.yield()* The package library provides basic facilities for loading and building modules in Lua. It exports two of its functions directly in the global environment: -`require` and `module` (see |luaref-require| and |luaref-module|). Everything else is +`require` and `module` (see |luaref-require()| and |luaref-module()|). Everything else is exported in a table `package`. module({name} [, {...}]) *luaref-module()* @@ -3914,7 +3847,7 @@ module({name} [, {...}]) *luaref-module()* `t._PACKAGE` with the package name (the full module name minus last component; see below). Finally, `module` sets `t` as the new environment of the current function and the new value of - `package.loaded[name]`, so that `require` (see |luaref-require|) + `package.loaded[name]`, so that `require` (see |luaref-require()|) returns `t`. If {name} is a compound name (that is, one with components separated @@ -3968,7 +3901,7 @@ require({modname}) *luaref-require()* If there is any error loading or running the module, or if it cannot find any loader for the module, then `require` signals an error. -package.cpath *package.cpath()* +package.cpath *package.cpath* The path used by `require` to search for a C loader. Lua initializes the C path `package.cpath` in the same way it @@ -3985,7 +3918,7 @@ package.loadlib({libname}, {funcname}) *package.loadlib()* Dynamically links the host program with the C library {libname}. Inside this library, looks for a function {funcname} and returns this function as a C function. (So, {funcname} must follow the protocol - (see |luaref-lua_CFunction|)). + (see |lua_CFunction()|)). This is a low-level function. It completely bypasses the package and module system. Unlike `require`, it does not perform any path @@ -3998,7 +3931,7 @@ package.loadlib({libname}, {funcname}) *package.loadlib()* available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the `dlfcn` standard). -package.path *package.path()* +package.path *package.path* The path used by `require` to search for a Lua loader. At start-up, Lua initializes this variable with the value of the @@ -4019,7 +3952,7 @@ package.path *package.path()* order. package.preload *package.preload()* - A table to store loaders for specific modules (see |luaref-require|). + A table to store loaders for specific modules (see |luaref-require()|). package.seeall({module}) *package.seeall()* Sets a metatable for {module} with its `__index` field referring to @@ -4059,7 +3992,7 @@ string.char({...}) *string.char()* string.dump({function}) *string.dump()* Returns a string containing a binary representation of the given - function, so that a later |luaref-loadstring| on this string returns a + function, so that a later |luaref-loadstring()| on this string returns a copy of the function. {function} must be a Lua function without upvalues. @@ -4127,7 +4060,7 @@ string.gmatch({s}, {pattern}) *string.gmatch()* end < -string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsu{b}()* +string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsub()* Returns a copy of {s} in which all occurrences of the {pattern} have been replaced by a replacement string specified by {repl}, which may be a string, a table, or a function. `gsub` also returns, as its @@ -4341,7 +4274,7 @@ table.foreach({table}, {f}) *table.foreach()* returns a non-`nil` value, then the loop is broken, and this value is returned as the final value of `table.foreach`. - See |luaref-next| for extra information about table traversals. + See |luaref-next()| for extra information about table traversals. table.foreachi({table}, {f}) *table.foreachi()* Executes the given {f} over the numerical indices of {table}. For each @@ -4658,7 +4591,7 @@ file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()* immediately. `"full"` full buffering; output operation is performed only when the buffer is full (or when you explicitly `flush` the file - (see |luaref-io.flush|). + (see |io.flush()|). `"line"` line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device). @@ -4669,7 +4602,7 @@ file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()* file:write({...}) *luaref-file:write()* Writes the value of each of its arguments to `file`. The arguments must be strings or numbers. To write other values, use `tostring` - |luaref-tostring| or `string.format` |luaref-string.format| before + |luaref-tostring()| or `string.format` |string.format()| before `write`. ============================================================================== @@ -4686,7 +4619,7 @@ os.date([{format} [, {time}]]) *os.date()* according to the given string {format}. If the {time} argument is present, this is the time to be formatted - (see the `os.time` function |luaref-os.time| for a description of this + (see the `os.time` function |os.time()| for a description of this value). Otherwise, `date` formats the current time. If {format} starts with `!`, then the date is formatted in @@ -4744,7 +4677,7 @@ os.time([{table}]) *os.time()* representing the date and time specified by the given table. This table must have fields `year`, `month`, and `day`, and may have fields `hour`, `min`, `sec`, and `isdst` (for a description of these fields, - see the `os.date` function |luaref-os.date|). + see the `os.date` function |os.date()|). The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the @@ -4802,7 +4735,7 @@ debug.getinfo([{thread},] {function} [, {what}]) *debug.getinfo()* functions, then `getinfo` returns `nil`. The returned table may contain all the fields returned by - `lua_getinfo` (see |luaref-lua_getinfo|), with the string {what} + `lua_getinfo` (see |lua_getinfo()|), with the string {what} describing which fields to fill in. The default for {what} is to get all information available, except the table of valid lines. If present, the option `f` adds a field named `func` with the function @@ -4821,7 +4754,7 @@ debug.getlocal([{thread},] {level}, {local}) *debug.getlocal()* last active local variable.) The function returns `nil` if there is no local variable with the given index, and raises an error when called with a {level} out of range. (You can call `debug.getinfo` - |luaref-debug.getinfo| to check whether the level is valid.) + |debug.getinfo()| to check whether the level is valid.) Variable names starting with `(` (open parentheses) represent internal variables (loop control variables, temporaries, and C @@ -4894,7 +4827,6 @@ debug.traceback([{thread},] [{message}] [,{level}]) *debug.traceback()* ============================================================================== A BIBLIOGRAPHY *luaref-bibliography* -============================================================================== This help file is a minor adaptation from this main reference: @@ -4920,8 +4852,7 @@ Lua is discussed in these references: "Proc. of V Brazilian Symposium on Programming Languages" (2001) B-14-B-28. ============================================================================== -B COPYRIGHT & LICENSES *luaref-copyright* -============================================================================== +B COPYRIGHT AND LICENSES *luaref-copyright* This help file has the same copyright and license as Lua 5.1 and the Lua 5.1 manual: @@ -4938,22 +4869,21 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. ============================================================================== C LUAREF DOC *luarefvim* *luarefvimdoc* *luaref-help* *luaref-doc* -============================================================================== This is a Vim help file containing a reference for Lua 5.1, and it is -- with a few exceptions and adaptations -- a copy of the Lua 5.1 Reference Manual (see |luaref-bibliography|). For usage information, refer to -|luaref-docUsage|. For copyright information, see |luaref-copyright|. +|luaref-doc|. For copyright information, see |luaref-copyright|. The main ideas and concepts on how to implement this reference were taken from Christian Habermann's CRefVim project diff --git a/runtime/doc/luvref.txt b/runtime/doc/luvref.txt index ee45444b42..6b77ee89a8 100644 --- a/runtime/doc/luvref.txt +++ b/runtime/doc/luvref.txt @@ -3355,7 +3355,7 @@ uv.getnameinfo({address} [, {callback}]) *uv.getnameinfo()* - `family`: `string` or `integer` or `nil` - `callback`: `callable` (async version) or `nil` (sync version) - - `err`: `nil` or `sring` + - `err`: `nil` or `string` - `host`: `string` or `nil` - `service`: `string` or `nil` diff --git a/runtime/doc/makehtml.awk b/runtime/doc/makehtml.awk deleted file mode 100644 index 50f5611fa7..0000000000 --- a/runtime/doc/makehtml.awk +++ /dev/null @@ -1,788 +0,0 @@ -BEGIN { - # some initialization variables - asciiart="no"; - wasset="no"; - lineset=0; - sample="no"; - while ( getline ti <"tags.ref" > 0 ) { - nf=split(ti,tag," "); - # as help.txt renders into index.html and index.txt -> vimindex.html, - # this hack is needed to get the links right to those pages. - if ( tag[2] == "index.txt" ) { - tag[2] = "vimindex.txt" - } else if ( tag[2] == "help.txt" ) { - tag[2] = "index.txt" - } - tagkey[tag[1]]="yes";tagref[tag[1]]=tag[2]; - } - skip_word["and"]="yes"; - skip_word["backspace"]="yes"; - skip_word["beep"]="yes"; - skip_word["bugs"]="yes"; - skip_word["da"]="yes"; - skip_word["end"]="yes"; - skip_word["ftp"]="yes"; - skip_word["go"]="yes"; - skip_word["help"]="yes"; - skip_word["home"]="yes"; - skip_word["news"]="yes"; - skip_word["index"]="yes"; - skip_word["insert"]="yes"; - skip_word["into"]="yes"; - skip_word["put"]="yes"; - skip_word["reference"]="yes"; - skip_word["section"]="yes"; - skip_word["space"]="yes"; - skip_word["starting"]="yes"; - skip_word["toggle"]="yes"; - skip_word["various"]="yes"; - skip_word["version"]="yes"; - skip_word["is"]="yes"; -} -# -# protect special chars -# -/[><&á]/ {gsub(/&/,"\\&");gsub(/>/,"\\>");gsub(/</,"\\<");gsub("á","\\á");} -# -# end of sample lines by non-blank in first column -# -sample == "yes" && substr($0,1,4) == "<" { sample = "no"; gsub(/^</, " "); } -sample == "yes" && substr($0,1,1) != " " && substr($0,1,1) != " " && length($0) > 0 { sample = "no" } -# -# sample lines printed bold unless empty... -# -sample == "yes" && $0 =="" { print ""; next; } -sample == "yes" && $0 !="" { print "<B>" $0 "</B>"; next; } -# -# start of sample lines in next line -# -$0 == ">" { sample = "yes"; print ""; next; } -substr($0,length($0)-4,5) == " >" { sample = "yes"; gsub(/ >$/, ""); } -# -# header lines printed bold, colored -# -substr($0,length($0),1) == "~" { print "<B><FONT COLOR=\"PURPLE\">" substr($0,1,length($0)-1) "</FONT></B>"; next; } -# -#ad hoc code -# -/^"\|& / {gsub(/\|/,"\\|"); } -/ = b / {gsub(/ b /," \\b "); } -# -# one letter tag -# -/[ ]\*.\*[ ]/ {gsub(/\*/,"ZWWZ"); } -# -# isolated "*" -# -/[ ]\*[ ]/ {gsub(/ \* /," \\* "); - gsub(/ \* /," \\* "); - gsub(/ \* /," \\* "); - gsub(/ \* /," \\* "); } -# -# tag start -# -/[ ]\*[^ ]/ {gsub(/ \*/," ZWWZ");gsub(/ \*/," ZWWZ");} -/^\*[^ ]/ {gsub(/^\*/,"ZWWZ");} -# -# tag end -# -/[^ ]\*$/ {gsub(/\*$/,"ZWWZ");} -/[^ \/ ]\*[ ]/ {gsub(/\*/,"ZWWZ");} -# -# isolated "|" -# -/[ ]\|[ ]/ {gsub(/ \| /," \\| "); - gsub(/ \| /," \\| "); - gsub(/ \| /," \\| "); - gsub(/ \| /," \\| "); } -/'\|'/ { gsub(/'\|'/,"'\\|'"); } -/\^V\|/ {gsub(/\^V\|/,"^V\\|");} -/ \\\| / {gsub(/\|/,"\\|");} -# -# one letter pipes and "||" false pipe (digraphs) -# -/[ ]\|.\|[ ]/ && asciiart == "no" {gsub(/\|/,"YXXY"); } -/^\|.\|[ ]/ {gsub(/\|/,"YXXY"); } -/\|\|/ {gsub(/\|\|/,"\\|\\|"); } -/^shellpipe/ {gsub(/\|/,"\\|"); } -# -# pipe start -# -/[ ]\|[^ ]/ && asciiart == "no" {gsub(/ \|/," YXXY"); - gsub(/ \|/," YXXY");} -/^\|[^ ]/ {gsub(/^\|/,"YXXY");} -# -# pipe end -# -/[^ ]\|$/ && asciiart == "no" {gsub(/\|$/,"YXXY");} -/[^ ]\|[s ,.); ]/ && asciiart == "no" {gsub(/\|/,"YXXY");} -/[^ ]\|]/ && asciiart == "no" {gsub(/\|/,"YXXY");} -# -# various -# -/'"/ {gsub(/'"/,"\\'\\"'");} -/"/ {gsub(/"/,"\\"");} -/%/ {gsub(/%/,"\\%");} - -NR == 1 { nf=split(FILENAME,f,".") - print "<HTML>"; - - print "<HEAD>" - if ( FILENAME == "mbyte.txt" ) { - # needs utf-8 as uses many languages - print "<META HTTP-EQUIV=\"Content-type\" content=\"text/html; charset=UTF-8\">"; - } else { - # common case - Latin1 - print "<META HTTP-EQUIV=\"Content-type\" content=\"text/html; charset=ISO-8859-1\">"; - } - print "<TITLE>Nvim documentation: " f[1] "</TITLE>"; - print "</HEAD>"; - - print "<BODY BGCOLOR=\"#ffffff\">"; - print "<H1>Nvim documentation: " f[1] "</H1>"; - print "<A NAME=\"top\"></A>"; - if ( FILENAME != "help.txt" ) { - print "<A HREF=\"index.html\">main help file</A>\n"; - } - print "<HR>"; - print "<PRE>"; - filename=f[1]".html"; -} - -# set to a low value to test for few lines of text -# NR == 99999 { exit; } - -# ignore underlines and tags -substr($0,1,5) == " vim:" { next; } -substr($0,1,4) == "vim:" { next; } -# keep just whole lines of "-", "=" -substr($0,1,3) == "===" && substr($0,75,1) != "=" { next; } -substr($0,1,3) == "---" && substr($0,75,1) != "-" { next; } - -{ - nstar = split($0,s,"ZWWZ"); - for ( i=2 ; i <= nstar ; i=i+2 ) { - nbla=split(s[i],blata,"[ ]"); - if ( nbla > 1 ) { - gsub("ZWWZ","*"); - nstar = split($0,s,"ZWWZ"); - } - } - npipe = split($0,p,"YXXY"); - for ( i=2 ; i <= npipe ; i=i+2 ) { - nbla=split(p[i],blata,"[ ]"); - if ( nbla > 1 ) { - gsub("YXXY","|"); - ntabs = split($0,p,"YXXY"); - } - } -} - - -FILENAME == "gui.txt" && asciiart == "no" \ - && $0 ~ /\+----/ && $0 ~ /----\+/ { - asciiart= "yes"; - asciicnt=0; - } - -FILENAME == "usr_20.txt" && asciiart == "no" \ - && $0 ~ /an empty line at the end:/ { - asciiart= "yes"; - asciicnt=0; - } - -asciiart == "yes" && $0=="" { asciicnt++; } - -asciiart == "yes" && asciicnt == 2 { asciiart = "no"; } - -asciiart == "yes" { npipe = 1; } -# { print NR " <=> " asciiart; } - -# -# line contains "*" -# -nstar > 2 && npipe < 3 { - printf("\n"); - for ( i=1; i <= nstar ; i=i+2 ) { - this=s[i]; - put_this(); - ii=i+1; - nbla = split(s[ii],blata," "); - if ( ii <= nstar ) { - if ( nbla == 1 && substr(s[ii],length(s[ii]),1) != " " ) { - printf("*<A NAME=\"%s\"></A>",s[ii]); - printf("<B>%s</B>*",s[ii]); - } else { - printf("*%s*",s[ii]); - } - } - } - printf("\n"); - next; - } -# -# line contains "|" -# -npipe > 2 && nstar < 3 { - if ( npipe%2 == 0 ) { - for ( i=1; i < npipe ; i++ ) { - gsub("ZWWZ","*",p[i]); - printf("%s|",p[i]); - } - printf("%s\n",p[npipe]); - next; - } - for ( i=1; i <= npipe ; i++ ) - { - if ( i % 2 == 1 ) { - gsub("ZWWZ","*",p[i]); - this=p[i]; - put_this(); - } - else { - nfn=split(p[i],f,"."); - if ( nfn == 1 || f[2] == "" || f[1] == "" || length(f[2]) < 3 ) { - find_tag1(); - } - else { - if ( f[1] == "index" ) { - printf "|<A HREF=\"vimindex.html\">" p[i] "</A>|"; - } else { - if ( f[1] == "help" ) { - printf "|<A HREF=\"index.html\">" p[i] "</A>|"; - } else { - printf "|<A HREF=\"" f[1] ".html\">" p[i] "</A>|"; - } - } - } - } - } - printf("\n"); - next; - } -# -# line contains both "|" and "*" -# -npipe > 2 && nstar > 2 { - printf("\n"); - for ( j=1; j <= nstar ; j=j+2 ) { - npipe = split(s[j],p,"YXXY"); - if ( npipe > 1 ) { - for ( np=1; np<=npipe; np=np+2 ) { - this=p[np]; - put_this(); - i=np+1;find_tag1(); - } - } else { - this=s[j]; - put_this(); - } - jj=j+1; - nbla = split(s[jj],blata," "); - if ( jj <= nstar && nbla == 1 && s[jj] != "" ) { - printf("*<A NAME=\"%s\"></A>",s[jj]); - printf("<B>%s</B>*",s[jj]); - } else { - if ( s[jj] != "" ) { - printf("*%s*",s[jj]); - } - } - } - printf("\n"); - next; - } -# -# line contains e-mail address john.doe@some.place.edu -# -$0 ~ /@/ && $0 ~ /[a-zA-Z0-9]@[a-z]/ \ - { - nemail=split($0,em," "); - if ( substr($0,1,1) == " " ) { printf(" "); } - for ( i=1; i <= nemail; i++ ) { - if ( em[i] ~ /@/ ) { - if ( substr(em[i],2,3) == "lt;" && substr(em[i],length(em[i])-2,3) == "gt;" ) { - mailaddr=substr(em[i],5,length(em[i])-8); - printf("<A HREF=\"mailto:%s\"><%s></A> ",mailaddr,mailaddr); - } else { - if ( substr(em[i],2,3) == "lt;" && substr(em[i],length(em[i])-3,3) == "gt;" ) { - mailaddr=substr(em[i],5,length(em[i])-9); - printf("<A HREF=\"mailto:%s\"><%s></A>%s ",mailaddr,mailaddr,substr(em[i],length(em[i]),1)); - } else { - printf("<A HREF=\"mailto:%s\">%s</A> ",em[i],em[i]); - } - } - } else { - printf("%s ",em[i]); - } - } - #print "*** " NR " " FILENAME " - possible mail ref"; - printf("\n"); - next; - } -# -# line contains http / ftp reference -# -$0 ~ /http:\/\// || $0 ~ /ftp:\/\// { - gsub("URL:",""); - gsub("<",""); - gsub(">",""); - gsub("\\(",""); - gsub("\\)",""); - nemail=split($0,em," "); - for ( i=1; i <= nemail; i++ ) { - if ( substr(em[i],1,5) == "http:" || - substr(em[i],1,4) == "ftp:" ) { - if ( substr(em[i],length(em[i]),1) != "." ) { - printf(" <A HREF=\"%s\">%s</A>",em[i],em[i]); - } else { - em[i]=substr(em[i],1,length(em[i])-1); - printf(" <A HREF=\"%s\">%s</A>.",em[i],em[i]); - } - } else { - printf(" %s",em[i]); - } - } - #print "*** " NR " " FILENAME " - possible http ref"; - printf("\n"); - next; - } -# -# some lines contains just one "almost regular" "*"... -# -nstar == 2 { - this=s[1]; - put_this(); - printf("*"); - this=s[2]; - put_this(); - printf("\n"); - next; - } -# -# regular line -# - { ntabs = split($0,tb," "); - for ( i=1; i < ntabs ; i++) { - this=tb[i]; - put_this(); - printf(" "); - } - this=tb[ntabs]; - put_this(); - printf("\n"); - } - - -asciiart == "yes" && $0 ~ /\+-\+--/ \ - && $0 ~ "scrollbar" { asciiart = "no"; } - -END { - topback(); - print "</PRE>\n</BODY>\n\n\n</HTML>"; } - -# -# as main we keep index.txt (by default) -# -function topback () { - if ( FILENAME != "tags" ) { - if ( FILENAME != "help.txt" ) { - printf("<A HREF=\"#top\">top</A> - "); - printf("<A HREF=\"index.html\">main help file</A>\n"); - } else { - printf("<A HREF=\"#top\">top</A>\n"); - } - } -} - -function find_tag1() { - if ( p[i] == "" ) { return; } - if ( tagkey[p[i]] == "yes" ) { - which=tagref[p[i]]; - put_href(); - return; - } - # if not found, then we have a problem - print "============================================" >>"errors.log"; - print FILENAME ", line " NR ", pointer: >>" p[i] "<<" >>"errors.log"; - print $0 >>"errors.log"; - which="intro.html"; - put_href(); -} - -function see_tag() { -# ad-hoc code: -if ( atag == "\"--" || atag == "--\"" ) { return; } -if_already(); -if ( already == "yes" ) { - printf("%s",aword); - return; - } -allow_one_char="no"; -find_tag2(); -if ( done == "yes" ) { return; } -rightchar=substr(atag,length(atag),1); -if ( rightchar == "." \ - || rightchar == "," \ - || rightchar == ":" \ - || rightchar == ";" \ - || rightchar == "!" \ - || rightchar == "?" \ - || rightchar == ")" ) { - atag=substr(atag,1,length(atag)-1); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - find_tag2(); - if ( done == "yes" ) { printf("%s",rightchar);return; } - leftchar=substr(atag,1,1); - lastbut1=substr(atag,length(atag),1); - if ( leftchar == "'" && lastbut1 == "'" ) { - allow_one_char="yes"; - atag=substr(atag,2,length(atag)-2); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",leftchar); - aword=substr(atag,1,length(atag))""lastbut1""rightchar; - find_tag2(); - if ( done == "yes" ) { printf("%s%s",lastbut1,rightchar);return; } - } - } -atag=aword; -leftchar=substr(atag,1,1); -if ( leftchar == "'" && rightchar == "'" ) { - allow_one_char="yes"; - atag=substr(atag,2,length(atag)-2); - if ( atag == "<" ) { printf(" |%s|%s| ",atag,p[2]); } - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",leftchar); - find_tag2(); - if ( done == "yes" ) { printf("%s",rightchar);return; } - printf("%s%s",atag,rightchar); - return; - } -last2=substr(atag,length(atag)-1,2); -first2=substr(atag,1,2); -if ( first2 == "('" && last2 == "')" ) { - allow_one_char="yes"; - atag=substr(atag,3,length(atag)-4); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",first2); - find_tag2(); - if ( done == "yes" ) { printf("%s",last2);return; } - printf("%s%s",atag,last2); - return; - } -if ( last2 == ".)" ) { - atag=substr(atag,1,length(atag)-2); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - find_tag2(); - if ( done == "yes" ) { printf("%s",last2);return; } - printf("%s%s",atag,last2); - return; - } -if ( last2 == ")." ) { - atag=substr(atag,1,length(atag)-2); - find_tag2(); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - if ( done == "yes" ) { printf("%s",last2);return; } - printf("%s%s",atag,last2); - return; - } -first6=substr(atag,1,6); -last6=substr(atag,length(atag)-5,6); -if ( last6 == atag ) { - printf("%s",aword); - return; - } -last6of7=substr(atag,length(atag)-6,6); -if ( first6 == """ && last6of7 == """ && length(atag) > 12 ) { - allow_one_char="yes"; - atag=substr(atag,7,length(atag)-13); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",first6); - find_tag2(); - if ( done == "yes" ) { printf(""%s",rightchar); return; } - printf("%s"%s",atag,rightchar); - return; - } -if ( first6 == """ && last6 != """ ) { - allow_one_char="yes"; - atag=substr(atag,7,length(atag)-6); - if ( atag == "[" ) { printf(""%s",atag); return; } - if ( atag == "." ) { printf(""%s",atag); return; } - if ( atag == ":" ) { printf(""%s",atag); return; } - if ( atag == "a" ) { printf(""%s",atag); return; } - if ( atag == "A" ) { printf(""%s",atag); return; } - if ( atag == "g" ) { printf(""%s",atag); return; } - if_already(); - if ( already == "yes" ) { - printf(""%s",atag); - return; - } - printf("%s",first6); - find_tag2(); - if ( done == "yes" ) { return; } - printf("%s",atag); - return; - } -if ( last6 == """ && first6 == """ ) { - allow_one_char="yes"; - atag=substr(atag,7,length(atag)-12); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",first6); - find_tag2(); - if ( done == "yes" ) { printf("%s",last6);return; } - printf("%s%s",atag,last6); - return; - } -last6of7=substr(atag,length(atag)-6,6); -if ( last6of7 == """ && first6 == """ ) { - allow_one_char="yes"; - atag=substr(atag,7,length(atag)-13); - #printf("\natag=%s,aword=%s\n",atag,aword); - if_already(); - if ( already == "yes" ) { - printf("%s",aword); - return; - } - printf("%s",first6); - find_tag2(); - if ( done == "yes" ) { printf("%s%s",last6of7,rightchar);return; } - printf("%s%s%s",atag,last6of7,rightchar); - return; - } -printf("%s",aword); -} - -function find_tag2() { - done="no"; - # no blanks present in a tag... - ntags=split(atag,blata,"[ ]"); - if ( ntags > 1 ) { return; } - if ( ( allow_one_char == "no" ) && \ - ( index("!#$%&'()+,-./0:;=?@ACINX\\[\\]^_`at\\{\\}~",atag) !=0 ) ) { - return; - } - if ( skip_word[atag] == "yes" ) { return; } - if ( wasset == "yes" && lineset == NR ) { - wasset="no"; - see_opt(); - if ( done_opt == "yes" ) {return;} - } - if ( wasset == "yes" && lineset != NR ) { - wasset="no"; - } - if ( atag == ":set" ) { - wasset="yes"; - lineset=NR; - } - if ( tagkey[atag] == "yes" ) { - which=tagref[atag]; - put_href2(); - done="yes"; - } -} - -function find_tag3() { - done="no"; - # no blanks present in a tag... - ntags=split(btag,blata,"[ ]"); - if ( ntags > 1 ) { return; } - if ( ( allow_one_char == "no" ) && \ - ( index("!#$%&'()+,-./0:;=?@ACINX\\[\\]^_`at\\{\\}~",btag) !=0 ) ) { - return; - } - if ( skip_word[btag] == "yes" ) { return; } - if ( tagkey[btag] == "yes" ) { - which=tagref[btag]; - put_href3(); - done="yes"; - } -} - -function put_href() { - if ( p[i] == "" ) { return; } - if ( which == FILENAME ) { - printf("|<A HREF=\"#%s\">%s</A>|",p[i],p[i]); - } - else { - nz=split(which,zz,"."); - if ( zz[2] == "txt" || zz[1] == "tags" ) { - printf("|<A HREF=\"%s.html#%s\">%s</A>|",zz[1],p[i],p[i]); - } - else { - printf("|<A HREF=\"intro.html#%s\">%s</A>|",p[i],p[i]); - } - } -} - -function put_href2() { - if ( atag == "" ) { return; } - if ( which == FILENAME ) { - printf("<A HREF=\"#%s\">%s</A>",atag,atag); - } - else { - nz=split(which,zz,"."); - if ( zz[2] == "txt" || zz[1] == "tags" ) { - printf("<A HREF=\"%s.html#%s\">%s</A>",zz[1],atag,atag); - } - else { - printf("<A HREF=\"intro.html#%s\">%s</A>",atag,atag); - } - } -} - -function put_href3() { - if ( btag == "" ) { return; } - if ( which == FILENAME ) { - printf("<A HREF=\"#%s\">%s</A>",btag,btag2); - } - else { - nz=split(which,zz,"."); - if ( zz[2] == "txt" || zz[1] == "tags" ) { - printf("<A HREF=\"%s.html#%s\">%s</A>",zz[1],btag,btag2); - } - else { - printf("<A HREF=\"intro.html#%s\">%s</A>",btag,btag2); - } - } -} - -function put_this() { - ntab=split(this,ta," "); - for ( nta=1 ; nta <= ntab ; nta++ ) { - ata=ta[nta]; - lata=length(ata); - aword=""; - for ( iata=1 ; iata <=lata ; iata++ ) { - achar=substr(ata,iata,1); - if ( achar != " " ) { aword=aword""achar; } - else { - if ( aword != "" ) { atag=aword; - see_tag(); - aword=""; - printf(" "); } - else { - printf(" "); - } - } - } - if ( aword != "" ) { atag=aword; - see_tag(); - } - if ( nta != ntab ) { printf(" "); } - } -} - -function if_already() { - already="no"; - if ( npipe < 2 ) { return; } - if ( atag == ":au" && p[2] == ":autocmd" ) { already="yes";return; } - for ( npp=2 ; npp <= npipe ; npp=npp+2 ) { - if ( ( (index(p[npp],atag)) != 0 \ - && length(p[npp]) > length(atag) \ - && length(atag) >= 1 \ - ) \ - || (p[npp] == atag) \ - ) { - # printf("p=|%s|,tag=|%s| ",p[npp],atag); - already="yes"; return; } - } -} - -function see_opt() { - done_opt="no"; - stag=atag; - nfields = split(atag,tae,"="); - if ( nfields > 1 ) { - btag="'"tae[1]"'"; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - for ( ntae=2 ; ntae <= nfields ; ntae++ ) { - printf("=%s",tae[ntae]); - } - atag=stag; - done_opt="yes"; - return; - } - btag=tae[1]; - btag2=tae[1]; - find_tag3(); - if ( done=="yes" ) { - for ( ntae=2 ; ntae <= nfields ; ntae++ ) { - printf("=%s",tae[ntae]); - } - atag=stag; - done_opt="yes"; - return; - } - } - nfields = split(atag,tae,"""); - if ( nfields > 1 ) { - btag="'"tae[1]"'"; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - printf("""); - atag=stag; - done_opt="yes"; - return; - } - btag=tae[1]; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - printf("""); - atag=stag; - done_opt="yes"; - return; - } - } - btag="'"tae[1]"'"; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - atag=stag; - done_opt="yes"; - return; - } - btag=tae[1]; - btag2=tae[1]; - find_tag3(); - if (done == "yes") { - atag=stag; - done_opt="yes"; - return; - } - atag=stag; -} diff --git a/runtime/doc/maketags.awk b/runtime/doc/maketags.awk deleted file mode 100644 index c6b2cd91f3..0000000000 --- a/runtime/doc/maketags.awk +++ /dev/null @@ -1,42 +0,0 @@ -BEGIN { FS=" "; } - -NR == 1 { nf=split(FILENAME,f,".") - print "<HTML>"; - print "<HEAD><TITLE>" f[1] "</TITLE></HEAD>"; - print "<BODY BGCOLOR=\"#ffffff\">"; - print "<H1>Vim Documentation: " f[1] "</H1>"; - print "<A NAME=\"top\"></A>"; - print "<HR>"; - print "<PRE>"; -} - -{ - # - # protect special chars - # - gsub(/&/,"\\&"); - gsub(/>/,"\\>"); - gsub(/</,"\\<"); - gsub(/"/,"\\""); - gsub(/%/,"\\%"); - - nf=split($0,tag," "); - tagkey[t]=tag[1];tagref[t]=tag[2];tagnum[t]=NR; - print $1 " " $2 " line " NR >"tags.ref" - n=split($2,w,"."); - printf ("|<A HREF=\"%s.html#%s\">%s</A>| %s\n",w[1],$1,$1,$2); -} - -END { - topback(); - print "</PRE>\n</BODY>\n\n\n</HTML>"; - } - -# -# as main we keep index.txt (by default) -# other candidate, help.txt -# -function topback () { - printf("<A HREF=\"#top\">top</A> - "); - printf("<A HREF=\"help.html\">back to help</A>\n"); -} diff --git a/runtime/doc/map.txt b/runtime/doc/map.txt index ca1ddaabd4..cbc92a8cb5 100644 --- a/runtime/doc/map.txt +++ b/runtime/doc/map.txt @@ -1623,11 +1623,11 @@ The valid escape sequences are *<mods>* *<q-mods>* *:command-modifiers* <mods> The command modifiers, if specified. Otherwise, expands to nothing. Supported modifiers are |:aboveleft|, |:belowright|, - |:botright|, |:browse|, |:confirm|, |:hide|, |:keepalt|, - |:keepjumps|, |:keepmarks|, |:keeppatterns|, |:leftabove|, - |:lockmarks|, |:noautocmd|, |:noswapfile| |:rightbelow|, - |:sandbox|, |:silent|, |:tab|, |:topleft|, |:unsilent|, - |:verbose|, and |:vertical|. + |:botright|, |:browse|, |:confirm|, |:hide|, |:horizontal|, + |:keepalt|, |:keepjumps|, |:keepmarks|, |:keeppatterns|, + |:leftabove|, |:lockmarks|, |:noautocmd|, |:noswapfile| + |:rightbelow|, |:sandbox|, |:silent|, |:tab|, |:topleft|, + |:unsilent|, |:verbose|, and |:vertical|. Note that |:filter| is not supported. Examples: > command! -nargs=+ -complete=file MyEdit @@ -1660,7 +1660,8 @@ The valid escape sequences are If the first two characters of an escape sequence are "q-" (for example, <q-args>) then the value is quoted in such a way as to make it a valid value for use in an expression. This uses the argument as one single value. -When there is no argument <q-args> is an empty string. +When there is no argument <q-args> is an empty string. See the +|q-args-example| below. *<f-args>* To allow commands to pass their arguments on to a user-defined function, there is a special form <f-args> ("function args"). This splits the command @@ -1670,10 +1671,10 @@ See the Mycmd example below. If no arguments are given <f-args> is removed. To embed whitespace into an argument of <f-args>, prepend a backslash. <f-args> replaces every pair of backslashes (\\) with one backslash. A backslash followed by a character other than white space or a backslash -remains unmodified. Overview: +remains unmodified. Also see |f-args-example| below. Overview: command <f-args> ~ - XX ab 'ab' + XX ab "ab" XX a\b 'a\b' XX a\ b 'a b' XX a\ b 'a ', 'b' @@ -1684,7 +1685,8 @@ remains unmodified. Overview: XX a\\\\b 'a\\b' XX a\\\\ b 'a\\', 'b' -Examples > + +Examples for user commands: > " Delete everything after here to the end :com Ddel +,$d @@ -1700,7 +1702,8 @@ Examples > " Count the number of lines in the range :com! -range -nargs=0 Lines echo <line2> - <line1> + 1 "lines" - " Call a user function (example of <f-args>) +< *f-args-example* +Call a user function (example of <f-args>) > :com -nargs=* Mycmd call Myfunc(<f-args>) When executed as: > @@ -1708,7 +1711,8 @@ When executed as: > This will invoke: > :call Myfunc("arg1","arg2") - :" A more substantial example +< *q-args-example* +A more substantial example: > :function Allargs(command) : let i = 0 : while i < argc() diff --git a/runtime/doc/mbyte.txt b/runtime/doc/mbyte.txt index 2aa49cee1e..dd2c99669c 100644 --- a/runtime/doc/mbyte.txt +++ b/runtime/doc/mbyte.txt @@ -86,9 +86,8 @@ You can also set 'guifont' alone, the Nvim GUI will try to find a matching INPUT There are several ways to enter multibyte characters: -- For X11 XIM can be used. See |XIM|. -- For MS-Windows IME can be used. See |IME|. -- For all systems keymaps can be used. See |mbyte-keymap|. +- Your system IME can be used. +- Keymaps can be used. See |mbyte-keymap|. The options 'iminsert', 'imsearch' and 'imcmdline' can be used to choose the different input methods or disable them temporarily. @@ -335,8 +334,8 @@ Vim will automatically convert from one to another encoding in several places: "utf-8" (requires a gettext version that supports this). - When reading a Vim script where |:scriptencoding| is different from "utf-8". -Most of these require the |+iconv| feature. Conversion for reading and -writing files may also be specified with the 'charconvert' option. +Most of these require iconv. Conversion for reading and writing files may +also be specified with the 'charconvert' option. Useful utilities for converting the charset: All: iconv diff --git a/runtime/doc/motion.txt b/runtime/doc/motion.txt index 511b1bd7b2..8ff4ed4f96 100644 --- a/runtime/doc/motion.txt +++ b/runtime/doc/motion.txt @@ -831,12 +831,12 @@ deletes the lines from the cursor position to mark 't'. Hint: Use mark 't' for Top, 'b' for Bottom, etc.. Lowercase marks are restored when using undo and redo. -Uppercase marks 'A to 'Z include the file name. -You can use them to jump from file to file. You can only use an uppercase -mark with an operator if the mark is in the current file. The line number of -the mark remains correct, even if you insert/delete lines or edit another file -for a moment. When the 'shada' option is not empty, uppercase marks are -kept in the .shada file. See |shada-file-marks|. +Uppercase marks 'A to 'Z include the file name. You can use them to jump from +file to file. You can only use an uppercase mark with an operator if the mark +is in the current file. The line number of the mark remains correct, even if +you insert/delete lines or edit another file for a moment. When the 'shada' +option is not empty, uppercase marks are kept in the .shada file. See +|shada-file-marks|. Numbered marks '0 to '9 are quite different. They can not be set directly. They are only present when using a shada file |shada-file|. Basically '0 @@ -1172,7 +1172,7 @@ g; Go to [count] older position in change list. (not a motion command) *g,* *E663* -g, Go to [count] newer cursor position in change list. +g, Go to [count] newer position in change list. Just like |g;| but in the opposite direction. (not a motion command) diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt new file mode 100644 index 0000000000..0fdd7aaaf9 --- /dev/null +++ b/runtime/doc/news.txt @@ -0,0 +1,39 @@ +*news.txt* Nvim + + + NVIM REFERENCE MANUAL + + +Notable changes in Nvim 0.9 from 0.8 *news* + + Type |gO| to see the table of contents. + +============================================================================== +BREAKING CHANGES *news-breaking* + +The following changes may require adaptations in user config or plugins. + +============================================================================== +NEW FEATURES *news-features* + +The following new APIs or features were added. + +============================================================================== +CHANGED FEATURES *news-changes* + +The following changes to existing APIs or features add new behavior. + +============================================================================== +REMOVED FEATURES *news-removed* + +The following deprecated functions or APIs were removed. + +============================================================================== +DEPRECATIONS *news-deprecations* + +The following functions are now deprecated and will be removed in the next +release. + + + + vim:tw=78:ts=8:sw=2:et:ft=help:norl: diff --git a/runtime/doc/nvim.txt b/runtime/doc/nvim.txt index 513d27ccad..203f57024c 100644 --- a/runtime/doc/nvim.txt +++ b/runtime/doc/nvim.txt @@ -1,10 +1,10 @@ *nvim.txt* Nvim - NVIM REFERENCE MANUAL + NVIM REFERENCE MANUAL -Nvim *nvim* *nvim-intro* +Nvim *nvim* *nvim-intro* Nvim is based on Vim by Bram Moolenaar. @@ -14,13 +14,13 @@ If you are new to Vim, try the 30-minute tutorial: > :Tutor<Enter> Nvim is emphatically a fork of Vim, not a clone: compatibility with Vim -(especially editor and VimL features) is maintained where possible. See +(especially editor and Vimscript features) is maintained where possible. See |vim-differences| for the complete reference of differences from Vim. - Type |gO| to see the table of contents. + Type |gO| to see the table of contents. ============================================================================== -Transitioning from Vim *nvim-from-vim* +Transitioning from Vim *nvim-from-vim* 1. To start the transition, create your |init.vim| (user config) file: > @@ -38,32 +38,37 @@ Transitioning from Vim *nvim-from-vim* See |provider-python| and |provider-clipboard| for additional software you might need to use some features. -Your Vim configuration might not be entirely Nvim-compatible. -See |vim-differences| for the full list of changes. - -The |'ttymouse'| option, for example, was removed from Nvim (mouse support -should work without it). If you use the same |vimrc| for Vim and Nvim, -consider guarding |'ttymouse'| in your configuration like so: +Your Vim configuration might not be entirely Nvim-compatible (see +|vim-differences|). For example the |'ttymouse'| option was removed from Nvim, +because mouse support is always enabled if possible. If you use the same +|vimrc| for Vim and Nvim you could guard |'ttymouse'| in your configuration +like so: > if !has('nvim') set ttymouse=xterm2 endif -< -Conversely, if you have Nvim specific configuration items, you could do -this: + +And for Nvim-specific configuration, you can do this: > if has('nvim') tnoremap <Esc> <C-\><C-n> endif -< + For a more granular approach use |exists()|: > if exists(':tnoremap') tnoremap <Esc> <C-\><C-n> endif -< + Now you should be able to explore Nvim more comfortably. Check |nvim-features| for more information. + *portable-config* +Because Nvim follows the XDG |base-directories| standard, configuration on +Windows is stored in ~/AppData instead of ~/.config. But you can still share +the same Nvim configuration on all of your machines, by creating +~/AppData/Local/nvim/init.vim containing just this line: > + source ~/.config/nvim/init.vim + ============================================================================== - vim:tw=78:ts=8:noet:ft=help:norl: + vim:tw=78:ts=8:et:ft=help:norl: diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 2e0c1f8cc4..522819a320 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -1337,9 +1337,14 @@ A jump table for the options with a short description can be found at |Q_op|. page can have a different value. When 'cmdheight' is zero, there is no command-line unless it is being - used. Some informative messages will not be displayed, any other - messages will cause the |hit-enter| prompt. Expect some other - unexpected behavior too. + used. The command-line will cover the last line of the screen when + shown. + + WARNING: `cmdheight=0` is considered experimental. Expect some + unwanted behaviour. Some 'shortmess' flags and similar + mechanism might fail to take effect, causing unwanted hit-enter + prompts. Some informative messages, both from Nvim itself and + plugins, will not be displayed. *'cmdwinheight'* *'cwh'* 'cmdwinheight' 'cwh' number (default 7) @@ -2123,9 +2128,9 @@ A jump table for the options with a short description can be found at |Q_op|. security reasons. *'display'* *'dy'* -'display' 'dy' string (default "lastline,msgsep") +'display' 'dy' string (default "lastline") global - Change the way text is displayed. This is comma-separated list of + Change the way text is displayed. This is a comma-separated list of flags: lastline When included, as much as possible of the last line in a window will be displayed. "@@@" is put in the @@ -2135,14 +2140,14 @@ A jump table for the options with a short description can be found at |Q_op|. column of the last screen line. Overrules "lastline". uhex Show unprintable characters hexadecimal as <xx> instead of using ^C and ~C. - msgsep When showing messages longer than 'cmdheight', only - scroll the message lines, not the entire screen. The - separator line is decorated by |hl-MsgSeparator| and - the "msgsep" flag of 'fillchars'. + msgsep Obsolete flag. Allowed but takes no effect. |msgsep| When neither "lastline" nor "truncate" is included, a last line that doesn't fit is replaced with "@" lines. + The "@" character can be changed by setting the "lastline" item in + 'fillchars'. The character is highlighted with |hl-NonText|. + *'eadirection'* *'ead'* 'eadirection' 'ead' string (default "both") global @@ -2454,28 +2459,31 @@ A jump table for the options with a short description can be found at |Q_op|. *'fillchars'* *'fcs'* 'fillchars' 'fcs' string (default "") global or local to window |global-local| - Characters to fill the statuslines and vertical separators. - It is a comma-separated list of items: + Characters to fill the statuslines, vertical separators and special + lines in the window. + It is a comma-separated list of items. Each item has a name, a colon + and the value of that item: item default Used for ~ - stl:c ' ' or '^' statusline of the current window - stlnc:c ' ' or '=' statusline of the non-current windows - wbr:c ' ' window bar - horiz:c '─' or '-' horizontal separators |:split| - horizup:c 'â”´' or '-' upwards facing horizontal separator - horizdown:c '┬' or '-' downwards facing horizontal separator - vert:c '│' or '|' vertical separators |:vsplit| - vertleft:c '┤' or '|' left facing vertical separator - vertright:c '├' or '|' right facing vertical separator - verthoriz:c '┼' or '+' overlapping vertical and horizontal + stl ' ' or '^' statusline of the current window + stlnc ' ' or '=' statusline of the non-current windows + wbr ' ' window bar + horiz '─' or '-' horizontal separators |:split| + horizup 'â”´' or '-' upwards facing horizontal separator + horizdown '┬' or '-' downwards facing horizontal separator + vert '│' or '|' vertical separators |:vsplit| + vertleft '┤' or '|' left facing vertical separator + vertright '├' or '|' right facing vertical separator + verthoriz '┼' or '+' overlapping vertical and horizontal separator - fold:c '·' or '-' filling 'foldtext' - foldopen:c '-' mark the beginning of a fold - foldclose:c '+' show a closed fold - foldsep:c '│' or '|' open fold middle marker - diff:c '-' deleted lines of the 'diff' option - msgsep:c ' ' message separator 'display' - eob:c '~' empty lines at the end of a buffer + fold '·' or '-' filling 'foldtext' + foldopen '-' mark the beginning of a fold + foldclose '+' show a closed fold + foldsep '│' or '|' open fold middle marker + diff '-' deleted lines of the 'diff' option + msgsep ' ' message separator 'display' + eob '~' empty lines at the end of a buffer + lastline '@' 'display' contains lastline/truncate Any one that is omitted will fall back to the default. For "stl" and "stlnc" the space will be used when there is highlighting, '^' or '=' @@ -2500,19 +2508,20 @@ A jump table for the options with a short description can be found at |Q_op|. The highlighting used for these items: item highlight group ~ - stl:c StatusLine |hl-StatusLine| - stlnc:c StatusLineNC |hl-StatusLineNC| - wbr:c WinBar |hl-WinBar| or |hl-WinBarNC| - horiz:c WinSeparator |hl-WinSeparator| - horizup:c WinSeparator |hl-WinSeparator| - horizdown:c WinSeparator |hl-WinSeparator| - vert:c WinSeparator |hl-WinSeparator| - vertleft:c WinSeparator |hl-WinSeparator| - vertright:c WinSeparator |hl-WinSeparator| - verthoriz:c WinSeparator |hl-WinSeparator| - fold:c Folded |hl-Folded| - diff:c DiffDelete |hl-DiffDelete| - eob:c EndOfBuffer |hl-EndOfBuffer| + stl StatusLine |hl-StatusLine| + stlnc StatusLineNC |hl-StatusLineNC| + wbr WinBar |hl-WinBar| or |hl-WinBarNC| + horiz WinSeparator |hl-WinSeparator| + horizup WinSeparator |hl-WinSeparator| + horizdown WinSeparator |hl-WinSeparator| + vert WinSeparator |hl-WinSeparator| + vertleft WinSeparator |hl-WinSeparator| + vertright WinSeparator |hl-WinSeparator| + verthoriz WinSeparator |hl-WinSeparator| + fold Folded |hl-Folded| + diff DiffDelete |hl-DiffDelete| + eob EndOfBuffer |hl-EndOfBuffer| + lastline NonText |hl-NonText| *'fixendofline'* *'fixeol'* *'nofixendofline'* *'nofixeol'* 'fixendofline' 'fixeol' boolean (default on) @@ -3911,9 +3920,9 @@ A jump table for the options with a short description can be found at |Q_op|. `:lgrepadd`, `:cfile`, `:cgetfile`, `:caddfile`, `:lfile`, `:lgetfile`, and `:laddfile`. - This would be mostly useful when you use MS-Windows. If |+iconv| is - enabled and GNU libiconv is used, setting 'makeencoding' to "char" has - the same effect as setting to the system locale encoding. Example: > + This would be mostly useful when you use MS-Windows. If iconv is + enabled, setting 'makeencoding' to "char" has the same effect as + setting to the system locale encoding. Example: > :set makeencoding=char " system locale is used < *'makeprg'* *'mp'* @@ -4229,6 +4238,15 @@ A jump table for the options with a short description can be found at |Q_op|. The 'mousemodel' option is set by the |:behave| command. + *'mousemoveevent'* *'mousemev'* +'mousemoveevent' 'mousemev' boolean (default off) + global + When on, mouse move events are delivered to the input queue and are + available for mapping. The default, off, avoids the mouse movement + overhead except when needed. + Warning: Setting this option can make pending mappings to be aborted + when the mouse is moved. + *'mousescroll'* 'mousescroll' string (default "ver:3,hor:6") global @@ -4930,10 +4948,13 @@ A jump table for the options with a short description can be found at |Q_op|. indent/ indent scripts |indent-expression| keymap/ key mapping files |mbyte-keymap| lang/ menu translations |:menutrans| + lua/ |Lua| plugins menu.vim GUI menus |menu.vim| pack/ packages |:packadd| + parser/ |treesitter| syntax parsers plugin/ plugin scripts |write-plugin| print/ files for printing |postscript-print-encoding| + query/ |treesitter| queries rplugin/ |remote-plugin| scripts spell/ spell checking files |spell| syntax/ syntax files |mysyntaxfile| @@ -4954,20 +4975,20 @@ A jump table for the options with a short description can be found at |Q_op|. but are not part of the Nvim distribution. XDG_DATA_DIRS defaults to /usr/local/share/:/usr/share/, so system administrators are expected to install site plugins to /usr/share/nvim/site. - 5. Applications state home directory, for files that contain your - session state (eg. backupdir, viewdir, undodir, etc). + 5. Session state directory, for state data such as swap, backupdir, + viewdir, undodir, etc. Given by `stdpath("state")`. |$XDG_STATE_HOME| - 6. $VIMRUNTIME, for files distributed with Neovim. + 6. $VIMRUNTIME, for files distributed with Nvim. *after-directory* 7, 8, 9, 10. In after/ subdirectories of 1, 2, 3 and 4, with reverse - ordering. This is for preferences to overrule or add to the + ordering. This is for preferences to overrule or add to the distributed defaults or system-wide settings (rarely needed). - *rtp-packages* - "start" packages will additionally be used to search for runtime files - after these, but package entries are not visible in `:set rtp`. - See |runtime-search-path| for more information. "opt" packages - will be explicitly added to &rtp when |:packadd| is used. + *packages-runtimepath* + "start" packages will also be searched (|runtime-search-path|) for + runtime files after these, though such packages are not explicitly + reported in &runtimepath. But "opt" packages are explicitly added to + &runtimepath by |:packadd|. Note that, unlike 'path', no wildcards like "**" are allowed. Normal wildcards are allowed, but can significantly slow down searching for @@ -4977,18 +4998,13 @@ A jump table for the options with a short description can be found at |Q_op|. Example: > :set runtimepath=~/vimruntime,/mygroup/vim,$VIMRUNTIME < This will use the directory "~/vimruntime" first (containing your - personal Vim runtime files), then "/mygroup/vim" (shared between a - group of people) and finally "$VIMRUNTIME" (the distributed runtime - files). - You probably should always include $VIMRUNTIME somewhere, to use the - distributed runtime files. You can put a directory before $VIMRUNTIME - to find files which replace a distributed runtime files. You can put - a directory after $VIMRUNTIME to find files which add to distributed - runtime files. - When Vim is started with |--clean| the home directory entries are not - included. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. + personal Nvim runtime files), then "/mygroup/vim", and finally + "$VIMRUNTIME" (the default runtime files). + You can put a directory before $VIMRUNTIME to find files which replace + distributed runtime files. You can put a directory after $VIMRUNTIME + to find files which add to distributed runtime files. + + With |--clean| the home directory entries are not included. *'scroll'* *'scr'* 'scroll' 'scr' number (default: half the window height) @@ -5341,7 +5357,7 @@ A jump table for the options with a short description can be found at |Q_op|. To use PowerShell: > let &shell = executable('pwsh') ? 'pwsh' : 'powershell' let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;' - let &shellredir = '-RedirectStandardOutput %s -NoNewWindow -Wait' + let &shellredir = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode' let &shellpipe = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode' set shellquote= shellxquote= @@ -5692,7 +5708,7 @@ A jump table for the options with a short description can be found at |Q_op|. "yes:[1-9]" always, with fixed space for signs up to the given number (maximum 9), e.g. "yes:3" "number" display signs in the 'number' column. If the number - column is not present, then behaves like 'auto'. + column is not present, then behaves like "auto". Note regarding 'orphaned signs': with signcolumn numbers higher than 1, deleting lines will also remove the associated signs automatically, @@ -5860,10 +5876,14 @@ A jump table for the options with a short description can be found at |Q_op|. 'spelloptions' 'spo' string (default "") local to buffer A comma-separated list of options for spell checking: - camel When a word is CamelCased, assume "Cased" is a + camel When a word is CamelCased, assume "Cased" is a separate word: every upper-case character in a word that comes after a lower case character indicates the start of a new word. + noplainbuffer Only spellcheck a buffer when 'syntax' is enabled, + or when extmarks are set within the buffer. Only + designated regions of the buffer are spellchecked in + this case. *'spellsuggest'* *'sps'* 'spellsuggest' 'sps' string (default "best") @@ -5939,6 +5959,22 @@ A jump table for the options with a short description can be found at |Q_op|. When on, splitting a window will put the new window below the current one. |:split| + *'splitkeep'* *'spk'* +'splitkeep' 'spk' string (default "cursor") + global + The value of this option determines the scroll behavior when opening, + closing or resizing horizontal splits. + + Possible values are: + cursor Keep the same relative cursor position. + screen Keep the text on the same screen line. + topline Keep the topline the same. + + For the "screen" and "topline" values, the cursor position will be + changed when necessary. In this case, the jumplist will be populated + with the previous cursor position. For "screen", the text cannot always + be kept on the same screen line when 'wrap' is enabled. + *'splitright'* *'spr'* *'nosplitright'* *'nospr'* 'splitright' 'spr' boolean (default off) global @@ -6465,7 +6501,7 @@ A jump table for the options with a short description can be found at |Q_op|. 'termguicolors' 'tgc' boolean (default off) global Enables 24-bit RGB color in the |TUI|. Uses "gui" |:highlight| - attributes instead of "cterm" attributes. |highlight-guifg| + attributes instead of "cterm" attributes. |guifg| Requires an ISO-8613-3 compatible terminal. *'termpastefilter'* *'tpf'* @@ -6732,11 +6768,11 @@ A jump table for the options with a short description can be found at |Q_op|. final value applying to all subsequent tabs. For example, when editing assembly language files where statements - start in the 8th column and comments in the 40th, it may be useful + start in the 9th column and comments in the 41st, it may be useful to use the following: > :set varsofttabstop=8,32,8 -< This will set soft tabstops at the 8th and 40th columns, and at every - 8th column thereafter. +< This will set soft tabstops with 8 and 8 + 32 spaces, and 8 more + for every column thereafter. Note that the value of |'softtabstop'| will be ignored while 'varsofttabstop' is set. @@ -6757,28 +6793,31 @@ A jump table for the options with a short description can be found at |Q_op|. *'verbose'* *'vbs'* 'verbose' 'vbs' number (default 0) global - When bigger than zero, Vim will give messages about what it is doing. - Currently, these messages are given: - >= 1 Lua assignments to options, mappings, etc. - >= 2 When a file is ":source"'ed and when the shada file is read or written.. - >= 3 UI info, terminal capabilities - >= 4 Shell commands. - >= 5 Every searched tags file and include file. - >= 8 Files for which a group of autocommands is executed. - >= 9 Every executed autocommand. - >= 11 Finding items in a path - >= 12 Every executed function. - >= 13 When an exception is thrown, caught, finished, or discarded. - >= 14 Anything pending in a ":finally" clause. - >= 15 Every executed Ex command from a script (truncated at 200 - characters). - >= 16 Every executed Ex command. - - This option can also be set with the "-V" argument. See |-V|. - This option is also set by the |:verbose| command. - - When the 'verbosefile' option is set then the verbose messages are not - displayed. + Sets the verbosity level. Also set by |-V| and |:verbose|. + + Tracing of options in Lua scripts is activated at level 1; Lua scripts + are not traced with verbose=0, for performance. + + If greater than or equal to a given level, Nvim produces the following + messages: + + Level Messages ~ + ---------------------------------------------------------------------- + 1 Lua assignments to options, mappings, etc. + 2 When a file is ":source"'ed, or |shada| file is read or written. + 3 UI info, terminal capabilities. + 4 Shell commands. + 5 Every searched tags file and include file. + 8 Files for which a group of autocommands is executed. + 9 Executed autocommands. + 11 Finding items in a path. + 12 Vimscript function calls. + 13 When an exception is thrown, caught, finished, or discarded. + 14 Anything pending in a ":finally" clause. + 15 Ex commands from a script (truncated at 200 characters). + 16 Ex commands. + + If 'verbosefile' is set then the verbose messages are not displayed. *'verbosefile'* *'vfile'* 'verbosefile' 'vfile' string (default empty) @@ -6938,15 +6977,18 @@ A jump table for the options with a short description can be found at |Q_op|. *'wildmenu'* *'wmnu'* *'nowildmenu'* *'nowmnu'* 'wildmenu' 'wmnu' boolean (default on) global - Enables "enhanced mode" of command-line completion. When user hits - <Tab> (or 'wildchar') to invoke completion, the possible matches are - shown in a menu just above the command-line (see 'wildoptions'), with - the first match highlighted (overwriting the statusline). Keys that - show the previous/next match (<Tab>/CTRL-P/CTRL-N) highlight the - match. + When 'wildmenu' is on, command-line completion operates in an enhanced + mode. On pressing 'wildchar' (usually <Tab>) to invoke completion, + the possible matches are shown. + When 'wildoptions' contains "pum", then the completion matches are + shown in a popup menu. Otherwise they are displayed just above the + command line, with the first match highlighted (overwriting the status + line, if there is one). + Keys that show the previous/next match, such as <Tab> or + CTRL-P/CTRL-N, cause the highlight to move to the appropriate match. 'wildmode' must specify "full": "longest" and "list" do not start 'wildmenu' mode. You can check the current mode with |wildmenumode()|. - The menu is canceled when a key is hit that is not used for selecting + The menu is cancelled when a key is hit that is not used for selecting a completion. While the menu is active these keys have special meanings: @@ -7117,7 +7159,7 @@ A jump table for the options with a short description can be found at |Q_op|. the window. Note: highlight namespaces take precedence over 'winhighlight'. - See |nvim_win_set_hl_ns| and |nvim_set_hl|. + See |nvim_win_set_hl_ns()| and |nvim_set_hl()|. Highlights of vertical separators are determined by the window to the left of the separator. The 'tabline' highlight of a tabpage is diff --git a/runtime/doc/pi_health.txt b/runtime/doc/pi_health.txt index 04e04b5165..8a6437fdc8 100644 --- a/runtime/doc/pi_health.txt +++ b/runtime/doc/pi_health.txt @@ -7,11 +7,12 @@ Author: TJ DeVries <devries.timothyj@gmail.com> ============================================================================== Introduction *health* -health.vim is a minimal framework to help with troubleshooting user -configuration. Nvim ships with healthchecks for configuration, performance, -python support, ruby support, clipboard support, and more. +health.vim is a minimal framework to help users troubleshoot configuration and +any other environment conditions that a plugin might care about. Nvim ships +with healthchecks for configuration, performance, python support, ruby +support, clipboard support, and more. -To run the healthchecks, use this command: > +To run all healthchecks, use: > :checkhealth < @@ -21,7 +22,7 @@ Plugin authors are encouraged to write new healthchecks. |health-dev| Commands *health-commands* *:checkhealth* *:CheckHealth* -:checkhealth Run all healthchecks. +:checkhealth Run all healthchecks. *E5009* Nvim depends on |$VIMRUNTIME|, 'runtimepath' and 'packpath' to find the standard "runtime files" for syntax highlighting, @@ -35,23 +36,21 @@ Commands *health-commands* :checkhealth nvim < To run the healthchecks for the "foo" and "bar" plugins - (assuming these plugins are on 'runtimepath' or 'packpath' and - they have implemented the Lua or Vimscript interface - require("foo.health").check() and health#bar#check(), - respectively): > + (assuming they are on 'runtimepath' and they have implemented + the Lua `require("foo.health").check()` interface): > :checkhealth foo bar < - To run healthchecks for lua submodules, use dot notation or - "*" to refer to all submodules. For example nvim provides - `vim.lsp` and `vim.treesitter` > + To run healthchecks for Lua submodules, use dot notation or + "*" to refer to all submodules. For example Nvim provides + `vim.lsp` and `vim.treesitter`: > :checkhealth vim.lsp vim.treesitter :checkhealth vim* < ============================================================================== -Lua Functions *health-functions-lua* *health-lua* *vim.health* +Functions *health-functions* *vim.health* -The Lua "health" module can be used to create new healthchecks (see also -|health-functions-vim|). To get started, simply use: +The Lua "health" module can be used to create new healthchecks. To get started +see |health-dev|. vim.health.report_start({name}) *vim.health.report_start()* Starts a new report. Most plugins should call this only once, but if @@ -65,36 +64,43 @@ vim.health.report_ok({msg}) *vim.health.report_ok()* Reports a "success" message. vim.health.report_warn({msg} [, {advice}]) *vim.health.report_warn()* - Reports a warning. {advice} is an optional List of suggestions. + Reports a warning. {advice} is an optional list of suggestions to + present to the user. vim.health.report_error({msg} [, {advice}]) *vim.health.report_error()* - Reports an error. {advice} is an optional List of suggestions. + Reports an error. {advice} is an optional list of suggestions to + present to the user. ============================================================================== -Create a Lua healthcheck *health-dev-lua* - -Healthchecks are functions that check the user environment, configuration, -etc. Nvim has built-in healthchecks in $VIMRUNTIME/autoload/health/. - -To add a new healthcheck for your own plugin, simply define a Lua module in -your plugin that returns a table with a "check()" function. |:checkhealth| -will automatically find and invoke this function. - -If your plugin is named "foo", then its healthcheck module should be a file in -one of these locations on 'runtimepath' or 'packpath': +Create a healthcheck *health-dev* + +Healthchecks are functions that check the user environment, configuration, or +any other prerequisites that a plugin cares about. Nvim ships with +healthchecks in: + - $VIMRUNTIME/autoload/health/ + - $VIMRUNTIME/lua/vim/lsp/health.lua + - $VIMRUNTIME/lua/vim/treesitter/health.lua + - and more... + +To add a new healthcheck for your own plugin, simply create a "health.lua" +module on 'runtimepath' that returns a table with a "check()" function. Then +|:checkhealth| will automatically find and invoke the function. + +For example if your plugin is named "foo", define your healthcheck module at +one of these locations (on 'runtimepath'): - lua/foo/health/init.lua - lua/foo/health.lua -If your plugin provides a submodule named "bar" for which you want a separate -healthcheck, define the healthcheck at one of these locations on 'runtimepath' -or 'packpath': +If your plugin also provides a submodule named "bar" for which you want +a separate healthcheck, define the healthcheck at one of these locations: - lua/foo/bar/health/init.lua - lua/foo/bar/health.lua -All submodules should return a Lua table containing the method `check()`. +All such health modules must return a Lua table containing a `check()` +function. -Copy this sample code into `lua/foo/health/init.lua` or `lua/foo/health.lua`, -replacing "foo" in the path with your plugin name: > +Copy this sample code into `lua/foo/health.lua`, replacing "foo" in the path +with your plugin name: > local M = {} @@ -102,9 +108,9 @@ replacing "foo" in the path with your plugin name: > vim.health.report_start("my_plugin report") -- make sure setup function parameters are ok if check_setup() then - vim.health.report_ok("Setup function is correct") + vim.health.report_ok("Setup is correct") else - vim.health.report_error("Setup function is incorrect") + vim.health.report_error("Setup is incorrect") end -- do some more checking -- ... @@ -112,67 +118,5 @@ replacing "foo" in the path with your plugin name: > return M -============================================================================== -Vimscript Functions *health-functions-vimscript* *health-vimscript* - -health.vim functions are for creating new healthchecks. (See also -|health-functions-lua|) - -health#report_start({name}) *health#report_start* - Starts a new report. Most plugins should call this only once, but if - you want different sections to appear in your report, call this once - per section. - -health#report_info({msg}) *health#report_info* - Reports an informational message. - -health#report_ok({msg}) *health#report_ok* - Reports a "success" message. - -health#report_warn({msg} [, {advice}]) *health#report_warn* - Reports a warning. {advice} is an optional List of suggestions. - -health#report_error({msg} [, {advice}]) *health#report_error* - Reports an error. {advice} is an optional List of suggestions. - -health#{plugin}#check() *health.user_checker* - Healthcheck function for {plugin}. Called by |:checkhealth| - automatically. Example: > - - function! health#my_plug#check() abort - silent call s:check_environment_vars() - silent call s:check_python_configuration() - endfunction -< -============================================================================== -Create a healthcheck *health-dev-vim* - -Healthchecks are functions that check the user environment, configuration, -etc. Nvim has built-in healthchecks in $VIMRUNTIME/autoload/health/. - -To add a new healthcheck for your own plugin, simply define a -health#{plugin}#check() function in autoload/health/{plugin}.vim. -|:checkhealth| automatically finds and invokes such functions. - -If your plugin is named "foo", then its healthcheck function must be > - health#foo#check() - -defined in this file on 'runtimepath' or 'packpath': - - autoload/health/foo.vim - -Copy this sample code into autoload/health/foo.vim and replace "foo" with your -plugin name: > - function! health#foo#check() abort - call health#report_start('sanity checks') - " perform arbitrary checks - " ... - - if looks_good - call health#report_ok('found required dependencies') - else - call health#report_error('cannot find foo', - \ ['npm install --save foo']) - endif - endfunction vim:et:tw=78:ts=8:ft=help:fdm=marker diff --git a/runtime/doc/pi_msgpack.txt b/runtime/doc/pi_msgpack.txt index 801c56e49f..24a31f1de7 100644 --- a/runtime/doc/pi_msgpack.txt +++ b/runtime/doc/pi_msgpack.txt @@ -63,16 +63,16 @@ msgpack#is_uint({msgpack-value}) *msgpack#is_uint()* *msgpack#strftime* msgpack#strftime({format}, {msgpack-integer}) *msgpack#strftime()* Same as |strftime()|, but second argument may be - |msgpack-special-dict|. Requires |+python| or |+python3| to really - work with |msgpack-special-dict|s. + |msgpack-special-dict|. Requires |Python| to really work with + |msgpack-special-dict|s. *msgpack#strptime* msgpack#strptime({format}, {time}) *msgpack#strptime()* Reverse of |msgpack#strftime()|: for any time and format |msgpack#equal|( |msgpack#strptime|(format, |msgpack#strftime|(format, - time)), time) be true. Requires |+python| or |+python3|, without it - only supports non-|msgpack-special-dict| nonnegative times and format - equal to `%Y-%m-%dT%H:%M:%S`. + time)), time) be true. Requires ||Python|, without it only supports + non-|msgpack-special-dict| nonnegative times and format equal to + `%Y-%m-%dT%H:%M:%S`. msgpack#int_dict_to_str({msgpack-special-int}) *msgpack#int_dict_to_str()* Function which converts |msgpack-special-dict| integer value to diff --git a/runtime/doc/pi_netrw.txt b/runtime/doc/pi_netrw.txt index 1eaa76264f..972c42107c 100644 --- a/runtime/doc/pi_netrw.txt +++ b/runtime/doc/pi_netrw.txt @@ -2353,7 +2353,7 @@ MARKED FILES: DIFF *netrw-md* {{{2 (See |netrw-mf| and |netrw-mr| for how to mark files) (uses the global marked file list) -Use |vimdiff| to visualize difference between selected files (two or +Use vimdiff to visualize difference between selected files (two or three may be selected for this). Uses the global marked file list. MARKED FILES: EDITING *netrw-me* {{{2 @@ -2782,7 +2782,7 @@ your browsing preferences. (see also: |netrw-settings|) history are saved (as .netrwbook and .netrwhist). Netrw uses |expand()| on the string. - default: stdpath('data') (see |stdpath()|) + default: stdpath("data") (see |stdpath()|) *g:netrw_keepdir* =1 (default) keep current directory immune from the browsing directory. @@ -3469,7 +3469,7 @@ Example: Clear netrw's marked file list via a mapping on gu > *netrw-p4* P4. I would like long listings to be the default. {{{2 - Put the following statement into your |.vimrc|: > + Put the following statement into your |vimrc|: > let g:netrw_liststyle= 1 < @@ -3482,7 +3482,7 @@ Example: Clear netrw's marked file list via a mapping on gu > Does your system's strftime() accept the "%c" to yield dates such as "Sun Apr 27 11:49:23 1997"? If not, do a "man strftime" and find out what option should be used. Then - put it into your |.vimrc|: > + put it into your |vimrc|: > let g:netrw_timefmt= "%X" (where X is the option) < @@ -3490,7 +3490,7 @@ Example: Clear netrw's marked file list via a mapping on gu > P6. I want my current directory to track my browsing. {{{2 How do I do that? - Put the following line in your |.vimrc|: + Put the following line in your |vimrc|: > let g:netrw_keepdir= 0 < @@ -3569,7 +3569,7 @@ Example: Clear netrw's marked file list via a mapping on gu > http://www.chiark.greenend.org.uk/~sgtatham/putty/0.60/htmldoc/Chapter8.html#pubkey-gettingready (8.3 Getting ready for public key authentication) < - How to use a private key with 'pscp': > + How to use a private key with "pscp": > http://www.chiark.greenend.org.uk/~sgtatham/putty/0.60/htmldoc/Chapter5.html (5.2.4 Using public key authentication with PSCP) @@ -3839,7 +3839,7 @@ netrw: or http://vim.sourceforge.net/scripts/script.php?script_id=120 - Decho.vim is provided as a "vimball"; see |vimball-intro|. You + Decho.vim is provided as a "vimball". You should edit the Decho.vba.gz file and source it in: > vim Decho.vba.gz @@ -3917,7 +3917,7 @@ netrw: * Installed |g:netrw_clipboard| setting * Installed option bypass for |'guioptions'| a/A settings - * Changed popup_beval() to |popup_atcursor()| + * Changed popup_beval() to popup_atcursor() in netrw#ErrorMsg (lacygoill). Apparently popup_beval doesn't reliably close the popup when the mouse is moved. @@ -3943,7 +3943,7 @@ netrw: did not restore options correctly that had a single quote in the option string. Apr 13, 2020 * implemented error handling via popup - windows (see |popup_beval()|) + windows (see popup_beval()) Apr 30, 2020 * (reported by Manatsu Takahashi) while using Lexplore, a modified file could be overwritten. Sol'n: will not overwrite, diff --git a/runtime/doc/print.txt b/runtime/doc/print.txt index 924fab175e..0e02c7d42d 100644 --- a/runtime/doc/print.txt +++ b/runtime/doc/print.txt @@ -659,7 +659,7 @@ It is possible to achieve a poor man's version of duplex printing using the PS utility psselect. This utility has options -e and -o for printing just the even or odd pages of a PS file respectively. -First generate a PS file with the 'hardcopy' command, then generate new +First generate a PS file with the ":hardcopy" command, then generate new files with all the odd and even numbered pages with: > psselect -o test.ps odd.ps diff --git a/runtime/doc/provider.txt b/runtime/doc/provider.txt index 9fd35f19c5..99ec84c625 100644 --- a/runtime/doc/provider.txt +++ b/runtime/doc/provider.txt @@ -236,11 +236,27 @@ The "copy" function stores a list of lines and the register type. The "paste" function returns the clipboard as a `[lines, regtype]` list, where `lines` is a list of lines and `regtype` is a register type conforming to |setreg()|. + *clipboard-wsl* +For Windows WSL, try this g:clipboard definition: +> + let g:clipboard = { + \ 'name': 'WslClipboard', + \ 'copy': { + \ '+': 'clip.exe', + \ '*': 'clip.exe', + \ }, + \ 'paste': { + \ '+': 'powershell.exe -c [Console]::Out.Write($(Get-Clipboard -Raw).tostring().replace("`r", ""))', + \ '*': 'powershell.exe -c [Console]::Out.Write($(Get-Clipboard -Raw).tostring().replace("`r", ""))', + \ }, + \ 'cache_enabled': 0, + \ } + ============================================================================== Paste *provider-paste* *paste* "Paste" is a separate concept from |clipboard|: paste means "dump a bunch of -text to the editor", whereas clipboard provides features like |quote-+| to get +text to the editor", whereas clipboard provides features like |quote+| to get and set the OS clipboard directly. For example, middle-click or CTRL-SHIFT-v (macOS: CMD-v) in your terminal is "paste", not "clipboard": the terminal application (Nvim) just gets a stream of text, it does not interact with the diff --git a/runtime/doc/quickfix.txt b/runtime/doc/quickfix.txt index dab3bfa280..924a6d4743 100644 --- a/runtime/doc/quickfix.txt +++ b/runtime/doc/quickfix.txt @@ -466,7 +466,7 @@ You can parse a list of lines using 'errorformat' without creating or modifying a quickfix list using the |getqflist()| function. Examples: > echo getqflist({'lines' : ["F1:10:Line10", "F2:20:Line20"]}) echo getqflist({'lines' : systemlist('grep -Hn quickfix *')}) -This returns a dictionary where the 'items' key contains the list of quickfix +This returns a dictionary where the "items" key contains the list of quickfix entries parsed from lines. The following shows how to use a custom 'errorformat' to parse the lines without modifying the 'errorformat' option: > echo getqflist({'efm' : '%f#%l#%m', 'lines' : ['F1#10#Line']}) @@ -585,7 +585,7 @@ can go back to the unfiltered list using the |:colder|/|:lolder| command. quickfix command or function, the |b:changedtick| variable is incremented. You can get the number of this buffer using the getqflist() and getloclist() - functions by passing the 'qfbufnr' item. For a + functions by passing the "qfbufnr" item. For a location list, this buffer is wiped out when the location list is removed. @@ -916,7 +916,7 @@ To get the number of the current list in the stack: > screen). 5. The errorfile is read using 'errorformat'. 6. All relevant |QuickFixCmdPost| autocommands are - executed. See example below. + executed. See example below. 7. If [!] is not given the first error is jumped to. 8. The errorfile is deleted. 9. You can now move through the errors with commands @@ -1939,7 +1939,7 @@ list window is: The values displayed in each line correspond to the "bufnr", "lnum", "col" and "text" fields returned by the |getqflist()| function. -For some quickfix/location lists, the displayed text need to be customized. +For some quickfix/location lists, the displayed text needs to be customized. For example, if only the filename is present for a quickfix entry, then the two "|" field separator characters after the filename are not needed. Another use case is to customize the path displayed for a filename. By default, the @@ -1965,7 +1965,7 @@ The function should return a single line of text to display in the quickfix window for each entry from start_idx to end_idx. The function can obtain information about the entries using the |getqflist()| function and specifying the quickfix list identifier "id". For a location list, getloclist() function -can be used with the 'winid' argument. If an empty list is returned, then the +can be used with the "winid" argument. If an empty list is returned, then the default format is used to display all the entries. If an item in the returned list is an empty string, then the default format is used to display the corresponding entry. diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt index 6f16db5cc2..5b100c73a9 100644 --- a/runtime/doc/quickref.txt +++ b/runtime/doc/quickref.txt @@ -3,7 +3,8 @@ VIM REFERENCE MANUAL by Bram Moolenaar - Quick reference guide +============================================================================== +Quick reference guide *quickref* *Contents* tag subject tag subject ~ @@ -30,10 +31,10 @@ |Q_fo| Folding ------------------------------------------------------------------------------ -N is used to indicate an optional count that can be given before the command. ------------------------------------------------------------------------------- *Q_lr* Left-right motions +N is used to indicate an optional count that can be given before the command. + |h| N h left (also: CTRL-H, <BS>, or <Left> key) |l| N l right (also: <Space> or <Right> key) |0| 0 to first character in the line (also: <Home> key) @@ -56,6 +57,7 @@ N is used to indicate an optional count that can be given before the command. |;| N ; repeat the last "f", "F", "t", or "T" N times |,| N , repeat the last "f", "F", "t", or "T" N times in opposite direction + ------------------------------------------------------------------------------ *Q_ud* Up-down motions @@ -73,6 +75,7 @@ N is used to indicate an optional count that can be given before the command. given, otherwise it is the |%| command |gk| N gk up N screen lines (differs from "k" when line wraps) |gj| N gj down N screen lines (differs from "j" when line wraps) + ------------------------------------------------------------------------------ *Q_tm* Text object motions @@ -105,6 +108,7 @@ N is used to indicate an optional count that can be given before the command. |]#| N ]# N times forward to unclosed "#else" or "#endif" |[star| N [* N times back to start of comment "/*" |]star| N ]* N times forward to end of comment "*/" + ------------------------------------------------------------------------------ *Q_pa* Pattern searches @@ -168,6 +172,7 @@ N is used to indicate an optional count that can be given before the command. b[+num] [num] identical to s[+num] above (mnemonic: begin) b[-num] [num] identical to s[-num] above (mnemonic: begin) ;{search-command} execute {search-command} next + ------------------------------------------------------------------------------ *Q_ma* Marks and motions @@ -188,6 +193,7 @@ N is used to indicate an optional count that can be given before the command. |CTRL-O| N CTRL-O go to Nth older position in jump list |CTRL-I| N CTRL-I go to Nth newer position in jump list |:ju| :ju[mps] print the jump list + ------------------------------------------------------------------------------ *Q_vm* Various motions @@ -202,6 +208,7 @@ N is used to indicate an optional count that can be given before the command. |go| N go go to Nth byte in the buffer |:go| :[range]go[to] [off] go to [off] byte in the buffer + ------------------------------------------------------------------------------ *Q_ta* Using tags @@ -229,6 +236,7 @@ N is used to indicate an optional count that can be given before the command. |:ptjump| :ptj[ump] like ":tjump" but show tag in preview window |:pclose| :pc[lose] close tag preview window |CTRL-W_z| CTRL-W z close tag preview window + ------------------------------------------------------------------------------ *Q_sc* Scrolling @@ -247,6 +255,7 @@ These only work when 'wrap' is off: |zl| N zl scroll screen N characters to the left |zH| N zH scroll screen half a screenwidth to the right |zL| N zL scroll screen half a screenwidth to the left + ------------------------------------------------------------------------------ *Q_in* Inserting text @@ -263,6 +272,7 @@ These only work when 'wrap' is off: in Visual block mode: |v_b_I| I insert the same text in front of all the selected lines |v_b_A| A append the same text after all the selected lines + ------------------------------------------------------------------------------ *Q_ai* Insert mode keys @@ -279,6 +289,7 @@ moving around: |i_<S-Up>| shift-up/down one screenful backward/forward |i_<End>| <End> cursor after last character in the line |i_<Home>| <Home> cursor to first character in the line + ------------------------------------------------------------------------------ *Q_ss* Special keys in Insert mode @@ -313,6 +324,7 @@ moving around: |i_0_CTRL-D| 0 CTRL-D delete all indent in the current line |i_^_CTRL-D| ^ CTRL-D delete all indent in the current line, restore indent in next line + ------------------------------------------------------------------------------ *Q_di* Digraphs @@ -325,12 +337,14 @@ In Insert or Command-line mode: enter digraph |i_digraph| {char1} <BS> {char2} enter digraph if 'digraph' option set + ------------------------------------------------------------------------------ *Q_si* Special inserts |:r| :r [file] insert the contents of [file] below the cursor |:r!| :r! {command} insert the standard output of {command} below the cursor + ------------------------------------------------------------------------------ *Q_de* Deleting text @@ -346,6 +360,7 @@ In Insert or Command-line mode: |gJ| N gJ like "J", but without inserting spaces |v_gJ| {visual}gJ like "{visual}J", but without inserting spaces |:d| :[range]d [x] delete [range] lines [into register x] + ------------------------------------------------------------------------------ *Q_cm* Copying and moving text @@ -363,6 +378,7 @@ In Insert or Command-line mode: |[p| N [p like P, but adjust indent to current line |gp| N gp like p, but leave cursor after the new text |gP| N gP like P, but leave cursor after the new text + ------------------------------------------------------------------------------ *Q_ch* Changing text @@ -418,6 +434,7 @@ In Insert or Command-line mode: left-align the lines in [range] (with [indent]) |:ri| :[range]ri[ght] [width] right-align the lines in [range] + ------------------------------------------------------------------------------ *Q_co* Complex changes @@ -444,6 +461,7 @@ In Insert or Command-line mode: |:ret| :[range]ret[ab][!] [tabstop] set 'tabstop' to new value and adjust white space accordingly + ------------------------------------------------------------------------------ *Q_vi* Visual mode @@ -457,6 +475,7 @@ In Insert or Command-line mode: |v_v| v highlight characters or stop highlighting |v_V| V highlight linewise or stop highlighting |v_CTRL-V| CTRL-V highlight blockwise or stop highlighting + ------------------------------------------------------------------------------ *Q_to* Text objects (only in Visual mode or after an operator) @@ -509,6 +528,7 @@ In Insert or Command-line mode: |:sl| :sl[eep] [sec] don't do anything for [sec] seconds |gs| N gs goto Sleep for N seconds + ------------------------------------------------------------------------------ *Q_km* Key mapping @@ -556,6 +576,7 @@ In Insert or Command-line mode: like ":mkvimrc", but store current files, windows, etc. too, to be able to continue this session later + ------------------------------------------------------------------------------ *Q_ab* Abbreviations @@ -570,6 +591,7 @@ In Insert or Command-line mode: |:abclear| :abc[lear] remove all abbreviations |:cabclear| :cabc[lear] remove all abbr's for Cmdline mode |:iabclear| :iabc[lear] remove all abbr's for Insert mode + ------------------------------------------------------------------------------ *Q_op* Options @@ -615,10 +637,6 @@ Short explanation of each option: *option-list* 'backupdir' 'bdir' list of directories for the backup file 'backupext' 'bex' extension used for the backup file 'backupskip' 'bsk' no backup for files that match these patterns -'balloondelay' 'bdlay' delay in mS before a balloon may pop up -'ballooneval' 'beval' switch on balloon evaluation in the GUI -'balloonevalterm' 'bevalterm' switch on balloon evaluation in the terminal -'balloonexpr' 'bexpr' expression to show in balloon 'belloff' 'bo' do not ring the bell for these reasons 'binary' 'bin' read/write/edit file in binary mode 'bomb' prepend a Byte Order Mark to the file @@ -649,6 +667,7 @@ Short explanation of each option: *option-list* 'complete' 'cpt' specify how Insert mode completion works 'completefunc' 'cfu' function to be used for Insert mode completion 'completeopt' 'cot' options for Insert mode completion +'completeslash' 'csl' like 'shellslash' for completion 'concealcursor' 'cocu' whether concealable text is hidden in cursor line 'conceallevel' 'cole' whether concealable text is shown or hidden 'confirm' 'cf' ask what to do about unsaved/read-only files @@ -801,7 +820,6 @@ Short explanation of each option: *option-list* 'patchexpr' 'pex' expression used to patch a file 'patchmode' 'pm' keep the oldest version of a file 'path' 'pa' list of directories searched with "gf" et.al. -'perldll' name of the Perl dynamic library 'preserveindent' 'pi' preserve the indent structure when reindenting 'previewheight' 'pvh' height of the preview window 'previewpopup' 'pvp' use popup window for preview @@ -816,8 +834,6 @@ Short explanation of each option: *option-list* 'printoptions' 'popt' controls the format of :hardcopy output 'pumheight' 'ph' maximum height of the popup menu 'pumwidth' 'pw' minimum width of the popup menu -'pythondll' name of the Python 2 dynamic library -'pythonthreedll' name of the Python 3 dynamic library 'pyxversion' 'pyx' Python version used for pyx* commands 'quoteescape' 'qe' escape characters used in a string 'readonly' 'ro' disallow writing the buffer @@ -828,7 +844,6 @@ Short explanation of each option: *option-list* 'revins' 'ri' inserting characters will work backwards 'rightleft' 'rl' window is right-to-left oriented 'rightleftcmd' 'rlc' commands for which editing works right-to-left -'rubydll' name of the Ruby dynamic library 'ruler' 'ru' show cursor line and column in the status line 'rulerformat' 'ruf' custom format for the ruler 'runtimepath' 'rtp' list of directories used for runtime files @@ -875,6 +890,7 @@ Short explanation of each option: *option-list* 'spelloptions' 'spo' options for spell checking 'spellsuggest' 'sps' method(s) used to suggest spelling corrections 'splitbelow' 'sb' new window from split is below the current one +'splitkeep' 'spk' determines scroll behavior for split windows 'splitright' 'spr' new window is put right of the current one 'startofline' 'sol' commands move cursor to first non-blank in line 'statusline' 'stl' custom format for the status line @@ -947,18 +963,21 @@ Short explanation of each option: *option-list* 'writeany' 'wa' write to file with no need for "!" override 'writebackup' 'wb' make a backup before overwriting a file 'writedelay' 'wd' delay this many msec for each char (for debug) + ------------------------------------------------------------------------------ *Q_ur* Undo/Redo commands |u| N u undo last N changes |CTRL-R| N CTRL-R redo last N undone changes |U| U restore last changed line + ------------------------------------------------------------------------------ *Q_et* External commands |:!| :!{command} execute {command} with a shell |K| K lookup keyword under the cursor with 'keywordprg' program (default: "man") + ------------------------------------------------------------------------------ *Q_qf* Quickfix commands @@ -982,6 +1001,7 @@ Short explanation of each option: *option-list* error |:grep| :gr[ep] [args] execute 'grepprg' to find matches and jump to the first one + ------------------------------------------------------------------------------ *Q_vc* Various commands @@ -1007,6 +1027,7 @@ Short explanation of each option: *option-list* unsaved changes or read-only files |:browse| :browse {command} open/read/write file, using a file selection dialog + ------------------------------------------------------------------------------ *Q_ce* Command-line editing @@ -1053,6 +1074,7 @@ Context-sensitive completion on the command-line: to next match |c_CTRL-P| CTRL-P after 'wildchar' with multiple matches: go to previous match + ------------------------------------------------------------------------------ *Q_ra* Ex ranges @@ -1073,6 +1095,7 @@ Context-sensitive completion on the command-line: (default: 1) |:range| -[num] subtract [num] from the preceding line number (default: 1) + ------------------------------------------------------------------------------ *Q_ex* Special Ex characters @@ -1105,6 +1128,7 @@ Context-sensitive completion on the command-line: |::r| :r root (extension removed) |::e| :e extension |::s| :s/{pat}/{repl}/ substitute {pat} with {repl} + ------------------------------------------------------------------------------ *Q_st* Starting Vim @@ -1141,6 +1165,7 @@ Context-sensitive completion on the command-line: |--help| --help show list of arguments and exit |--version| --version show version info and exit |--| - read file from stdin + ------------------------------------------------------------------------------ *Q_ed* Editing a file @@ -1160,6 +1185,7 @@ Context-sensitive completion on the command-line: position |:file| :f[ile] {name} set the current file name to {name} |:files| :files show alternate file names + ------------------------------------------------------------------------------ *Q_fl* Using the argument list |argument-list| @@ -1180,6 +1206,7 @@ Context-sensitive completion on the command-line: |:Next| :N[ext] :sN[ext] edit previous file |:first| :fir[st] :sfir[st] edit first file |:last| :la[st] :sla[st] edit last file + ------------------------------------------------------------------------------ *Q_wq* Writing and quitting @@ -1217,6 +1244,7 @@ Context-sensitive completion on the command-line: |:stop| :st[op][!] suspend Vim or start new shell; if 'aw' option is set and [!] not given write the buffer |CTRL-Z| CTRL-Z same as ":stop" + ------------------------------------------------------------------------------ *Q_ac* Automatic Commands @@ -1248,6 +1276,7 @@ Context-sensitive completion on the command-line: with {pat} |:autocmd| :au! {event} {pat} {cmd} remove all autocommands for {event} with {pat} and enter new one + ------------------------------------------------------------------------------ *Q_wi* Multi-window commands @@ -1293,6 +1322,7 @@ Context-sensitive completion on the command-line: |CTRL-W_>| CTRL-W > increase current window width |CTRL-W_bar| CTRL-W | set current window width (default: widest possible) + ------------------------------------------------------------------------------ *Q_bu* Buffer list commands @@ -1314,6 +1344,7 @@ Context-sensitive completion on the command-line: |:bfirst| :bfirst :sbfirst to first arg/buf |:blast| :blast :sblast to last arg/buf |:bmodified| :[N]bmod [N] :[N]sbmod [N] to Nth modified buf + ------------------------------------------------------------------------------ *Q_sy* Syntax Highlighting @@ -1340,6 +1371,7 @@ Context-sensitive completion on the command-line: |:filetype| :filetype plugin indent on switch on file type detection, with automatic indenting and settings + ------------------------------------------------------------------------------ *Q_gu* GUI commands @@ -1352,6 +1384,7 @@ Context-sensitive completion on the command-line: add toolbar item, giving {rhs} |:tmenu| :tmenu {mpath} {text} add tooltip to menu {mpath} |:unmenu| :unmenu {mpath} remove menu {mpath} + ------------------------------------------------------------------------------ *Q_fo* Folding diff --git a/runtime/doc/repeat.txt b/runtime/doc/repeat.txt index 508565dea4..21945dc499 100644 --- a/runtime/doc/repeat.txt +++ b/runtime/doc/repeat.txt @@ -83,7 +83,8 @@ pattern and do not match another pattern: > This first finds all lines containing "found", but only executes {cmd} when there is no match for "notfound". -To execute a non-Ex command, you can use the `:normal` command: > +Any Ex command can be used, see |ex-cmd-index|. To execute a Normal mode +command, you can use the `:normal` command: > :g/pat/normal {commands} Make sure that {commands} ends with a whole command, otherwise Vim will wait for you to type the rest of the command for each match. The screen will not @@ -470,7 +471,7 @@ flag when defining the function, it is not relevant when executing it. > :set cpo-=C < *line-continuation-comment* -To add a comment in between the lines start with '"\ '. Notice the space +To add a comment in between the lines start with `'"\ '`. Notice the space after the backslash. Example: > let array = [ "\ first entry comment @@ -490,29 +491,40 @@ Rationale: continuation lines to be part of the comment. Since it was like this for a long time, when making it possible to add a comment halfway a sequence of continuation lines, it was not possible to use \", since - that was a valid continuation line. Using '"\ ' comes closest, even + that was a valid continuation line. Using `'"\ '` comes closest, even though it may look a bit weird. Requiring the space after the backslash is to make it very unlikely this is a normal comment line. ============================================================================== Using Vim packages *packages* -A Vim package is a directory that contains one or more plugins. The -advantages over normal plugins: -- A package can be downloaded as an archive and unpacked in its own directory. - Thus the files are not mixed with files of other plugins. That makes it - easy to update and remove. -- A package can be a git, mercurial, etc. repository. That makes it really - easy to update. -- A package can contain multiple plugins that depend on each other. -- A package can contain plugins that are automatically loaded on startup and - ones that are only loaded when needed with `:packadd`. +A Vim "package" is a directory that contains |plugin|s. Compared to normal +plugins, a package can... +- be downloaded as an archive and unpacked in its own directory, so the files + are not mixed with files of other plugins. +- be a git, mercurial, etc. repository, thus easy to update. +- contain multiple plugins that depend on each other. +- contain plugins that are automatically loaded on startup ("start" packages, + located in "pack/*/start/*") and ones that are only loaded when needed with + |:packadd| ("opt" packages, located in "pack/*/opt/*"). + *runtime-search-path* +Nvim searches for |:runtime| files in: + 1. all paths in 'runtimepath' + 2. all "pack/*/start/*" dirs + +Note that the "pack/*/start/*" paths are not explicitly included in +'runtimepath', so they will not be reported by ":set rtp" or "echo &rtp". +Scripts can use |nvim_list_runtime_paths()| to list all used directories, and +|nvim_get_runtime_file()| to query for specific files or sub-folders within +the runtime path. Example: > + " List all runtime dirs and packages with Lua paths. + :echo nvim_get_runtime_file("lua/", v:true) Using a package and loading automatically ~ -Let's assume your Vim files are in the "~/.local/share/nvim/site" directory -and you want to add a package from a zip archive "/tmp/foopack.zip": +Let's assume your Nvim files are in "~/.local/share/nvim/site" and you want to +add a package from a zip archive "/tmp/foopack.zip": % mkdir -p ~/.local/share/nvim/site/pack/foo % cd ~/.local/share/nvim/site/pack/foo % unzip /tmp/foopack.zip @@ -525,28 +537,17 @@ You would now have these files under ~/.local/share/nvim/site: pack/foo/start/foobar/syntax/some.vim pack/foo/opt/foodebug/plugin/debugger.vim - *runtime-search-path* -When runtime files are searched for, first all paths in 'runtimepath' are -searched, then all "pack/*/start/*" dirs are searched. However, package entries -are not visible in `:set rtp` or `echo &rtp`, as the final concatenated path -would be too long and get truncated. To list all used directories, use -|nvim_list_runtime_paths()|. In addition |nvim_get_runtime_file()| can be used -to query for specific files or sub-folders within the runtime path. For -instance to list all runtime dirs and packages with lua paths, use > - - :echo nvim_get_runtime_file("lua/", v:true) +On startup after processing your |config|, Nvim scans all directories in +'packpath' for plugins in "pack/*/start/*", then loads the plugins. -<When Vim starts up, after processing your .vimrc, it scans all directories in -'packpath' for plugins under the "pack/*/start" directory, and all the plugins -are loaded. - -In the example Vim will find "pack/foo/start/foobar/plugin/foo.vim" and load it. +In the example Nvim will find "pack/foo/start/foobar/plugin/foo.vim" and load +it. -If the "foobar" plugin kicks in and sets the 'filetype' to "some", Vim will +If the "foobar" plugin kicks in and sets the 'filetype' to "some", Nvim will find the syntax/some.vim file, because its directory is in the runtime search path. -Vim will also load ftdetect files, if there are any. +Nvim will also load ftdetect files, if there are any. Note that the files under "pack/foo/opt" are not loaded automatically, only the ones under "pack/foo/start". See |pack-add| below for how the "opt" directory @@ -588,12 +589,12 @@ This searches for "pack/*/opt/foodebug" in 'packpath' and will find it. This could be done if some conditions are met. For example, depending on -whether Vim supports a feature or a dependency is missing. +whether Nvim supports a feature or a dependency is missing. You can also load an optional plugin at startup, by putting this command in -your |.vimrc|: > +your |config|: > :packadd! foodebug -The extra "!" is so that the plugin isn't loaded if Vim was started with +The extra "!" is so that the plugin isn't loaded if Nvim was started with |--noplugin|. It is perfectly normal for a package to only have files in the "opt" @@ -605,7 +606,7 @@ Where to put what ~ Since color schemes, loaded with `:colorscheme`, are found below "pack/*/start" and "pack/*/opt", you could put them anywhere. We recommend you put them below "pack/*/opt", for example -".vim/pack/mycolors/opt/dark/colors/very_dark.vim". +"~/.config/nvim/pack/mycolors/opt/dark/colors/very_dark.vim". Filetype plugins should go under "pack/*/start", so that they are always found. Unless you have more than one plugin for a file type and want to @@ -683,8 +684,8 @@ found automatically. Your package would have these files: < pack/foo/start/lib/autoload/foolib.vim > func foolib#getit() -This works, because start packages will be used to look for autoload files, -when sourcing the plugins. +This works, because start packages will be searchd for autoload files, when +sourcing the plugins. ============================================================================== Debugging scripts *debug-scripts* diff --git a/runtime/doc/spell.txt b/runtime/doc/spell.txt index 23d5905ec3..15aa0117ec 100644 --- a/runtime/doc/spell.txt +++ b/runtime/doc/spell.txt @@ -1583,7 +1583,7 @@ CHECKCOMPOUNDTRIPLE (Hunspell) *spell-CHECKCOMPOUNDTRIPLE* Forbid three identical characters when compounding. Not supported. -CHECKSHARPS (Hunspell)) *spell-CHECKSHARPS* +CHECKSHARPS (Hunspell) *spell-CHECKSHARPS* SS letter pair in uppercased (German) words may be upper case sharp s (ß). Not supported. diff --git a/runtime/doc/starting.txt b/runtime/doc/starting.txt index d57a85423c..baa60f431f 100644 --- a/runtime/doc/starting.txt +++ b/runtime/doc/starting.txt @@ -35,7 +35,7 @@ filename One or more file names. The first one will be the current no other options or "+command" argument can follow. *--* -- Alias for stdin (standard input). +`-` Alias for stdin (standard input). Example: > echo text | nvim - file < "text" is read into buffer 1, "file" is opened as buffer 2. @@ -82,12 +82,10 @@ argument. --help *-h* *--help* *-?* -? -h Give usage (help) message and exit. - See |info-message| about capturing the text. --version *-v* *--version* -v Print version information and exit. Same output as for |:version| command. - See |info-message| about capturing the text. *--clean* --clean Mimics a fresh install of Nvim: @@ -145,12 +143,11 @@ argument. these commands, independently from "-c" commands. *-S* --S {file} The {file} will be sourced after the first file has been read. - This is an easy way to do the equivalent of: > +-S {file} Vimscript or Lua (".lua") {file} will be |:source|d after the + first file has been read. Equivalent to: > -c "source {file}" -< It can be mixed with "-c" arguments and repeated like "-c". - The limit of 10 "-c" arguments applies here as well. - {file} cannot start with a "-". +< Can be repeated like "-c", subject to the same limit of 10 + "-c" arguments. {file} cannot start with a "-". -S Works like "-S Session.vim". Only when used as the last argument or when another "-" option follows. @@ -205,13 +202,14 @@ argument. send commands. > printf "foo\n" | nvim -Es +"%print" -< Output of these commands is displayed (to stdout): - :print +< These commands display on stdout: :list :number - :set (to display option values) - When 'verbose' is set messages are printed to stderr. > - echo foo | nvim -V1 -es + :print + :set + With |:verbose| or 'verbose', other commands display on stderr: > + nvim -es +":verbose echo 'foo'" + nvim -V1 -es +foo < User |config| is skipped (unless given with |-u|). Swap file is skipped (like |-n|). @@ -445,9 +443,9 @@ accordingly, proceeding as follows: *VIMINIT* *EXINIT* *$MYVIMRC* b. Locations searched for initializations, in order of preference: - $VIMINIT environment variable (Ex command line). - - User |config|: $XDG_CONFIG_HOME/nvim/init.vim. - - Other config: {dir}/nvim/init.vim where {dir} is any directory - in $XDG_CONFIG_DIRS. + - User |config|: $XDG_CONFIG_HOME/nvim/init.vim (or init.lua). + - Other config: {dir}/nvim/init.vim (or init.lua) where {dir} is any + directory in $XDG_CONFIG_DIRS. - $EXINIT environment variable (Ex command line). |$MYVIMRC| is set to the first valid location unless it was already set or when using $VIMINIT. @@ -1184,7 +1182,7 @@ exactly four MessagePack objects: encoding Binary, effective 'encoding' value. max_kbyte Integer, effective |shada-s| limit value. pid Integer, instance process ID. - * It is allowed to have any number of + `*` It is allowed to have any number of additional keys with any data. 2 (SearchPattern) Map containing data describing last used search or substitute pattern. Normally ShaDa file contains two @@ -1215,7 +1213,7 @@ exactly four MessagePack objects: sp Binary N/A Actual pattern. Required. sb Boolean false True if search direction is backward. - * any none Other keys are allowed for + `*` any none Other keys are allowed for compatibility reasons, see |shada-compatibility|. 3 (SubString) Array containing last |:substitute| replacement string. @@ -1286,7 +1284,7 @@ exactly four MessagePack objects: GlobalMark and LocalMark entries. f Binary N/A File name. Required. - * any none Other keys are allowed for + `*` any none Other keys are allowed for compatibility reasons, see |shada-compatibility|. 9 (BufferList) Array containing maps. Each map in the array @@ -1296,10 +1294,10 @@ exactly four MessagePack objects: greater then zero. c UInteger 0 Position column number. f Binary N/A File name. Required. - * any none Other keys are allowed for + `*` any none Other keys are allowed for compatibility reasons, see |shada-compatibility|. - * (Unknown) Any other entry type is allowed for compatibility + `*` (Unknown) Any other entry type is allowed for compatibility reasons, see |shada-compatibility|. *E575* *E576* @@ -1359,7 +1357,7 @@ LOG FILE *$NVIM_LOG_FILE* *E5430* Besides 'debug' and 'verbose', Nvim keeps a general log file for internal debugging, plugins and RPC clients. > :echo $NVIM_LOG_FILE -By default, the file is located at stdpath('log')/log unless that path +By default, the file is located at stdpath("log")/log unless that path is inaccessible or if $NVIM_LOG_FILE was set before |startup|. diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index b74611633f..74778addc7 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -181,16 +181,16 @@ Vim will only load the first syntax file found, assuming that it sets b:current_syntax. -NAMING CONVENTIONS *group-name* *{group-name}* *E669* *W18* +NAMING CONVENTIONS *group-name* *{group-name}* *E669* *E5248* A syntax group name is to be used for syntax items that match the same kind of thing. These are then linked to a highlight group that specifies the color. A syntax group name doesn't specify any color or attributes itself. -The name for a highlight or syntax group must consist of ASCII letters, digits -and the underscore. As a regexp: "[a-zA-Z0-9_]*". However, Vim does not give -an error when using other characters. The maximum length of a group name is -about 200 bytes. *E1249* +The name for a highlight or syntax group must consist of ASCII letters, +digits, underscores, periods and `@` characters. As a regexp it is +`[a-zA-Z0-9_.@]*`. The maximum length of a group name is about 200 bytes. +*E1249* To be able to allow each user to pick their favorite set of colors, there must be preferred names for highlight groups that are common for many languages. @@ -2057,7 +2057,7 @@ The g:lisp_rainbow option provides 10 levels of individual colorization for the parentheses and backquoted parentheses. Because of the quantity of colorization levels, unlike non-rainbow highlighting, the rainbow mode specifies its highlighting using ctermfg and guifg, thereby bypassing the -usual colorscheme control using standard highlighting groups. The actual +usual color scheme control using standard highlighting groups. The actual highlighting used depends on the dark/bright setting (see |'bg'|). @@ -2365,7 +2365,7 @@ you set the variable: > :let papp_include_html=1 -in your startup file it will try to syntax-hilight html code inside phtml +in your startup file it will try to syntax-highlight html code inside phtml sections, but this is relatively slow and much too colourful to be able to edit sensibly. ;) @@ -3118,7 +3118,7 @@ The default is to use the twice sh_minlines. Set it to a smaller number to speed up displaying. The disadvantage is that highlight errors may appear. syntax/sh.vim tries to flag certain problems as errors; usually things like -extra ']'s, 'done's, 'fi's, etc. If you find the error handling problematic +unmatched "]", "done", "fi", etc. If you find the error handling problematic for your purposes, you may suppress such error highlighting by putting the following line in your .vimrc: > @@ -4838,7 +4838,7 @@ in their own color. To customize a color scheme use another name, e.g. "~/.config/nvim/colors/mine.vim", and use `:runtime` to - load the original colorscheme: > + load the original color scheme: > runtime colors/evening.vim hi Statement ctermfg=Blue guifg=Blue @@ -4846,7 +4846,7 @@ in their own color. |ColorSchemePre| autocommand event is triggered. After the color scheme has been loaded the |ColorScheme| autocommand event is triggered. - For info about writing a colorscheme file: > + For info about writing a color scheme file: > :edit $VIMRUNTIME/colors/README.txt :hi[ghlight] List all the current highlight groups that have @@ -4935,7 +4935,7 @@ cterm={attr-list} *attr-list* *highlight-cterm* *E418* have the same effect. "undercurl", "underdouble", "underdotted", and "underdashed" fall back to "underline" in a terminal that does not support them. The color is - set using |highlight-guisp|. + set using |guisp|. start={term-list} *highlight-start* *E422* stop={term-list} *term-list* *highlight-stop* @@ -4956,8 +4956,8 @@ stop={term-list} *term-list* *highlight-stop* like "<Esc>" and "<Space>". Example: start=<Esc>[27h;<Esc>[<Space>r; -ctermfg={color-nr} *highlight-ctermfg* *E421* -ctermbg={color-nr} *highlight-ctermbg* +ctermfg={color-nr} *ctermfg* *E421* +ctermbg={color-nr} *ctermbg* The {color-nr} argument is a color number. Its range is zero to (not including) the number of |tui-colors| available. The actual color with this number depends on the type of terminal @@ -5016,7 +5016,7 @@ ctermbg={color-nr} *highlight-ctermbg* explicitly. This causes the highlight groups that depend on 'background' to change! This means you should set the colors for Normal first, before setting other colors. - When a colorscheme is being used, changing 'background' causes it to + When a color scheme is being used, changing 'background' causes it to be reloaded, which may reset all colors (including Normal). First delete the "g:colors_name" variable when you don't want this. @@ -5064,9 +5064,9 @@ font={font-name} *highlight-font* Example: > :hi comment font='Monospace 10' -guifg={color-name} *highlight-guifg* -guibg={color-name} *highlight-guibg* -guisp={color-name} *highlight-guisp* +guifg={color-name} *guifg* +guibg={color-name} *guibg* +guisp={color-name} *guisp* These give the foreground (guifg), background (guibg) and special (guisp) color to use in the GUI. "guisp" is used for various underlines. @@ -5123,7 +5123,7 @@ Cursor Character under the cursor. lCursor Character under the cursor when |language-mapping| is used (see 'guicursor'). *hl-CursorIM* -CursorIM Like Cursor, but used when in IME mode. |CursorIM| +CursorIM Like Cursor, but used when in IME mode. *CursorIM* *hl-CursorColumn* CursorColumn Screen-column at the cursor, when 'cursorcolumn' is set. *hl-CursorLine* @@ -5187,7 +5187,7 @@ ModeMsg 'showmode' message (e.g., "-- INSERT --"). *hl-MsgArea* MsgArea Area for messages and cmdline. *hl-MsgSeparator* -MsgSeparator Separator for scrolled messages, `msgsep` flag of 'display'. +MsgSeparator Separator for scrolled messages |msgsep|. *hl-MoreMsg* MoreMsg |more-prompt| *hl-NonText* diff --git a/runtime/doc/tabpage.txt b/runtime/doc/tabpage.txt index 9197710819..49b2773253 100644 --- a/runtime/doc/tabpage.txt +++ b/runtime/doc/tabpage.txt @@ -186,8 +186,8 @@ gt *i_CTRL-<PageDown>* *i_<C-PageDown>* :+2tabnext " go to the two next tab page :1tabnext " go to the first tab page :$tabnext " go to the last tab page - :tabnext # " go to the last accessed tab page :tabnext $ " as above + :tabnext # " go to the last accessed tab page :tabnext - " go to the previous tab page :tabnext -1 " as above :tabnext + " go to the next tab page diff --git a/runtime/doc/tagsrch.txt b/runtime/doc/tagsrch.txt index 2485290667..82deb0fa0c 100644 --- a/runtime/doc/tagsrch.txt +++ b/runtime/doc/tagsrch.txt @@ -870,13 +870,15 @@ like |CTRL-]|. The function used for generating the taglist is specified by setting the 'tagfunc' option. The function will be called with three arguments: - a:pattern The tag identifier or pattern used during the tag search. - a:flags String containing flags to control the function behavior. - a:info Dict containing the following entries: + pattern The tag identifier or pattern used during the tag search. + flags String containing flags to control the function behavior. + info Dict containing the following entries: buf_ffname Full filename which can be used for priority. user_data Custom data String, if stored in the tag stack previously by tagfunc. +Note that "a:" needs to be prepended to the argument name when using it. + Currently up to three flags may be passed to the tag function: 'c' The function was invoked by a normal command being processed (mnemonic: the tag function may use the context around the diff --git a/runtime/doc/testing.txt b/runtime/doc/testing.txt index 4e4a908d0f..f4375c3363 100644 --- a/runtime/doc/testing.txt +++ b/runtime/doc/testing.txt @@ -134,7 +134,7 @@ assert_match({pattern}, {actual} [, {msg}]) When {pattern} does not match {actual} an error message is added to |v:errors|. Also see |assert-return|. - {pattern} is used as with |=~|: The matching is always done + {pattern} is used as with |expr-=~|: The matching is always done like 'magic' was set and 'cpoptions' is empty, no matter what the actual value of 'magic' or 'cpoptions' is. diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index 52531a1525..c836ccec8c 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -4,77 +4,75 @@ NVIM REFERENCE MANUAL -Tree-sitter integration *treesitter* +Treesitter integration *treesitter* - Type |gO| to see the table of contents. - ------------------------------------------------------------------------------- -VIM.TREESITTER *lua-treesitter* - -Nvim integrates the tree-sitter library for incremental parsing of buffers. +Nvim integrates the `tree-sitter` library for incremental parsing of buffers: +https://tree-sitter.github.io/tree-sitter/ - *vim.treesitter.language_version* -The latest parser ABI version that is supported by the bundled tree-sitter -library. +WARNING: Treesitter support is still experimental and subject to frequent +changes. This documentation may also not fully reflect the latest changes. - *vim.treesitter.minimum_language_version* -The earliest parser ABI version that is supported by the bundled tree-sitter -library. + Type |gO| to see the table of contents. -Parser files *treesitter-parsers* +============================================================================== +PARSER FILES *treesitter-parsers* Parsers are the heart of tree-sitter. They are libraries that tree-sitter will -search for in the `parser` runtime directory. Currently Nvim does not provide -the tree-sitter parsers, instead these must be built separately, for instance -using the tree-sitter utility. The only exception is a C parser being included -in official builds for testing purposes. Parsers are searched for as -`parser/{lang}.*` in any 'runtimepath' directory. +search for in the `parser` runtime directory. By default, Nvim bundles only +parsers for C, Lua, and Vimscript, but parsers can be installed manually or +via a plugin like https://github.com/nvim-treesitter/nvim-treesitter. +Parsers are searched for as `parser/{lang}.*` in any 'runtimepath' directory. +If multiple parsers for the same language are found, the first one is used. +(This typically implies the priority "user config > plugins > bundled". A parser can also be loaded manually using a full path: > vim.treesitter.require_language("python", "/path/to/python.so") +< +============================================================================== +LANGUAGE TREES *treesitter-languagetree* + *LanguageTree* -<Create a parser for a buffer and a given language (if another plugin uses the -same buffer/language combination, it will be safely reused). Use > +As buffers can contain multiple languages (e.g., Vimscript commands in a Lua +file), multiple parsers may be needed to parse the full buffer. These are +combined in a |LanguageTree| object. - parser = vim.treesitter.get_parser(bufnr, lang) +To create a LanguageTree (parser object) for a buffer and a given language, +use > -<`bufnr=0` can be used for current buffer. `lang` will default to 'filetype'. + tsparser = vim.treesitter.get_parser(bufnr, lang) +< +`bufnr=0` can be used for current buffer. `lang` will default to 'filetype'. Currently, the parser will be retained for the lifetime of a buffer but this is subject to change. A plugin should keep a reference to the parser object as long as it wants incremental updates. - -Parser methods *lua-treesitter-parser* - -tsparser:parse() *tsparser:parse()* Whenever you need to access the current syntax tree, parse the buffer: > - tstree = parser:parse() - -<This will return a table of immutable trees that represent the current state -of the buffer. When the plugin wants to access the state after a (possible) -edit it should call `parse()` again. If the buffer wasn't edited, the same tree -will be returned again without extra work. If the buffer was parsed before, -incremental parsing will be done of the changed parts. - -Note: to use the parser directly inside a |nvim_buf_attach| Lua callback, you -must call `get_parser()` before you register your callback. But preferably + tstree = tsparser:parse() +< +This will return a table of immutable |treesitter-tree|s that represent the +current state of the buffer. When the plugin wants to access the state after a +(possible) edit it should call `parse()` again. If the buffer wasn't edited, +the same tree will be returned again without extra work. If the buffer was +parsed before, incremental parsing will be done of the changed parts. + +Note: To use the parser directly inside a |nvim_buf_attach()| Lua callback, you +must call |get_parser()| before you register your callback. But preferably parsing shouldn't be done directly in the change callback anyway as they will be very frequent. Rather a plugin that does any kind of analysis on a tree should use a timer to throttle too frequent updates. -tsparser:set_included_regions({region_list}) *tsparser:set_included_regions()* - Changes the regions the parser should consider. This is used for language - injection. {region_list} should be of the form (all zero-based): > - { - {node1, node2}, - ... - } -< - `node1` and `node2` are both considered part of the same region and will - be parsed together with the parser in the same context. +See |lua-treesitter-languagetree| for the list of available methods. -Tree methods *lua-treesitter-tree* +============================================================================== +TREESITTER TREES *treesitter-tree* + *tstree* + +A "treesitter tree" represents the parsed contents of a buffer, which can be +used to perform further analysis. It is a |luaref-userdata| reference to an +object held by the tree-sitter library. + +An instance `tstree` of a treesitter tree supports the following methods. tstree:root() *tstree:root()* Return the root node of this tree. @@ -82,8 +80,15 @@ tstree:root() *tstree:root()* tstree:copy() *tstree:copy()* Returns a copy of the `tstree`. +============================================================================== +TREESITTER NODES *treesitter-node* + *tsnode* + +A "treesitter node" represents one specific element of the parsed contents of +a buffer, which can be captured by a |Query| for, e.g., highlighting. It is a +|luaref-userdata| reference to an object held by the tree-sitter library. -Node methods *lua-treesitter-node* +An instance `tsnode` of a treesitter node supports the following methods. tsnode:parent() *tsnode:parent()* Get the node's immediate parent. @@ -160,10 +165,10 @@ tsnode:id() *tsnode:id()* Get an unique identifier for the node inside its own tree. No guarantees are made about this identifier's internal representation, - except for being a primitive lua type with value equality (so not a + except for being a primitive Lua type with value equality (so not a table). Presently it is a (non-printable) string. - Note: the id is not guaranteed to be unique for nodes from different + Note: The `id` is not guaranteed to be unique for nodes from different trees. *tsnode:descendant_for_range()* @@ -176,90 +181,93 @@ tsnode:named_descendant_for_range({start_row}, {start_col}, {end_row}, {end_col} Get the smallest named node within this node that spans the given range of (row, column) positions -Query *lua-treesitter-query* +============================================================================== +TREESITTER QUERIES *treesitter-query* + +Treesitter queries are a way to extract information about a parsed |tstree|, +e.g., for the purpose of highlighting. Briefly, a `query` consists of one or +more patterns. A `pattern` is defined over node types in the syntax tree. A +`match` corresponds to specific elements of the syntax tree which match a +pattern. Patterns may optionally define captures and predicates. A `capture` +allows you to associate names with a specific node in a pattern. A `predicate` +adds arbitrary metadata and conditional data to a match. + +Queries are written in a lisp-like language documented in +https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax +Note: The predicates listed there page differ from those Nvim supports. See +|treesitter-predicates| for a complete list of predicates supported by Nvim. -Tree-sitter queries are supported, they are a way to do pattern-matching over -a tree, using a simple to write lisp-like format. See -https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax for more -information on how to write queries. +Nvim looks for queries as `*.scm` files in a `queries` directory under +`runtimepath`, where each file contains queries for a specific language and +purpose, e.g., `queries/lua/highlights.scm` for highlighting Lua files. +By default, the first query on `runtimepath` is used (which usually implies +that user config takes precedence over plugins, which take precedence over +queries bundled with Neovim). If a query should extend other queries instead +of replacing them, use |treesitter-query-modeline-extends|. -Note: The predicates listed in the web page above differ from those Neovim -supports. See |lua-treesitter-predicates| for a complete list of predicates -supported by Neovim. +See |lua-treesitter-query| for the list of available methods for working with +treesitter queries from Lua. -A `query` consists of one or more patterns. A `pattern` is defined over node -types in the syntax tree. A `match` corresponds to specific elements of the -syntax tree which match a pattern. Patterns may optionally define captures -and predicates. A `capture` allows you to associate names with a specific -node in a pattern. A `predicate` adds arbitrary metadata and conditional data -to a match. -Treesitter Query Predicates *lua-treesitter-predicates* +TREESITTER QUERY PREDICATES *treesitter-predicates* + +Predicates are special scheme nodes that are evaluated to conditionally capture +nodes. For example, the |eq?| predicate can be used as follows: > -When writing queries for treesitter, one might use `predicates`, that is, -special scheme nodes that are evaluated to verify things on a captured node -for example, the |eq?| predicate : > ((identifier) @foo (#eq? @foo "foo")) +< +to only match identifier corresponding to the `"foo"` text. -This will only match identifier corresponding to the `"foo"` text. -Here is a list of built-in predicates : +The following predicates are built in: - `eq?` *ts-predicate-eq?* - This predicate will check text correspondence between nodes or - strings: > + `eq?` *treesitter-predicate-eq?* + Match a string against the text corresponding to a node: > ((identifier) @foo (#eq? @foo "foo")) ((node1) @left (node2) @right (#eq? @left @right)) < - `match?` *ts-predicate-match?* - `vim-match?` *ts-predicate-vim-match?* - This will match if the provided vim regex matches the text - corresponding to a node: > + `match?` *treesitter-predicate-match?* + `vim-match?` *treesitter-predicate-vim-match?* + Match a |regexp| against the text corresponding to a node: > ((identifier) @constant (#match? @constant "^[A-Z_]+$")) -< Note: the `^` and `$` anchors will respectively match the start and - end of the node's text. +< Note: The `^` and `$` anchors will match the start and end of the + node's text. - `lua-match?` *ts-predicate-lua-match?* - This will match the same way than |match?| but using lua regexes. + `lua-match?` *treesitter-predicate-lua-match?* + Match |lua-patterns| against the text corresponding to a node, + similar to `match?` - `contains?` *ts-predicate-contains?* - Will check if any of the following arguments appears in the text - corresponding to the node: > + `contains?` *treesitter-predicate-contains?* + Match a string against parts of the text corresponding to a node: > ((identifier) @foo (#contains? @foo "foo")) ((identifier) @foo-bar (#contains @foo-bar "foo" "bar")) < - `any-of?` *ts-predicate-any-of?* - Will check if the text is the same as any of the following arguments: > + `any-of?` *treesitter-predicate-any-of?* + Match any of the given strings against the text corresponding to + a node: > ((identifier) @foo (#any-of? @foo "foo" "bar")) < This is the recommended way to check if the node matches one of many - keywords for example, as it has been optimized for this. -< + keywords, as it has been optimized for this. + *lua-treesitter-not-predicate* Each predicate has a `not-` prefixed predicate that is just the negation of the predicate. - *vim.treesitter.query.add_predicate()* -vim.treesitter.query.add_predicate({name}, {handler}) +Further predicates can be added via `vim.treesitter.query.`|add_predicate()|. +Use `vim.treesitter.query.`|list_predicates()| to list all available +predicates. -This adds a predicate with the name {name} to be used in queries. -{handler} should be a function whose signature will be : > - handler(match, pattern, bufnr, predicate) -< - *vim.treesitter.query.list_predicates()* -vim.treesitter.query.list_predicates() -This lists the currently available predicates to use in queries. +TREESITTER QUERY DIRECTIVES *treesitter-directives* -Treesitter Query Directive *lua-treesitter-directives* +Treesitter directives store metadata for a node or match and perform side +effects. For example, the |set!| predicate sets metadata on the match or node: > -Treesitter queries can also contain `directives`. Directives store metadata -for a node or match and perform side effects. For example, the |set!| -predicate sets metadata on the match or node : > ((identifier) @foo (#set! "type" "parameter")) +< +The following directives are built in: -Built-in directives: - - `set!` *ts-directive-set!* + `set!` *treesitter-directive-set!* Sets key/value metadata for a specific match or capture. Value is accessible as either `metadata[key]` (match specific) or `metadata[capture_id][key]` (capture specific). @@ -273,7 +281,7 @@ Built-in directives: ((identifier) @foo (#set! @foo "kind" "parameter")) ((node1) @left (node2) @right (#set! "type" "pair")) < - `offset!` *ts-directive-offset!* + `offset!` *treesitter-directive-offset!* Takes the range of the captured node and applies an offset. This will generate a new range object for the captured node as `metadata[capture_id].range`. @@ -289,94 +297,284 @@ Built-in directives: ((identifier) @constant (#offset! @constant 0 1 0 -1)) < -Treesitter syntax highlighting (WIP) *lua-treesitter-highlight* +Further directives can be added via `vim.treesitter.query.`|add_directive()|. +Use `vim.treesitter.query.`|list_directives()| to list all available +directives. -NOTE: This is a partially implemented feature, and not usable as a default -solution yet. What is documented here is a temporary interface intended -for those who want to experiment with this feature and contribute to -its development. -Highlights are defined in the same query format as in the tree-sitter -highlight crate, with some limitations and additions. Set a highlight query -for a buffer with this code: > +TREESITTER QUERY MODELINES *treesitter-query-modeline* - local query = [[ - "for" @keyword - "if" @keyword - "return" @keyword +Neovim supports to customize the behavior of the queries using a set of +"modelines", that is comments in the queries starting with `;`. Here are the +currently supported modeline alternatives: - (string_literal) @string - (number_literal) @number - (comment) @comment + `inherits: {lang}...` *treesitter-query-modeline-inherits* + Specifies that this query should inherit the queries from {lang}. + This will recursively descend in the queries of {lang} unless wrapped + in parentheses: `({lang})`. + Note: This is meant to be used to include queries from another + language. If you want your query to extend the queries of the same + language, use `extends`. - (preproc_function_def name: (identifier) @function) + `extends` *treesitter-query-modeline-extends* + Specifies that this query should be used as an extension for the + query, i.e. that it should be merged with the others. + Note: The order of the extensions, and the query that will be used as + a base depends on your 'runtimepath' value. - ; ... more definitions - ]] +Note: These modeline comments must be at the top of the query, but can be +repeated, for example, the following two modeline blocks are both valid: > - highlighter = vim.treesitter.TSHighlighter.new(query, bufnr, lang) - -- alternatively, to use the current buffer and its filetype: - -- highlighter = vim.treesitter.TSHighlighter.new(query) + ;; inherits: foo,bar + ;; extends - -- Don't recreate the highlighter for the same buffer, instead - -- modify the query like this: - local query2 = [[ ... ]] - highlighter:set_query(query2) + ;; extends + ;; + ;; inherits: baz +< +============================================================================== +TREESITTER SYNTAX HIGHLIGHTING *treesitter-highlight* -As mentioned above the supported predicate is currently only `eq?`. `match?` -predicates behave like matching always fails. As an addition a capture which -begin with an upper-case letter like `@WarningMsg` will map directly to this -highlight group, if defined. Also if the predicate begins with upper-case and -contains a dot only the part before the first will be interpreted as the -highlight group. As an example, this warns of a binary expression with two -identical identifiers, highlighting both as |hl-WarningMsg|: > +Syntax highlighting is specified through queries named `highlights.scm`, +which match a |tsnode| in the parsed |tstree| to a `capture` that can be +assigned a highlight group. For example, the query > - ((binary_expression left: (identifier) @WarningMsg.left right: (identifier) @WarningMsg.right) - (eq? @WarningMsg.left @WarningMsg.right)) + (parameters (identifier) @parameter) < -Treesitter Highlighting Priority *lua-treesitter-highlight-priority* +matches any `identifier` node inside a function `parameter` node (e.g., the +`bar` in `foo(bar)`) to the capture named `@parameter`. It is also possible to +match literal expressions (provided the parser returns them): > -Tree-sitter uses |nvim_buf_set_extmark()| to set highlights with a default + "return" @keyword.return +< +Assuming a suitable parser and `highlights.scm` query is found in runtimepath, +treesitter highlighting for the current buffer can be enabled simply via +|vim.treesitter.start()|. + + *treesitter-highlight-groups* +The capture names, with `@` included, are directly usable as highlight groups. +For many commonly used captures, the corresponding highlight groups are linked +to Nvim's standard |highlight-groups| by default but can be overridden in +colorschemes. + +A fallback system is implemented, so that more specific groups fallback to +more generic ones. For instance, in a language that has separate doc comments, +`@comment.doc` could be used. If this group is not defined, the highlighting +for an ordinary `@comment` is used. This way, existing color schemes already +work out of the box, but it is possible to add more specific variants for +queries that make them available. + +As an additional rule, capture highlights can always be specialized by +language, by appending the language name after an additional dot. For +instance, to highlight comments differently per language: > + + hi @comment.c guifg=Blue + hi @comment.lua @guifg=DarkBlue + hi link @comment.doc.java String +< + *treesitter-highlight-spell* +The special `@spell` capture can be used to indicate that a node should be +spell checked by Nvim's builtin |spell| checker. For example, the following +capture marks comments as to be checked: > + + (comment) @spell +< + *treesitter-highlight-conceal* +Treesitter highlighting supports |conceal| via the `conceal` metadata. By +convention, nodes to be concealed are captured as `@conceal`, but any capture +can be used. For example, the following query can be used to hide code block +delimiters in Markdown: > + + (fenced_code_block_delimiter) @conceal (#set! conceal "") +< +It is also possible to replace a node with a single character, which (unlike +legacy syntax) can be given a custom highlight. For example, the following +(ill-advised) query replaces the `!=` operator by a Unicode glyph, which is +still highlighted the same as other operators: > + + "!=" @operator (#set! conceal "≠") +< +Conceals specified in this way respect 'conceallevel'. + + *treesitter-highlight-priority* +Treesitter uses |nvim_buf_set_extmark()| to set highlights with a default priority of 100. This enables plugins to set a highlighting priority lower or higher than tree-sitter. It is also possible to change the priority of an individual query pattern manually by setting its `"priority"` metadata attribute: > - ( - (super_important_node) @ImportantHighlight - ; Give the whole query highlight priority higher than the default (100) - (set! "priority" 105) - ) + (super_important_node) @ImportantHighlight (#set! "priority" 105) < +============================================================================== +VIM.TREESITTER *lua-treesitter* + +The remainder of this document is a reference manual for the `vim.treesitter` +Lua module, which is the main interface for Nvim's tree-sitter integration. +Most of the following content is automatically generated from the function +documentation. + + + *vim.treesitter.language_version* +The latest parser ABI version that is supported by the bundled tree-sitter +library. + + *vim.treesitter.minimum_language_version* +The earliest parser ABI version that is supported by the bundled tree-sitter +library. ============================================================================== Lua module: vim.treesitter *lua-treesitter-core* +get_captures_at_cursor({winnr}) *get_captures_at_cursor()* + Returns a list of highlight capture names under the cursor + + Parameters: ~ + • {winnr} (number|nil) Window handle or 0 for current window (default) + + Return: ~ + string[] List of capture names + +get_captures_at_pos({bufnr}, {row}, {col}) *get_captures_at_pos()* + Returns a list of highlight captures at the given position + + Each capture is represented by a table containing the capture name as a + string as well as a table of metadata (`priority`, `conceal`, ...; empty + if none are defined). + + Parameters: ~ + • {bufnr} (number) Buffer number (0 for current buffer) + • {row} (number) Position row + • {col} (number) Position column + + Return: ~ + table[] List of captures `{ capture = "capture name", metadata = { ... + } }` + +get_node_at_cursor({winnr}) *get_node_at_cursor()* + Returns the smallest named node under the cursor + + Parameters: ~ + • {winnr} (number|nil) Window handle or 0 for current window (default) + + Return: ~ + (string) Name of node under the cursor + +get_node_at_pos({bufnr}, {row}, {col}, {opts}) *get_node_at_pos()* + Returns the smallest named node at the given position + + Parameters: ~ + • {bufnr} (number) Buffer number (0 for current buffer) + • {row} (number) Position row + • {col} (number) Position column + • {opts} (table) Optional keyword arguments: + • ignore_injections boolean Ignore injected languages + (default true) + + Return: ~ + userdata |tsnode| under the cursor + +get_node_range({node_or_range}) *get_node_range()* + Returns the node's range or an unpacked range table + + Parameters: ~ + • {node_or_range} (userdata|table) |tsnode| or table of positions + + Return: ~ + (table) `{ start_row, start_col, end_row, end_col }` + get_parser({bufnr}, {lang}, {opts}) *get_parser()* - Gets the parser for this bufnr / ft combination. + Returns the parser for a specific buffer and filetype and attaches it to + the buffer - If needed this will create the parser. Unconditionally attach the provided - callback + If needed, this will create the parser. Parameters: ~ - {bufnr} The buffer the parser should be tied to - {lang} The filetype of this parser - {opts} Options object to pass to the created language tree + • {bufnr} (number|nil) Buffer the parser should be tied to (default: + current buffer) + • {lang} (string|nil) Filetype of this parser (default: buffer + filetype) + • {opts} (table|nil) Options to pass to the created language tree Return: ~ - The parser + LanguageTree |LanguageTree| object to use for parsing get_string_parser({str}, {lang}, {opts}) *get_string_parser()* - Gets a string parser + 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 + + Return: ~ + LanguageTree |LanguageTree| object to use for parsing + +is_ancestor({dest}, {source}) *is_ancestor()* + Determines whether a node is the ancestor of another + + Parameters: ~ + • {dest} userdata Possible ancestor |tsnode| + • {source} userdata Possible descendant |tsnode| + + Return: ~ + (boolean) True if {dest} is an ancestor of {source} + +is_in_node_range({node}, {line}, {col}) *is_in_node_range()* + Determines whether (line, col) position is in node range + + Parameters: ~ + • {node} userdata |tsnode| defining the range + • {line} (number) Line (0-based) + • {col} (number) Column (0-based) + + Return: ~ + (boolean) True if the position is in node range + +node_contains({node}, {range}) *node_contains()* + Determines if a node contains a range Parameters: ~ - {str} The string to parse - {lang} The language of this string - {opts} Options to pass to the created language tree + • {node} userdata |tsnode| + • {range} (table) + + Return: ~ + (boolean) True if the {node} contains the {range} + +start({bufnr}, {lang}) *start()* + Starts treesitter highlighting for a buffer + + Can be used in an ftplugin or FileType autocommand. + + Note: By default, disables regex syntax highlighting, which may be + required for some plugins. In this case, add `vim.bo.syntax = 'on'` after + the call to `start`. + + Example: > + + vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex', + callback = function(args) + vim.treesitter.start(args.buf, 'latex') + vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed + end + }) +< + + Parameters: ~ + • {bufnr} (number|nil) Buffer to be highlighted (default: current + buffer) + • {lang} (string|nil) Language of the parser (default: buffer + filetype) + +stop({bufnr}) *stop()* + Stops treesitter highlighting for a buffer + + Parameters: ~ + • {bufnr} (number|nil) Buffer to stop highlighting (default: current + buffer) ============================================================================== -Lua module: vim.treesitter.language *treesitter-language* +Lua module: vim.treesitter.language *lua-treesitter-language* inspect_language({lang}) *inspect_language()* Inspects the provided language. @@ -385,22 +583,32 @@ inspect_language({lang}) *inspect_language()* names, ... Parameters: ~ - {lang} The language. + • {lang} (string) Language -require_language({lang}, {path}, {silent}) *require_language()* - Asserts that the provided language is installed, and optionally provide a - path for the parser + Return: ~ + (table) + + *require_language()* +require_language({lang}, {path}, {silent}, {symbol_name}) + Asserts that a parser for the language {lang} is installed. - Parsers are searched in the `parser` runtime directory. + Parsers are searched in the `parser` runtime directory, or the provided + {path} Parameters: ~ - {lang} The language the parser should parse - {path} Optional path the parser is located at - {silent} Don't throw an error if language not found + • {lang} (string) Language the parser should parse + • {path} (string|nil) Optional path the parser is located at + • {silent} (boolean|nil) Don't throw an error if language not + found + • {symbol_name} (string|nil) Internal symbol name for the language to + load + + Return: ~ + (boolean) If the specified language is installed ============================================================================== -Lua module: vim.treesitter.query *treesitter-query* +Lua module: vim.treesitter.query *lua-treesitter-query* add_directive({name}, {handler}, {force}) *add_directive()* Adds a new directive to be used in queries @@ -411,61 +619,74 @@ add_directive({name}, {handler}, {force}) *add_directive()* `metadata[capture_id].key = value` Parameters: ~ - {name} the name of the directive, without leading # - {handler} the handler function to be used signature will be (match, - pattern, bufnr, predicate, metadata) + • {name} (string) Name of the directive, without leading # + • {handler} function(match:string, pattern:string, bufnr:number, + predicate:function, metadata:table) add_predicate({name}, {handler}, {force}) *add_predicate()* Adds a new predicate to be used in queries Parameters: ~ - {name} the name of the predicate, without leading # - {handler} the handler function to be used signature will be (match, - pattern, bufnr, predicate) + • {name} (string) Name of the predicate, without leading # + • {handler} function(match:string, pattern:string, bufnr:number, + predicate:function) -get_node_text({node}, {source}) *get_node_text()* +get_node_text({node}, {source}, {opts}) *get_node_text()* Gets the text corresponding to a given node Parameters: ~ - {node} the node - {source} The buffer or string from which the node is extracted + • {node} userdata |tsnode| + • {source} (number|string) Buffer or string from which the {node} is + extracted + • {opts} (table|nil) Optional parameters. + • concat: (boolean) Concatenate result in a string (default + true) + + Return: ~ + (string[]|string) get_query({lang}, {query_name}) *get_query()* Returns the runtime query {query_name} for {lang}. Parameters: ~ - {lang} The language to use for the query - {query_name} The name of the query (i.e. "highlights") + • {lang} (string) Language to use for the query + • {query_name} (string) Name of the query (e.g. "highlights") Return: ~ - The corresponding query, parsed. + Query Parsed query *get_query_files()* get_query_files({lang}, {query_name}, {is_included}) Gets the list of files used to make up a query Parameters: ~ - {lang} The language - {query_name} The name of the query to load - {is_included} Internal parameter, most of the time left as `nil` + • {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 + as `nil` + + Return: ~ + string[] query_files List of files to load for given query and + language list_directives() *list_directives()* Lists the currently available directives to use in queries. Return: ~ - The list of supported directives. + string[] List of supported directives. list_predicates() *list_predicates()* + Lists the currently available predicates to use in queries. + Return: ~ - The list of supported predicates. + string[] List of supported predicates. parse_query({lang}, {query}) *parse_query()* 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}. @@ -473,208 +694,213 @@ parse_query({lang}, {query}) *parse_query()* • `info.patterns` contains information about predicates. Parameters: ~ - {lang} (string) The language - {query} (string) A string containing the query (s-expr syntax) + • {lang} (string) Language to use for the query + • {query} (string) Query in s-expr syntax Return: ~ - The query + Query Parsed query *Query:iter_captures()* Query:iter_captures({self}, {node}, {source}, {start}, {stop}) Iterate over all captures from all matches inside {node} - {source} is needed if the query contains predicates, then the caller must + {source} is needed if the query contains predicates; then the caller must ensure to use a freshly parsed tree consistent with the current text of the buffer (if relevant). {start_row} and {end_row} can be used to limit matches inside a row range (this is typically used with root node as the - node, i e to get syntax highlight matches in the current viewport). When - omitted the start and end row values are used from the given node. + {node}, i.e., to get syntax highlight matches in the current viewport). + When omitted, the {start} and {end} row values are used from the given + node. - The iterator returns three values, a numeric id identifying the capture, + The iterator returns three values: a numeric id identifying the capture, the captured node, and metadata from any directives processing the match. - The following example shows how to get captures by name: -> - - for id, node, metadata in query:iter_captures(tree:root(), bufnr, first, last) do - local name = query.captures[id] -- name of the capture in the query - -- typically useful info about the node: - local type = node:type() -- type of the captured node - local row1, col1, row2, col2 = node:range() -- range of the capture - ... use the info here ... - end + The following example shows how to get captures by name: > + + for id, node, metadata in query:iter_captures(tree:root(), bufnr, first, last) do + local name = query.captures[id] -- name of the capture in the query + -- typically useful info about the node: + local type = node:type() -- type of the captured node + local row1, col1, row2, col2 = node:range() -- range of the capture + ... use the info here ... + end < Parameters: ~ - {node} The node under which the search will occur - {source} The source buffer or string to extract text from - {start} The starting line of the search - {stop} The stopping line of the search (end-exclusive) - {self} + • {node} userdata |tsnode| under which the search will occur + • {source} (number|string) Source buffer or string to extract text from + • {start} (number) Starting line for the search + • {stop} (number) Stopping line for the search (end-exclusive) + • {self} Return: ~ - The matching capture id - The captured node + (number) capture Matching capture id + (table) capture_node Capture for {node} + (table) metadata for the {capture} *Query:iter_matches()* Query:iter_matches({self}, {node}, {source}, {start}, {stop}) Iterates the matches of self on a given range. - Iterate over all matches within a node. The arguments are the same as for - |query:iter_captures()| but the iterated values are different: an + Iterate over all matches within a {node}. The arguments are the same as + for |Query:iter_captures()| but the iterated values are different: an (1-based) index of the pattern in the query, a table mapping capture indices to nodes, and metadata from any directives processing the match. - If the query has more than one pattern the capture table might be sparse, - and e.g. `pairs()` method should be used over `ipairs`. Here an example - iterating over all captures in every match: -> + If the query has more than one pattern, the capture table might be sparse + and e.g. `pairs()` method should be used over `ipairs` . Here is an example iterating over all captures in every match: > - for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do - for id, node in pairs(match) do - local name = query.captures[id] - -- `node` was captured by the `name` capture in the match + for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do + for id, node in pairs(match) do + local name = query.captures[id] + -- `node` was captured by the `name` capture in the match - local node_data = metadata[id] -- Node level metadata + local node_data = metadata[id] -- Node level metadata - ... use the info here ... - end - end + ... use the info here ... + end + end < Parameters: ~ - {node} The node under which the search will occur - {source} The source buffer or string to search - {start} The starting line of the search - {stop} The stopping line of the search (end-exclusive) - {self} + • {node} userdata |tsnode| under which the search will occur + • {source} (number|string) Source buffer or string to search + • {start} (number) Starting line for the search + • {stop} (number) Stopping line for the search (end-exclusive) + • {self} Return: ~ - The matching pattern id - The matching match + (number) pattern id + (table) match + (table) metadata set_query({lang}, {query_name}, {text}) *set_query()* - Sets the runtime query {query_name} for {lang} + Sets the runtime query named {query_name} for {lang} This allows users to override any runtime files and/or configuration set by plugins. Parameters: ~ - {lang} string: The language to use for the query - {query_name} string: The name of the query (i.e. "highlights") - {text} string: The 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). ============================================================================== -Lua module: vim.treesitter.highlighter *treesitter-highlighter* +Lua module: vim.treesitter.highlighter *lua-treesitter-highlighter* new({tree}, {opts}) *highlighter.new()* Creates a new highlighter using Parameters: ~ - {tree} The language tree to use for highlighting - {opts} Table used to configure the highlighter - • queries: Table to overwrite queries used by the highlighter + • {tree} LanguageTree |LanguageTree| parser object to use for highlighting + • {opts} (table|nil) Configuration of the highlighter: + • queries table overwrite queries used by the highlighter + + Return: ~ + TSHighlighter Created highlighter object TSHighlighter:destroy({self}) *TSHighlighter:destroy()* Removes all internal references to the highlighter Parameters: ~ - {self} - -TSHighlighter:get_query({self}, {lang}) *TSHighlighter:get_query()* - Gets the query used for - - Parameters: ~ - {lang} A language used by the highlighter. - {self} + • {self} ============================================================================== -Lua module: vim.treesitter.languagetree *treesitter-languagetree* - -LanguageTree:add_child({self}, {lang}) *LanguageTree:add_child()* - Adds a child language to this tree. - - If the language already exists as a child, it will first be removed. - - Parameters: ~ - {lang} The language to add. - {self} +Lua module: vim.treesitter.languagetree *lua-treesitter-languagetree* LanguageTree:children({self}) *LanguageTree:children()* Returns a map of language to child tree. Parameters: ~ - {self} + • {self} LanguageTree:contains({self}, {range}) *LanguageTree:contains()* - Determines whether {range} is contained in this language tree + Determines whether {range} is contained in the |LanguageTree|. Parameters: ~ - {range} A range, that is a `{ start_line, start_col, end_line, - end_col }` table. - {self} + • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {self} + + Return: ~ + (boolean) LanguageTree:destroy({self}) *LanguageTree:destroy()* - Destroys this language tree and all its children. + Destroys this |LanguageTree| and all its children. Any cleanup logic should be performed here. Note: This DOES NOT remove this tree from a parent. Instead, `remove_child` must be called on the parent to remove it. Parameters: ~ - {self} + • {self} *LanguageTree:for_each_child()* LanguageTree:for_each_child({self}, {fn}, {include_self}) - Invokes the callback for each LanguageTree and it's children recursively + Invokes the callback for each |LanguageTree| and its children recursively Parameters: ~ - {fn} The function to invoke. This is invoked with arguments - (tree: LanguageTree, lang: string) - {include_self} Whether to include the invoking tree in the results. - {self} + • {fn} function(tree: LanguageTree, lang: string) + • {include_self} (boolean) Whether to include the invoking tree in the + results + • {self} LanguageTree:for_each_tree({self}, {fn}) *LanguageTree:for_each_tree()* - Invokes the callback for each treesitter trees recursively. + Invokes the callback for each |LanguageTree| recursively. - Note, this includes the invoking language tree's trees as well. + Note: This includes the invoking tree's child trees as well. Parameters: ~ - {fn} The callback to invoke. The callback is invoked with arguments - (tree: TSTree, languageTree: LanguageTree) - {self} + • {fn} function(tree: TSTree, languageTree: LanguageTree) + • {self} LanguageTree:included_regions({self}) *LanguageTree:included_regions()* Gets the set of included regions Parameters: ~ - {self} + • {self} LanguageTree:invalidate({self}, {reload}) *LanguageTree:invalidate()* Invalidates this parser and all its children Parameters: ~ - {self} + • {self} LanguageTree:is_valid({self}) *LanguageTree:is_valid()* Determines whether this tree is valid. If the tree is invalid, call `parse()` . This will return the updated tree. Parameters: ~ - {self} + • {self} LanguageTree:lang({self}) *LanguageTree:lang()* Gets the language of this tree node. Parameters: ~ - {self} + • {self} *LanguageTree:language_for_range()* LanguageTree:language_for_range({self}, {range}) - Gets the appropriate language that contains {range} + Gets the appropriate language that contains {range}. + + Parameters: ~ + • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {self} + + Return: ~ + LanguageTree Managing {range} + + *LanguageTree:named_node_for_range()* +LanguageTree:named_node_for_range({self}, {range}, {opts}) + Gets the smallest named node that contains {range}. Parameters: ~ - {range} A text range, see |LanguageTree:contains| - {self} + • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {opts} (table|nil) Optional keyword arguments: + • ignore_injections boolean Ignore injected languages + (default true) + • {self} + + Return: ~ + userdata|nil Found |tsnode| LanguageTree:parse({self}) *LanguageTree:parse()* Parses all defined regions using a treesitter parser for the language this @@ -682,14 +908,18 @@ LanguageTree:parse({self}) *LanguageTree:parse()* determine if any child languages should be created. Parameters: ~ - {self} + • {self} + + Return: ~ + userdata[] Table of parsed |tstree| + (table) Change list LanguageTree:register_cbs({self}, {cbs}) *LanguageTree:register_cbs()* - Registers callbacks for the parser. + Registers callbacks for the |LanguageTree|. Parameters: ~ - {cbs} (table) An |nvim_buf_attach()|-like table argument with the - following keys : + • {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_changedtree` : a callback that will be called every time the tree has syntactical changes. It will only be passed one @@ -699,61 +929,50 @@ LanguageTree:register_cbs({self}, {cbs}) *LanguageTree:register_cbs()* tree. • `on_child_removed` : emitted when a child is removed from the tree. - {self} + • {self} -LanguageTree:remove_child({self}, {lang}) *LanguageTree:remove_child()* - Removes a child language from this tree. +LanguageTree:source({self}) *LanguageTree:source()* + Returns the source content of the language tree (bufnr or string). Parameters: ~ - {lang} The language to remove. - {self} - - *LanguageTree:set_included_regions()* -LanguageTree:set_included_regions({self}, {regions}) - Sets the included regions that should be parsed by this parser. A region - is a set of nodes and/or ranges that will be parsed in the same context. - - For example, `{ { node1 }, { node2} }` is two separate regions. This will - be parsed by the parser in two different contexts... thus resulting in two - separate trees. + • {self} - `{ { node1, node2 } }` is a single region consisting of two nodes. This - will be parsed by the parser in a single context... thus resulting in a - single tree. - - This allows for embedded languages to be parsed together across different - nodes, which is useful for templating languages like ERB and EJS. - - Note, this call invalidates the tree and requires it to be parsed again. + *LanguageTree:tree_for_range()* +LanguageTree:tree_for_range({self}, {range}, {opts}) + Gets the tree that contains {range}. Parameters: ~ - {regions} (table) list of regions this tree should manage and parse. - {self} - -LanguageTree:source({self}) *LanguageTree:source()* - Returns the source content of the language tree (bufnr or string). + • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {opts} (table|nil) Optional keyword arguments: + • ignore_injections boolean Ignore injected languages + (default true) + • {self} - Parameters: ~ - {self} + Return: ~ + userdata|nil Contained |tstree| LanguageTree:trees({self}) *LanguageTree:trees()* Returns all trees this language tree contains. Does not include child languages. Parameters: ~ - {self} + • {self} new({source}, {lang}, {opts}) *languagetree.new()* - Represents a single treesitter parser for a language. The language can - contain child languages with in its range, hence the tree. + A |LanguageTree| holds the treesitter parser for a given language {lang} + used to parse a buffer. As the buffer may contain injected languages, the LanguageTree needs to store parsers for these child languages as well (which in turn + may contain child languages themselves, hence the name). Parameters: ~ - {source} Can be a bufnr or a string of text to parse - {lang} The language this tree represents - {opts} Options table - {opts.injections} A table of language to injection query strings. - This is useful for overriding the built-in runtime - file searching for the injection language query per - language. + • {source} (number|string) Buffer or a string of text to parse + • {lang} (string) Root language this tree represents + • {opts} (table|nil) Optional keyword arguments: + • injections table Mapping language to injection query + strings. This is useful for overriding the built-in + runtime file searching for the injection language query + per language. + + Return: ~ + LanguageTree |LanguageTree| parser object vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/ui.txt b/runtime/doc/ui.txt index 3fb9ed1125..5685979c82 100644 --- a/runtime/doc/ui.txt +++ b/runtime/doc/ui.txt @@ -23,40 +23,37 @@ screen grid with a size of width × height cells. This is typically done by an embedder at startup (see |ui-startup|), but UIs can also connect to a running Nvim instance and invoke nvim_ui_attach(). The `options` parameter is a map with these (optional) keys: + *ui-rgb* - `rgb` Decides the color format. - true: (default) 24-bit RGB colors - false: Terminal colors (8-bit, max 256) +- `rgb` Decides the color format. + - true: (default) 24-bit RGB colors + - false: Terminal colors (8-bit, max 256) *ui-override* - `override` Decides how UI capabilities are resolved. - true: Enable requested UI capabilities, even - if not supported by all connected UIs - (including |TUI|). - false: (default) Disable UI capabilities not - supported by all connected UIs - (including TUI). +- `override` Decides how UI capabilities are resolved. + - true: Enable requested UI capabilities, even if not + supported by all connected UIs (including |TUI|). + - false: (default) Disable UI capabilities not + supported by all connected UIs (including TUI). *ui-ext-options* - `ext_cmdline` Externalize the cmdline. |ui-cmdline| - `ext_hlstate` Detailed highlight state. |ui-hlstate| - Sets `ext_linegrid` implicitly. - `ext_linegrid` Line-based grid events. |ui-linegrid| - Deactivates |ui-grid-old| implicitly. - `ext_messages` Externalize messages. |ui-messages| - Sets `ext_linegrid` and `ext_cmdline` implicitly. - `ext_multigrid` Per-window grid events. |ui-multigrid| - Sets `ext_linegrid` implicitly. - `ext_popupmenu` Externalize |popupmenu-completion| and - 'wildmenu'. |ui-popupmenu| - `ext_tabline` Externalize the tabline. |ui-tabline| - `ext_termcolors` Use external default colors. - `term_name` Sets the name of the terminal 'term'. - `term_colors` Sets the number of supported colors 't_Co'. - `term_background` Sets the default value of 'background'. - `stdin_fd` Read buffer from `fd` as if it was a stdin pipe - This option can only used by |--embed| ui, - see |ui-startup-stdin|. - - +- `ext_cmdline` Externalize the cmdline. |ui-cmdline| +- `ext_hlstate` Detailed highlight state. |ui-hlstate| + Sets `ext_linegrid` implicitly. +- `ext_linegrid` Line-based grid events. |ui-linegrid| + Deactivates |ui-grid-old| implicitly. +- `ext_messages` Externalize messages. |ui-messages| + Sets `ext_linegrid` and `ext_cmdline` implicitly. +- `ext_multigrid` Per-window grid events. |ui-multigrid| + Sets `ext_linegrid` implicitly. +- `ext_popupmenu` Externalize |popupmenu-completion| and + 'wildmenu'. |ui-popupmenu| +- `ext_tabline` Externalize the tabline. |ui-tabline| +- `ext_termcolors` Use external default colors. +- `term_name` Sets the name of the terminal 'term'. +- `term_colors` Sets the number of supported colors 't_Co'. +- `term_background` Sets the default value of 'background'. +- `stdin_fd` Read buffer from `fd` as if it was a stdin pipe + This option can only used by |--embed| ui, + see |ui-startup-stdin|. Specifying an unknown option is an error; UIs can check the |api-metadata| `ui_options` key for supported options. @@ -164,13 +161,13 @@ Global Events *ui-global* The following UI events are always emitted, and describe global state of the editor. -["set_title", title] -["set_icon", icon] +["set_title", title] ~ +["set_icon", icon] ~ Set the window title, and icon (minimized) window title, respectively. In windowing systems not distinguishing between the two, "set_icon" can be ignored. -["mode_info_set", cursor_style_enabled, mode_info] +["mode_info_set", cursor_style_enabled, mode_info] ~ `cursor_style_enabled` is a boolean indicating if the UI should set the cursor style. `mode_info` is a list of mode property maps. The current mode is given by the `mode_idx` field of the `mode_change` @@ -197,20 +194,21 @@ the editor. `hl_id`: Use `attr_id` instead. `hl_lm`: Use `attr_id_lm` instead. -["option_set", name, value] +["option_set", name, value] ~ UI-related option changed, where `name` is one of: - 'arabicshape' - 'ambiwidth' - 'emoji' - 'guifont' - 'guifontwide' - 'linespace' - 'mousefocus' - 'pumblend' - 'showtabline' - 'termguicolors' - "ext_*" (all |ui-ext-options|) + - 'arabicshape' + - 'ambiwidth' + - 'emoji' + - 'guifont' + - 'guifontwide' + - 'linespace' + - 'mousefocus' + - 'mousemoveevent' + - 'pumblend' + - 'showtabline' + - 'termguicolors' + - "ext_*" (all |ui-ext-options|) Triggered when the UI first connects to Nvim, and whenever an option is changed by the user or a plugin. @@ -223,7 +221,7 @@ the editor. however a UI might still use such options when rendering raw text sent from Nvim, like for |ui-cmdline|. -["mode_change", mode, mode_idx] +["mode_change", mode, mode_idx] ~ Editor mode changed. The `mode` parameter is a string representing the current mode. `mode_idx` is an index into the array emitted in the `mode_info_set` event. UIs should change the cursor style @@ -232,30 +230,30 @@ the editor. instance more submodes and temporary states might be represented as separate modes. -["mouse_on"] -["mouse_off"] +["mouse_on"] ~ +["mouse_off"] ~ 'mouse' was enabled/disabled in the current editor mode. Useful for a terminal UI, or embedding into an application where Nvim mouse would conflict with other usages of the mouse. Other UI:s may ignore this event. -["busy_start"] -["busy_stop"] +["busy_start"] ~ +["busy_stop"] ~ Indicates to the UI that it must stop rendering the cursor. This event is misnamed and does not actually have anything to do with busyness. -["suspend"] +["suspend"] ~ |:suspend| command or |CTRL-Z| mapping is used. A terminal client (or another client where it makes sense) could suspend itself. Other clients can safely ignore it. -["update_menu"] +["update_menu"] ~ The menu mappings changed. -["bell"] -["visual_bell"] +["bell"] ~ +["visual_bell"] ~ Notify the user with an audible or visual bell, respectively. -["flush"] +["flush"] ~ Nvim is done redrawing the screen. For an implementation that renders to an internal buffer, this is the time to display the redrawn parts to the user. @@ -278,11 +276,11 @@ be created; to enable per-window grids, activate |ui-multigrid|. Highlight attribute groups are predefined. UIs should maintain a table to map numerical highlight ids to the actual attributes. -["grid_resize", grid, width, height] +["grid_resize", grid, width, height] ~ Resize a `grid`. If `grid` wasn't seen by the client before, a new grid is being created with this size. -["default_colors_set", rgb_fg, rgb_bg, rgb_sp, cterm_fg, cterm_bg] +["default_colors_set", rgb_fg, rgb_bg, rgb_sp, cterm_fg, cterm_bg] ~ The first three arguments set the default foreground, background and special colors respectively. `cterm_fg` and `cterm_bg` specifies the default color codes to use in a 256-color terminal. @@ -299,7 +297,7 @@ numerical highlight ids to the actual attributes. screen with changed background color itself. *ui-event-hl_attr_define* -["hl_attr_define", id, rgb_attr, cterm_attr, info] +["hl_attr_define", id, rgb_attr, cterm_attr, info] ~ Add a highlight with `id` to the highlight table, with the attributes specified by the `rgb_attr` and `cterm_attr` dicts, with the following (all optional) keys. @@ -345,7 +343,7 @@ numerical highlight ids to the actual attributes. `info` is an empty array by default, and will be used by the |ui-hlstate| extension explained below. -["hl_group_set", name, hl_id] +["hl_group_set", name, hl_id] ~ The bulitin highlight group `name` was set to use the attributes `hl_id` defined by a previous `hl_attr_define` call. This event is not needed to render the grids which use attribute ids directly, but is useful @@ -354,7 +352,7 @@ numerical highlight ids to the actual attributes. use the |hl-Pmenu| family of builtin highlights. *ui-event-grid_line* -["grid_line", grid, row, col_start, cells] +["grid_line", grid, row, col_start, cells] ~ Redraw a continuous part of a `row` on a `grid`, starting at the column `col_start`. `cells` is an array of arrays each with 1 to 3 items: `[text(, hl_id, repeat)]` . `text` is the UTF-8 text that should be put in @@ -373,19 +371,19 @@ numerical highlight ids to the actual attributes. enough to cover the remaining line, will be sent when the rest of the line should be cleared. -["grid_clear", grid] +["grid_clear", grid] ~ Clear a `grid`. -["grid_destroy", grid] +["grid_destroy", grid] ~ `grid` will not be used anymore and the UI can free any data associated with it. -["grid_cursor_goto", grid, row, column] +["grid_cursor_goto", grid, row, column] ~ Makes `grid` the current grid and `row, column` the cursor position on this grid. This event will be sent at most once in a `redraw` batch and indicates the visible cursor position. -["grid_scroll", grid, top, bot, left, right, rows, cols] +["grid_scroll", grid, top, bot, left, right, rows, cols] ~ Scroll a region of `grid`. This is semantically unrelated to editor |scrolling|, rather this is an optimized way to say "copy these screen cells". @@ -438,30 +436,30 @@ Grid Events (cell-based) *ui-grid-old* This is the legacy representation of the screen grid, emitted if |ui-linegrid| is not active. New UIs should implement |ui-linegrid| instead. -["resize", width, height] +["resize", width, height] ~ The grid is resized to `width` and `height` cells. -["clear"] +["clear"] ~ Clear the grid. -["eol_clear"] +["eol_clear"] ~ Clear from the cursor position to the end of the current line. -["cursor_goto", row, col] +["cursor_goto", row, col] ~ Move the cursor to position (row, col). Currently, the same cursor is used to define the position for text insertion and the visible cursor. However, only the last cursor position, after processing the entire array in the "redraw" event, is intended to be a visible cursor position. -["update_fg", color] -["update_bg", color] -["update_sp", color] +["update_fg", color] ~ +["update_bg", color] ~ +["update_sp", color] ~ Set the default foreground, background and special colors respectively. *ui-event-highlight_set* -["highlight_set", attrs] +["highlight_set", attrs] ~ Set the attributes that the next text put on the grid will have. `attrs` is a dict with the keys below. Any absent key is reset to its default value. Color defaults are set by the `update_fg` etc @@ -481,18 +479,18 @@ is not active. New UIs should implement |ui-linegrid| instead. `underdotted`: underdotted text. The dots have `special` color. `underdashed`: underdashed text. The dashes have `special` color. -["put", text] +["put", text] ~ The (utf-8 encoded) string `text` is put at the cursor position (and the cursor is advanced), with the highlights as set by the last `highlight_set` update. -["set_scroll_region", top, bot, left, right] +["set_scroll_region", top, bot, left, right] ~ Define the scroll region used by `scroll` below. Note: ranges are end-inclusive, which is inconsistent with API conventions. -["scroll", count] +["scroll", count] ~ Scroll the text in the scroll region. The diagrams below illustrate what will happen, depending on the scroll direction. "=" is used to represent the SR(scroll region) boundaries and "-" the moved rectangles. @@ -575,7 +573,7 @@ The multigrid extension gives UIs more control over how windows are displayed: per-window. Or reserve space around the border of the window for its own elements, such as scrollbars from the UI toolkit. - A dedicated grid is used for messages, which may scroll over the window - area. (Alternatively |ext_messages| can be used). + area. (Alternatively |ui-messages| can be used). By default, the grid size is handled by Nvim and set to the outer grid size (i.e. the size of the window frame in Nvim) whenever the split is created. @@ -587,46 +585,46 @@ A window can be hidden and redisplayed without its grid being deallocated. This can happen multiple times for the same window, for instance when switching tabs. -["win_pos", grid, win, start_row, start_col, width, height] +["win_pos", grid, win, start_row, start_col, width, height] ~ Set the position and size of the grid in Nvim (i.e. the outer grid size). If the window was previously hidden, it should now be shown again. -["win_float_pos", grid, win, anchor, anchor_grid, anchor_row, anchor_col, focusable] +["win_float_pos", grid, win, anchor, anchor_grid, anchor_row, anchor_col, focusable] ~ Display or reconfigure floating window `win`. The window should be displayed above another grid `anchor_grid` at the specified position `anchor_row` and `anchor_col`. For the meaning of `anchor` and more details of positioning, see |nvim_open_win()|. -["win_external_pos", grid, win] +["win_external_pos", grid, win] ~ Display or reconfigure external window `win`. The window should be displayed as a separate top-level window in the desktop environment, or something similar. -["win_hide", grid] +["win_hide", grid] ~ Stop displaying the window. The window can be shown again later. -["win_close", grid] +["win_close", grid] ~ Close the window. -["msg_set_pos", grid, row, scrolled, sep_char] - Display messages on `grid`. The grid will be displayed at `row` on the - default grid (grid=1), covering the full column width. `scrolled` +["msg_set_pos", grid, row, scrolled, sep_char] ~ + Display messages on `grid`. The grid will be displayed at `row` on + the default grid (grid=1), covering the full column width. `scrolled` indicates whether the message area has been scrolled to cover other - grids. It can be useful to draw a separator then ('display' msgsep - flag). The Builtin TUI draws a full line filled with `sep_char` and - |hl-MsgSeparator| highlight. + grids. It can be useful to draw a separator then |msgsep|. The Builtin + TUI draws a full line filled with `sep_char` ('fillchars' msgsep + field) and |hl-MsgSeparator| highlight. - When |ext_messages| is active, no message grid is used, and this event + When |ui-messages| is active, no message grid is used, and this event will not be sent. -["win_viewport", grid, win, topline, botline, curline, curcol] +["win_viewport", grid, win, topline, botline, curline, curcol] ~ Indicates the range of buffer text displayed in the window, as well as the cursor position in the buffer. All positions are zero-based. `botline` is set to one more than the line count of the buffer, if there are filler lines past the end. -["win_extmark", grid, win, ns_id, mark_id, row, col] +["win_extmark", grid, win, ns_id, mark_id, row, col] ~ Updates the position of an extmark which is currently visible in a window. Only emitted if the mark has the `ui_watched` attribute. @@ -638,7 +636,7 @@ Activated by the `ext_popupmenu` |ui-option|. This UI extension delegates presentation of the |popupmenu-completion| and command-line 'wildmenu'. -["popupmenu_show", items, selected, row, col, grid] +["popupmenu_show", items, selected, row, col, grid] ~ Show |popupmenu-completion|. `items` is an array of completion items to show; each item is an array of the form [word, kind, menu, info] as defined at |complete-items|, except that `word` is replaced by `abbr` @@ -650,12 +648,12 @@ command-line 'wildmenu'. set to -1 to indicate the popupmenu should be anchored to the external cmdline. Then `col` will be a byte position in the cmdline text. -["popupmenu_select", selected] +["popupmenu_select", selected] ~ Select an item in the current popupmenu. `selected` is a zero-based index into the array of items from the last popupmenu_show event, or -1 if no item is selected. -["popupmenu_hide"] +["popupmenu_hide"] ~ Hide the popupmenu. ============================================================================== @@ -663,7 +661,7 @@ Tabline Events *ui-tabline* Activated by the `ext_tabline` |ui-option|. -["tabline_update", curtab, tabs, curbuf, buffers] +["tabline_update", curtab, tabs, curbuf, buffers] ~ Tabline was updated. UIs should present this data in a custom tabline widget. Note: options `curbuf` + `buffers` were added in API7. curtab: Current Tabpage @@ -679,7 +677,7 @@ Activated by the `ext_cmdline` |ui-option|. This UI extension delegates presentation of the |cmdline| (except 'wildmenu'). For command-line 'wildmenu' UI events, activate |ui-popupmenu|. -["cmdline_show", content, pos, firstc, prompt, indent, level] +["cmdline_show", content, pos, firstc, prompt, indent, level] ~ content: List of [attrs, string] [[{}, "t"], [attrs, "est"], ...] @@ -702,10 +700,10 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. prompt has level 2. A command line invoked from the |cmdline-window| has a higher level than than the edited command line. -["cmdline_pos", pos, level] +["cmdline_pos", pos, level] ~ Change the cursor position in the cmdline. -["cmdline_special_char", c, shift, level] +["cmdline_special_char", c, shift, level] ~ Display a special char in the cmdline at the cursor position. This is typically used to indicate a pending state, e.g. after |c_CTRL-V|. If `shift` is true the text after the cursor should be shifted, otherwise @@ -713,10 +711,10 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. Should be hidden at next cmdline_show. -["cmdline_hide"] +["cmdline_hide"] ~ Hide the cmdline. -["cmdline_block_show", lines] +["cmdline_block_show", lines] ~ Show a block of context to the current command line. For example if the user defines a |:function| interactively: > :function Foo() @@ -726,10 +724,10 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. `lines` is a list of lines of highlighted chunks, in the same form as the "cmdline_show" `contents` parameter. -["cmdline_block_append", line] +["cmdline_block_append", line] ~ Append a line at the end of the currently shown block. -["cmdline_block_hide"] +["cmdline_block_hide"] ~ Hide the block. ============================================================================== @@ -746,7 +744,7 @@ Nvim will not allocate screen space for the cmdline or messages, and 'cmdheight' will be forced zero. Cmdline state is emitted as |ui-cmdline| events, which the UI must handle. -["msg_show", kind, content, replace_last] +["msg_show", kind, content, replace_last] ~ Display a message to the user. kind @@ -780,25 +778,25 @@ events, which the UI must handle. true: Replace the message in the most-recent `msg_show` call, but any other visible message should still remain. -["msg_clear"] +["msg_clear"] ~ Clear all messages currently displayed by "msg_show". (Messages sent by other "msg_" events below will not be affected). -["msg_showmode", content] +["msg_showmode", content] ~ Shows 'showmode' and |recording| messages. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_showcmd", content] +["msg_showcmd", content] ~ Shows 'showcmd' messages. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_ruler", content] +["msg_ruler", content] ~ Used to display 'ruler' when there is no space for the ruler in a statusline. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_history_show", entries] +["msg_history_show", entries] ~ Sent when |:messages| command is invoked. History is sent as a list of entries, where each entry is a `[kind, content]` tuple. diff --git a/runtime/doc/userfunc.txt b/runtime/doc/userfunc.txt new file mode 100644 index 0000000000..5462fa952c --- /dev/null +++ b/runtime/doc/userfunc.txt @@ -0,0 +1,428 @@ +*userfunc.txt* Nvim + + + VIM REFERENCE MANUAL by Bram Moolenaar + + +Defining and using functions. + +This is introduced in section |41.7| of the user manual. + + Type |gO| to see the table of contents. + +============================================================================== + +1. Defining a function ~ + *define-function* +New functions can be defined. These can be called just like builtin +functions. The function executes a sequence of Ex commands. Normal mode +commands can be executed with the |:normal| command. + +The function name must start with an uppercase letter, to avoid confusion with +builtin functions. To prevent from using the same name in different scripts +make them script-local. If you do use a global function then avoid obvious, +short names. A good habit is to start the function name with the name of the +script, e.g., "HTMLcolor()". + +It is also possible to use curly braces, see |curly-braces-names|. + +The |autoload| facility is useful to define a function only when it's called. + + *local-function* +A function local to a script must start with "s:". A local script function +can only be called from within the script and from functions, user commands +and autocommands defined in the script. It is also possible to call the +function from a mapping defined in the script, but then |<SID>| must be used +instead of "s:" when the mapping is expanded outside of the script. +There are only script-local functions, no buffer-local or window-local +functions. + + *:fu* *:function* *E128* *E129* *E123* +:fu[nction] List all functions and their arguments. + +:fu[nction][!] {name} List function {name}, annotated with line numbers + unless "!" is given. + {name} may be a |Dictionary| |Funcref| entry: > + :function dict.init + +:fu[nction] /{pattern} List functions with a name matching {pattern}. + Example that lists all functions ending with "File": > + :function /File$ +< + *:function-verbose* +When 'verbose' is non-zero, listing a function will also display where it was +last defined. Example: > + + :verbose function SetFileTypeSH + function SetFileTypeSH(name) + Last set from /usr/share/vim/vim-7.0/filetype.vim +< +See |:verbose-cmd| for more information. + + *E124* *E125* *E853* *E884* +:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure] + Define a new function by the name {name}. The body of + the function follows in the next lines, until the + matching |:endfunction|. + + The name must be made of alphanumeric characters and + '_', and must start with a capital or "s:" (see + above). Note that using "b:" or "g:" is not allowed. + (since patch 7.4.260 E884 is given if the function + name has a colon in the name, e.g. for "foo:bar()". + Before that patch no error was given). + + {name} can also be a |Dictionary| entry that is a + |Funcref|: > + :function dict.init(arg) +< "dict" must be an existing dictionary. The entry + "init" is added if it didn't exist yet. Otherwise [!] + is required to overwrite an existing function. The + result is a |Funcref| to a numbered function. The + function can only be used with a |Funcref| and will be + deleted if there are no more references to it. + *E127* *E122* + When a function by this name already exists and [!] is + not used an error message is given. There is one + exception: When sourcing a script again, a function + that was previously defined in that script will be + silently replaced. + When [!] is used, an existing function is silently + replaced. Unless it is currently being executed, that + is an error. + NOTE: Use ! wisely. If used without care it can cause + an existing function to be replaced unexpectedly, + which is hard to debug. + + For the {arguments} see |function-argument|. + + *:func-range* *a:firstline* *a:lastline* + When the [range] argument is added, the function is + expected to take care of a range itself. The range is + passed as "a:firstline" and "a:lastline". If [range] + is excluded, ":{range}call" will call the function for + each line in the range, with the cursor on the start + of each line. See |function-range-example|. + The cursor is still moved to the first line of the + range, as is the case with all Ex commands. + *:func-abort* + When the [abort] argument is added, the function will + abort as soon as an error is detected. + *:func-dict* + When the [dict] argument is added, the function must + be invoked through an entry in a |Dictionary|. The + local variable "self" will then be set to the + dictionary. See |Dictionary-function|. + *:func-closure* *E932* + When the [closure] argument is added, the function + can access variables and arguments from the outer + scope. This is usually called a closure. In this + example Bar() uses "x" from the scope of Foo(). It + remains referenced even after Foo() returns: > + :function! Foo() + : let x = 0 + : function! Bar() closure + : let x += 1 + : return x + : endfunction + : return funcref('Bar') + :endfunction + + :let F = Foo() + :echo F() +< 1 > + :echo F() +< 2 > + :echo F() +< 3 + + *function-search-undo* + The last used search pattern and the redo command "." + will not be changed by the function. This also + implies that the effect of |:nohlsearch| is undone + when the function returns. + + *:endf* *:endfunction* *E126* *E193* *W22* +:endf[unction] [argument] + The end of a function definition. Best is to put it + on a line by its own, without [argument]. + + [argument] can be: + | command command to execute next + \n command command to execute next + " comment always ignored + anything else ignored, warning given when + 'verbose' is non-zero + The support for a following command was added in Vim + 8.0.0654, before that any argument was silently + ignored. + + To be able to define a function inside an `:execute` + command, use line breaks instead of |:bar|: > + :exe "func Foo()\necho 'foo'\nendfunc" +< + *:delf* *:delfunction* *E131* *E933* +:delf[unction][!] {name} + Delete function {name}. + {name} can also be a |Dictionary| entry that is a + |Funcref|: > + :delfunc dict.init +< This will remove the "init" entry from "dict". The + function is deleted if there are no more references to + it. + With the ! there is no error if the function does not + exist. + *:retu* *:return* *E133* +:retu[rn] [expr] Return from a function. When "[expr]" is given, it is + evaluated and returned as the result of the function. + If "[expr]" is not given, the number 0 is returned. + When a function ends without an explicit ":return", + the number 0 is returned. + Note that there is no check for unreachable lines, + thus there is no warning if commands follow ":return". + + If the ":return" is used after a |:try| but before the + matching |:finally| (if present), the commands + following the ":finally" up to the matching |:endtry| + are executed first. This process applies to all + nested ":try"s inside the function. The function + returns at the outermost ":endtry". + + *function-argument* *a:var* +An argument can be defined by giving its name. In the function this can then +be used as "a:name" ("a:" for argument). + *a:0* *a:1* *a:000* *E740* *...* +Up to 20 arguments can be given, separated by commas. After the named +arguments an argument "..." can be specified, which means that more arguments +may optionally be following. In the function the extra arguments can be used +as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which +can be 0). "a:000" is set to a |List| that contains these arguments. Note +that "a:1" is the same as "a:000[0]". + *E742* +The a: scope and the variables in it cannot be changed, they are fixed. +However, if a composite type is used, such as |List| or |Dictionary| , you can +change their contents. Thus you can pass a |List| to a function and have the +function add an item to it. If you want to make sure the function cannot +change a |List| or |Dictionary| use |:lockvar|. + +It is also possible to define a function without any arguments. You must +still supply the () then. + +It is allowed to define another function inside a function body. + + *optional-function-argument* +You can provide default values for positional named arguments. This makes +them optional for function calls. When a positional argument is not +specified at a call, the default expression is used to initialize it. +This only works for functions declared with `:function`, not for +lambda expressions |expr-lambda|. + +Example: > + function Something(key, value = 10) + echo a:key .. ": " .. a:value + endfunction + call Something('empty') "empty: 10" + call Something('key', 20) "key: 20" + +The argument default expressions are evaluated at the time of the function +call, not definition. Thus it is possible to use an expression which is +invalid the moment the function is defined. The expressions are also only +evaluated when arguments are not specified during a call. + + *E989* +Optional arguments with default expressions must occur after any mandatory +arguments. You can use "..." after all optional named arguments. + +It is possible for later argument defaults to refer to prior arguments, +but not the other way around. They must be prefixed with "a:", as with all +arguments. + +Example that works: > + :function Okay(mandatory, optional = a:mandatory) + :endfunction +Example that does NOT work: > + :function NoGood(first = a:second, second = 10) + :endfunction +< +When not using "...", the number of arguments in a function call must be at +least equal to the number of mandatory named arguments. When using "...", the +number of arguments may be larger than the total of mandatory and optional +arguments. + + *local-variables* +Inside a function local variables can be used. These will disappear when the +function returns. Global variables need to be accessed with "g:". Inside +functions local variables are accessed without prepending anything. But you +can also prepend "l:" if you like. This is required for some reserved names, +such as "version". + +Example: > + :function Table(title, ...) + : echohl Title + : echo a:title + : echohl None + : echo a:0 .. " items:" + : for s in a:000 + : echon ' ' .. s + : endfor + :endfunction + +This function can then be called with: > + call Table("Table", "line1", "line2") + call Table("Empty Table") + +To return more than one value, return a |List|: > + :function Compute(n1, n2) + : if a:n2 == 0 + : return ["fail", 0] + : endif + : return ["ok", a:n1 / a:n2] + :endfunction + +This function can then be called with: > + :let [success, div] = Compute(102, 6) + :if success == "ok" + : echo div + :endif +< +============================================================================== + +2. Calling a function ~ + *:cal* *:call* *E107* *E117* +:[range]cal[l] {name}([arguments]) + Call a function. The name of the function and its arguments + are as specified with `:function`. Up to 20 arguments can be + used. The returned value is discarded. + Without a range and for functions that accept a range, the + function is called once. When a range is given the cursor is + positioned at the start of the first line before executing the + function. + When a range is given and the function doesn't handle it + itself, the function is executed for each line in the range, + with the cursor in the first column of that line. The cursor + is left at the last line (possibly moved by the last function + call). The arguments are re-evaluated for each line. Thus + this works: + *function-range-example* > + :function Mynumber(arg) + : echo line(".") .. " " .. a:arg + :endfunction + :1,5call Mynumber(getline(".")) +< + The "a:firstline" and "a:lastline" are defined anyway, they + can be used to do something different at the start or end of + the range. + + Example of a function that handles the range itself: > + + :function Cont() range + : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ ' + :endfunction + :4,8call Cont() +< + This function inserts the continuation character "\" in front + of all the lines in the range, except the first one. + + When the function returns a composite value it can be further + dereferenced, but the range will not be used then. Example: > + :4,8call GetDict().method() +< Here GetDict() gets the range but method() does not. + + *E132* +The recursiveness of user functions is restricted with the |'maxfuncdepth'| +option. + +It is also possible to use `:eval`. It does not support a range, but does +allow for method chaining, e.g.: > + eval GetList()->Filter()->append('$') + +A function can also be called as part of evaluating an expression or when it +is used as a method: > + let x = GetList() + let y = GetList()->Filter() + + +============================================================================== + +3. Automatically loading functions ~ + *autoload-functions* +When using many or large functions, it's possible to automatically define them +only when they are used. There are two methods: with an autocommand and with +the "autoload" directory in 'runtimepath'. + + +Using an autocommand ~ + +This is introduced in the user manual, section |41.14|. + +The autocommand is useful if you have a plugin that is a long Vim script file. +You can define the autocommand and quickly quit the script with `:finish`. +That makes Vim startup faster. The autocommand should then load the same file +again, setting a variable to skip the `:finish` command. + +Use the FuncUndefined autocommand event with a pattern that matches the +function(s) to be defined. Example: > + + :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim + +The file "~/vim/bufnetfuncs.vim" should then define functions that start with +"BufNet". Also see |FuncUndefined|. + + +Using an autoload script ~ + *autoload* *E746* +This is introduced in the user manual, section |41.15|. + +Using a script in the "autoload" directory is simpler, but requires using +exactly the right file name. A function that can be autoloaded has a name +like this: > + + :call filename#funcname() + +When such a function is called, and it is not defined yet, Vim will search the +"autoload" directories in 'runtimepath' for a script file called +"filename.vim". For example "~/.config/nvim/autoload/filename.vim". That +file should then define the function like this: > + + function filename#funcname() + echo "Done!" + endfunction + +The file name and the name used before the # in the function must match +exactly, and the defined function must have the name exactly as it will be +called. + +It is possible to use subdirectories. Every # in the function name works like +a path separator. Thus when calling a function: > + + :call foo#bar#func() + +Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'. + +This also works when reading a variable that has not been set yet: > + + :let l = foo#bar#lvar + +However, when the autoload script was already loaded it won't be loaded again +for an unknown variable. + +When assigning a value to such a variable nothing special happens. This can +be used to pass settings to the autoload script before it's loaded: > + + :let foo#bar#toggle = 1 + :call foo#bar#func() + +Note that when you make a mistake and call a function that is supposed to be +defined in an autoload script, but the script doesn't actually define the +function, you will get an error message for the missing function. If you fix +the autoload script it won't be automatically loaded again. Either restart +Vim or manually source the script. + +Also note that if you have two script files, and one calls a function in the +other and vice versa, before the used function is defined, it won't work. +Avoid using the autoload functionality at the toplevel. + +Hint: If you distribute a bunch of scripts read |distribute-script|. + + + vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/usr_22.txt b/runtime/doc/usr_22.txt index f53d578456..539bda3980 100644 --- a/runtime/doc/usr_22.txt +++ b/runtime/doc/usr_22.txt @@ -220,7 +220,7 @@ a tab page share this directory except for windows with a window-local directory. Any new windows opened in this tab page will use this directory as the current working directory. Using a `:cd` command in a tab page will not change the working directory of tab pages which have a tab local directory. -When the global working directory is changed using the ":cd" command in a tab +When the global working directory is changed using the `:cd` command in a tab page, it will also change the current tab page working directory. diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index 0c907bfb68..6690dad4a7 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -604,6 +604,8 @@ String manipulation: *string-functions* fnameescape() escape a file name for use with a Vim command tr() translate characters from one set to another strtrans() translate a string to make it printable + keytrans() translate internal keycodes to a form that + can be used by |:map| tolower() turn a string to lowercase toupper() turn a string to uppercase charclass() class of a character @@ -745,6 +747,7 @@ Cursor and mark position: *cursor-functions* *mark-functions* screencol() get screen column of the cursor screenrow() get screen row of the cursor screenpos() screen row and col of a text character + virtcol2col() byte index of a text character on screen getcurpos() get position of the cursor getpos() get position of cursor, mark, etc. setpos() set position of cursor, mark, etc. @@ -872,6 +875,7 @@ Command line: *command-line-functions* getcmdpos() get position of the cursor in the command line getcmdscreenpos() get screen position of the cursor in the command line + setcmdline() set the current command line setcmdpos() set position of the cursor in the command line getcmdtype() return the current command-line type getcmdwintype() return the current command-line window type @@ -1012,6 +1016,7 @@ Testing: *test-functions* assert_beeps() assert that a command beeps assert_nobeep() assert that a command does not cause a beep assert_fails() assert that a command fails + assert_report() report a test failure Timers: *timer-functions* timer_start() create a timer @@ -1069,8 +1074,8 @@ Various: *various-functions* wordcount() get byte/word/char count of buffer luaeval() evaluate |Lua| expression - py3eval() evaluate Python expression (|+python3|) - pyeval() evaluate Python expression (|+python|) + py3eval() evaluate |Python| expression + pyeval() evaluate |Python| expression pyxeval() evaluate |python_x| expression rubyeval() evaluate |Ruby| expression @@ -1706,7 +1711,7 @@ There is a little "catch" with comments for some commands. Examples: > :execute cmd " do it :!ls *.c " list C files -The abbreviation 'dev' will be expanded to 'development " shorthand'. The +The abbreviation "dev" will be expanded to 'development " shorthand'. The mapping of <F3> will actually be the whole line after the 'o# ....' including the '" insert include'. The "execute" command will give an error. The "!" command will send everything after it to the shell, causing an error for an @@ -1757,7 +1762,7 @@ does not exist as a mapped sequence. An error will be issued, which is very hard to identify, because the ending whitespace character in ":unmap ,ab " is not visible. -And this is the same as what happens when one uses a comment after an 'unmap' +And this is the same as what happens when one uses a comment after an "unmap" command: > :unmap ,ab " comment diff --git a/runtime/doc/usr_45.txt b/runtime/doc/usr_45.txt index 3199c4d8ea..0d23ef50fd 100644 --- a/runtime/doc/usr_45.txt +++ b/runtime/doc/usr_45.txt @@ -300,8 +300,7 @@ can use digraphs. This was already explained in |24.9|. keyboard, you will want to use an Input Method (IM). This requires learning the translation from typed keys to resulting character. When you need an IM you probably already have one on your system. It should work with Vim like -with other programs. For details see |mbyte-XIM| for the X Window system and -|mbyte-IME| for MS-Windows. +with other programs. KEYMAPS diff --git a/runtime/doc/usr_toc.txt b/runtime/doc/usr_toc.txt index bf9c02882c..c61bb55c26 100644 --- a/runtime/doc/usr_toc.txt +++ b/runtime/doc/usr_toc.txt @@ -5,7 +5,7 @@ Table Of Contents *user-manual* ============================================================================== -Overview ~ +Overview Getting Started |usr_01.txt| About the manuals @@ -52,7 +52,7 @@ The user manual is online: https://neovim.io/doc/user ============================================================================== -Getting Started ~ +Getting Started Read this from start to end to learn the essential commands. @@ -167,7 +167,7 @@ Read this from start to end to learn the essential commands. |12.8| Find where a word is used ============================================================================== -Editing Effectively ~ +Editing Effectively Subjects that can be read independently. @@ -275,7 +275,7 @@ Subjects that can be read independently. |32.4| Time travelling ============================================================================== -Tuning Vim ~ +Tuning Vim Make Vim work as you like it. diff --git a/runtime/doc/various.txt b/runtime/doc/various.txt index cae9c76030..cd178cfbbb 100644 --- a/runtime/doc/various.txt +++ b/runtime/doc/various.txt @@ -260,6 +260,10 @@ g8 Print the hex values of the bytes used in the Use |jobstart()| instead. > :call jobstart('foo', {'detach':1}) < + For powershell, chaining a stringed executable path + requires using the call operator (&). > + :!Write-Output "1`n2" | & "C:\Windows\System32\sort.exe" /r +< *E34* Any "!" in {cmd} is replaced with the previous external command (see also 'cpoptions'), unless diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index 53effa1443..62b755d64b 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -38,7 +38,7 @@ centralized reference of the differences. - 'complete' excludes "i" - 'cscopeverbose' is enabled - 'directory' defaults to ~/.local/state/nvim/swap// (|xdg|), auto-created -- 'display' defaults to "lastline,msgsep" +- 'display' defaults to "lastline" - 'encoding' is UTF-8 (cf. 'fileencoding' for file-content encoding) - 'fillchars' defaults (in effect) to "vert:│,fold:·,sep:│" - 'formatoptions' defaults to "tcqj" @@ -73,7 +73,7 @@ centralized reference of the differences. - 'wildmenu' is enabled - 'wildoptions' defaults to "pum,tagfile" -- |man.vim| plugin is enabled, so |:Man| is available by default. +- |man.lua| plugin is enabled, so |:Man| is available by default. - |matchit| plugin is enabled. To disable it in your config: > :let loaded_matchit = 1 @@ -82,27 +82,24 @@ centralized reference of the differences. Default Mouse ~ *default-mouse* *disable-mouse* -By default the mouse is enabled. The right button click opens |popup-menu| -with standard actions, such as "Cut", "Copy" and "Paste". - -If you don't like this you can add to your |config| any of the following: - -- ignore mouse completely > +By default the mouse is enabled, and <RightMouse> opens a |popup-menu| with +standard actions ("Cut", "Copy", "Paste", …). Mouse is NOT enabled in +|command-mode| or the |more-prompt|, so you can temporarily disable it just by +typing ":". + +If you don't like this you can disable the mouse in your |config| using any of +the following: +- Disable mouse completely by unsetting the 'mouse' option: > set mouse= -< -- no |popup-menu| but the right button extends selection > +- Pressing <RightMouse> extends selection instead of showing popup-menu: > set mousemodel=extend -> -- pressing ALT+LeftMouse releases mouse until main cursor moves > - nnoremap <M-LeftMouse> <Cmd> +- Pressing <A-LeftMouse> releases mouse until the cursor moves: > + nnoremap <A-LeftMouse> <Cmd> \ set mouse=<Bar> \ echo 'mouse OFF until next cursor-move'<Bar> \ autocmd CursorMoved * ++once set mouse&<Bar> \ echo 'mouse ON'<CR> < -Also, mouse is not in use in |command-mode| or at |more-prompt|. So if you -need to copy/paste with your terminal then just pressing ':' makes Nvim to -release the mouse cursor temporarily. Default Mappings ~ *default-mappings* @@ -256,9 +253,8 @@ Normal commands: Options: 'cpoptions' flags: |cpo-_| - 'display' flags: "msgsep" minimizes scrolling when showing messages 'guicursor' works in the terminal - 'fillchars' flags: "msgsep" (see 'display'), "horiz", "horizup", + 'fillchars' flags: "msgsep", "horiz", "horizup", "horizdown", "vertleft", "vertright", "verthoriz" 'foldcolumn' supports up to 9 dynamic/fixed columns 'inccommand' shows interactive results for |:substitute|-like commands @@ -372,6 +368,7 @@ Lua interface (|lua.txt|): Commands: |:doautocmd| does not warn about "No matching autocommands". |:wincmd| accepts a count. + `:write!` does not show a prompt if the file was updated externally. Command line completion: The meanings of arrow keys do not change depending on 'wildoptions'. @@ -390,6 +387,9 @@ Highlight groups: using |n| or |N| |hl-CursorLine| is low-priority unless foreground color is set |hl-VertSplit| superseded by |hl-WinSeparator| + Highlight groups names are allowed to contain the characters `.` and `@`. + It is an error to define a highlight group with a name that doesn't match + the regexp `[a-zA-Z0-9_.@]*` (see |group-name|). Macro/|recording| behavior Replay of a macro recorded during :lmap produces the same actions as when it @@ -413,8 +413,8 @@ Normal commands: Options: 'ttimeout', 'ttimeoutlen' behavior was simplified - |jumpoptions| "stack" behavior - |jumpoptions| "view" tries to restore the |mark-view| when moving through + 'jumpoptions' "stack" behavior + 'jumpoptions' "view" tries to restore the |mark-view| when moving through the |jumplist|, |changelist|, |alternate-file| or using |mark-motions|. 'shortmess' the "F" flag does not affect output from autocommands @@ -475,6 +475,11 @@ TUI: UI/Display: |Visual| selection highlights the character at cursor. |visual-use| + messages: When showing messages longer than 'cmdheight', only + scroll the message lines, not the entire screen. The + separator line is decorated by |hl-MsgSeparator| and + the "msgsep" flag of 'fillchars'. *msgsep* + Vimscript compatibility: `count` does not alias to |v:count| `errmsg` does not alias to |v:errmsg| @@ -494,13 +499,16 @@ Working directory (Vim implemented some of these later than Nvim): ============================================================================== 5. Missing legacy features *nvim-features-missing* -Some legacy Vim features are not implemented: +Some legacy Vim features are not yet implemented: -- |if_lua|: Nvim Lua API is not compatible with Vim's "if_lua" +- *if_lua* : Nvim |Lua| API is not compatible with Vim's "if_lua" - *if_mzscheme* -- |if_py|: *python-bindeval* *python-Function* are not supported +- |if_pyth|: *python-bindeval* *python-Function* are not supported - *if_tcl* +*:gui* +*:gvim* + ============================================================================== 6. Removed features *nvim-features-removed* @@ -562,18 +570,18 @@ Highlight groups: < Options: - 'antialias' + antialias *'balloondelay'* *'bdlay'* *'ballooneval'* *'beval'* *'noballooneval'* *'nobeval'* *'balloonexpr'* *'bexpr'* - 'bioskey' (MS-DOS) - 'conskey' (MS-DOS) + bioskey (MS-DOS) + conskey (MS-DOS) *'cp'* *'nocompatible'* *'nocp'* *'compatible'* (Nvim is always "nocompatible".) 'cpoptions' (gjkHw<*- and all POSIX flags were removed) *'cryptmethod'* *'cm'* *'key'* (Vim encryption implementation) *'ed'* *'edcompatible'* *'noed'* *'noedcompatible'* 'encoding' ("utf-8" is always used) - 'esckeys' + esckeys 'guioptions' "t" flag was removed *'guifontset'* *'gfs'* (Use 'guifont' instead.) *'guipty'* (Nvim uses pipes and PTYs consistently on all platforms.) @@ -614,18 +622,18 @@ Options: Nvim always displays up to 6 combining characters. You can still edit text with more than 6 combining characters, you just can't see them. Use |g8| or |ga|. See |mbyte-combining|. - 'maxmem' Nvim delegates memory-management to the OS. - 'maxmemtot' Nvim delegates memory-management to the OS. + *'maxmem'* Nvim delegates memory-management to the OS. + *'maxmemtot'* Nvim delegates memory-management to the OS. *'prompt'* *'noprompt'* *'remap'* *'noremap'* *'restorescreen'* *'rs'* *'norestorescreen'* *'nors'* - 'shelltype' + *'shelltype'* *'shortname'* *'sn'* *'noshortname'* *'nosn'* *'swapsync'* *'sws'* *'termencoding'* *'tenc'* (Vim 7.4.852 also removed this for Windows) *'terse'* *'noterse'* (Add "s" to 'shortmess' instead) - 'textauto' - 'textmode' + textauto + textmode *'toolbar'* *'tb'* *'toolbariconsize'* *'tbis'* *'ttybuiltin'* *'tbi'* *'nottybuiltin'* *'notbi'* @@ -633,7 +641,10 @@ Options: *'ttymouse'* *'ttym'* *'ttyscroll'* *'tsl'* *'ttytype'* *'tty'* - 'weirdinvert' + weirdinvert + +Performance: + Folds are not updated during insert-mode. Startup: --literal (file args are always literal; to expand wildcards on Windows, use diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 7355cec522..45cedd2cd8 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -119,7 +119,7 @@ windows. *filler-lines* The lines after the last buffer line in a window are called filler lines. By -default, these lines start with a tilde (~) character. The 'eob' item in the +default, these lines start with a tilde (~) character. The "eob" item in the 'fillchars' option can be used to change this character. By default, these characters are highlighted as NonText (|hl-NonText|). The EndOfBuffer highlight group (|hl-EndOfBuffer|) can be used to change the highlighting of @@ -148,7 +148,7 @@ CTRL-W CTRL-S *CTRL-W_CTRL-S* Note: CTRL-S does not work on all terminals and might block further input, use CTRL-Q to get going again. Also see |++opt| and |+cmd|. - *E242* + *E242* *E1159* Be careful when splitting a window in an autocommand, it may mess up the window layout if this happens while making other window layout changes. @@ -163,6 +163,8 @@ CTRL-W v *CTRL-W_v* 3. 'eadirection' isn't "ver", and 4. one of the other windows is wider than the current or new window. + If N was given make the new window N columns wide, if + possible. Note: In other places CTRL-Q does the same as CTRL-V, but here it doesn't! @@ -233,9 +235,16 @@ and 'winminwidth' are relevant. *:vert* *:vertical* :vert[ical] {cmd} Execute {cmd}. If it contains a command that splits a window, - it will be split vertically. + it will be split vertically. For `vertical wincmd =` windows + will be equalized only vertically. Doesn't work for |:execute| and |:normal|. + *:hor* *:horizontal* +:hor[izontal] {cmd} + Execute {cmd}. Currently only makes a difference for + `horizontal wincmd =`, which will equalize windows only + horizontally. + :lefta[bove] {cmd} *:lefta* *:leftabove* :abo[veleft] {cmd} *:abo* *:aboveleft* Execute {cmd}. If it contains a command that splits a window, @@ -282,9 +291,8 @@ Closing a window :{count}q[uit] *:count_quit* CTRL-W q *CTRL-W_q* CTRL-W CTRL-Q *CTRL-W_CTRL-Q* - Without {count}: Quit the current window. If {count} is - given quit the {count} window - + Without {count}: Quit the current window. If {count} is + given quit the {count} window. *edit-window* When quitting the last edit window (not counting help or preview windows), exit Vim. @@ -343,7 +351,7 @@ CTRL-W CTRL-C *CTRL-W_CTRL-C* window, but that does not work, because the CTRL-C cancels the command. - *:hide* + *:hide* :hid[e] :{count}hid[e] Without {count}: Quit the current window, unless it is the @@ -528,6 +536,10 @@ CTRL-W = Make all windows (almost) equally high and wide, but use 'winheight' and 'winwidth' for the current window. Windows with 'winfixheight' set keep their height and windows with 'winfixwidth' set keep their width. + To equalize only vertically (make window equally high) use + `vertical wincmd =` + To equalize only horizontally (make window equally wide) use + `horizontal wincmd =` :res[ize] -N *:res* *:resize* *CTRL-W_-* CTRL-W - Decrease current window height by N (default 1). @@ -738,6 +750,7 @@ can also get to them with the buffer list commands, like ":bnext". the current window. {cmd} can contain '|' to concatenate several commands. {cmd} must not open or close windows or reorder them. + Also see |:tabdo|, |:argdo|, |:bufdo|, |:cdo|, |:ldo|, |:cfdo| and |:lfdo|. @@ -765,6 +778,7 @@ can also get to them with the buffer list commands, like ":bnext". autocommand event is disabled by adding it to 'eventignore'. This considerably speeds up editing each buffer. + Also see |:tabdo|, |:argdo|, |:windo|, |:cdo|, |:ldo|, |:cfdo| and |:lfdo|. diff --git a/runtime/filetype.lua b/runtime/filetype.lua index 9f5b5fd0dc..ee9d5a0a75 100644 --- a/runtime/filetype.lua +++ b/runtime/filetype.lua @@ -6,7 +6,7 @@ vim.g.did_load_filetypes = 1 vim.api.nvim_create_augroup('filetypedetect', { clear = false }) -vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile' }, { +vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile', 'StdinReadPost' }, { group = 'filetypedetect', callback = function(args) local ft, on_detect = vim.filetype.match({ filename = args.match, buf = args.buf }) @@ -14,10 +14,14 @@ vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile' }, { -- Generic configuration file used as fallback ft = require('vim.filetype.detect').conf(args.file, args.buf) if ft then - vim.api.nvim_cmd({ cmd = 'setf', args = { 'FALLBACK', ft } }, {}) + vim.api.nvim_buf_call(args.buf, function() + vim.api.nvim_cmd({ cmd = 'setf', args = { 'FALLBACK', ft } }, {}) + end) end else - vim.api.nvim_buf_set_option(args.buf, 'filetype', ft) + vim.api.nvim_buf_call(args.buf, function() + vim.api.nvim_cmd({ cmd = 'setf', args = { ft } }, {}) + end) if on_detect then on_detect(args.buf) end diff --git a/runtime/filetype.vim b/runtime/filetype.vim index 52a20d5c10..b6673c1762 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -1,7 +1,7 @@ " Vim support file to detect file types " " Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2022 Jul 5 +" Last Change: 2022 Sep 27 " Only run this if enabled if !exists("do_legacy_filetype") @@ -300,6 +300,9 @@ au BufNewFile,BufRead cfengine.conf setf cfengine " ChaiScript au BufRead,BufNewFile *.chai setf chaiscript +" Chatito +au BufNewFile,BufRead *.chatito setf chatito + " Comshare Dimension Definition Language au BufNewFile,BufRead *.cdl setf cdl @@ -449,6 +452,9 @@ endif " Lynx config files au BufNewFile,BufRead lynx.cfg setf lynx +" LyRiCs +au BufNewFile,BufRead *.lrc setf lyrics + " Modula-3 configuration language (must be before *.cfg and *makefile) au BufNewFile,BufRead *.quake,cm3.cfg setf m3quake au BufNewFile,BufRead m3makefile,m3overrides setf m3build @@ -697,7 +703,10 @@ au BufNewFile,BufRead *.mo,*.gdmo setf gdmo au BufNewFile,BufRead *.gd setf gdscript " Godot resource -au BufRead,BufNewFile *.tscn,*.tres setf gdresource +au BufRead,BufNewFile *.tscn,*.tres setf gdresource + +" Godot shader +au BufRead,BufNewFile *.gdshader,*.shader setf gdshader " Gedcom au BufNewFile,BufRead *.ged,lltxxxxx.txt setf gedcom @@ -718,9 +727,16 @@ au BufNewFile,BufRead *.git/worktrees/*/config.worktree setf gitconfig au BufNewFile,BufRead .gitmodules,*.git/modules/*/config setf gitconfig if !empty($XDG_CONFIG_HOME) au BufNewFile,BufRead $XDG_CONFIG_HOME/git/config setf gitconfig + au BufNewFile,BufRead $XDG_CONFIG_HOME/git/attributes setf gitattributes + au BufNewFile,BufRead $XDG_CONFIG_HOME/git/ignore setf gitignore endif -au BufNewFile,BufRead git-rebase-todo setf gitrebase -au BufRead,BufNewFile .gitsendemail.msg.?????? setf gitsendemail +au BufNewFile,BufRead .gitattributes,*.git/info/attributes setf gitattributes +au BufNewFile,BufRead */.config/git/attributes setf gitattributes +au BufNewFile,BufRead */etc/gitattributes setf gitattributes +au BufNewFile,BufRead .gitignore,*.git/info/exclude setf gitignore +au BufNewFile,BufRead */.config/git/ignore setf gitignore +au BufNewFile,BufRead git-rebase-todo setf gitrebase +au BufRead,BufNewFile .gitsendemail.msg.?????? setf gitsendemail au BufNewFile,BufRead *.git/* \ if getline(1) =~# '^\x\{40,\}\>\|^ref: ' | \ setf git | @@ -755,8 +771,8 @@ au BufNewFile,BufRead gitolite.conf setf gitolite au BufNewFile,BufRead {,.}gitolite.rc,example.gitolite.rc setf perl " Glimmer-flavored TypeScript and JavaScript -au BufNewFile,BufRead *.gts setf typescript.glimmer -au BufNewFile,BufRead *.gjs setf javascript.glimmer +au BufNewFile,BufRead *.gts setf typescript.glimmer +au BufNewFile,BufRead *.gjs setf javascript.glimmer " Gnuplot scripts au BufNewFile,BufRead *.gpi,.gnuplot setf gnuplot @@ -787,6 +803,9 @@ au BufNewFile,BufRead */etc/group,*/etc/group-,*/etc/group.edit,*/etc/gshadow,*/ " GTK RC au BufNewFile,BufRead .gtkrc,gtkrc setf gtkrc +" GYP +au BufNewFile,BufRead *.gyp,*.gypi setf gyp + " Hack au BufRead,BufNewFile *.hack,*.hackpartial setf hack @@ -829,6 +848,9 @@ au BufNewFile,BufRead *.hex,*.h32 setf hex " Hjson au BufNewFile,BufRead *.hjson setf hjson +" HLS Playlist (or another form of playlist) +au BufNewFile,BufRead *.m3u,*.m3u8 setf hlsplaylist + " Hollywood au BufRead,BufNewFile *.hws setf hollywood @@ -865,11 +887,11 @@ au BufNewFile,BufRead *.htt,*.htb setf httest " i3 au BufNewFile,BufRead */i3/config setf i3config -au BufNewFile,BufRead */.i3/config setf i3config +au BufNewFile,BufRead */.i3/config setf i3config " sway au BufNewFile,BufRead */sway/config setf swayconfig -au BufNewFile,BufRead */.sway/config setf swayconfig +au BufNewFile,BufRead */.sway/config setf swayconfig " Icon au BufNewFile,BufRead *.icn setf icon @@ -938,7 +960,7 @@ au BufNewFile,BufRead *.java,*.jav setf java au BufNewFile,BufRead *.jj,*.jjt setf javacc " JavaScript, ECMAScript, ES module script, CommonJS script -au BufNewFile,BufRead *.js,*.javascript,*.es,*.mjs,*.cjs setf javascript +au BufNewFile,BufRead *.js,*.jsm,*.javascript,*.es,*.mjs,*.cjs setf javascript " JavaScript with React au BufNewFile,BufRead *.jsx setf javascriptreact @@ -976,6 +998,9 @@ au BufNewFile,BufRead .babelrc,.eslintrc,.prettierrc,.firebaserc setf json " JSONC au BufNewFile,BufRead *.jsonc setf jsonc +" Jsonnet +au BufNewFile,BufRead *.jsonnet,*.libjsonnet setf jsonnet + " Julia au BufNewFile,BufRead *.jl setf julia @@ -1005,6 +1030,9 @@ au BufNewFile,BufRead Kconfig,Kconfig.debug setf kconfig " Lace (ISE) au BufNewFile,BufRead *.ace,*.ACE setf lace +" Latexmkrc +au BufNewFile,BufRead .latexmkrc,latexmkrc setf perl + " Latte au BufNewFile,BufRead *.latte,*.lte setf latte @@ -1085,6 +1113,9 @@ au BufNewFile,BufRead *.lou,*.lout setf lout " Lua au BufNewFile,BufRead *.lua setf lua +" Luacheck +au BufNewFile,BufRead .luacheckrc setf lua + " Luarocks au BufNewFile,BufRead *.rockspec setf lua @@ -1257,6 +1288,9 @@ au BufNewFile,BufRead .netrc setf netrc " Nginx au BufNewFile,BufRead *.nginx,nginx*.conf,*nginx.conf,*/etc/nginx/*,*/usr/local/nginx/conf/*,*/nginx/*.conf setf nginx +" Nim file +au BufNewFile,BufRead *.nim,*.nims,*.nimble setf nim + " Ninja file au BufNewFile,BufRead *.ninja setf ninja @@ -1314,7 +1348,7 @@ au BufNewFile,BufRead *.or setf openroad au BufNewFile,BufRead *.[Oo][Pp][Ll] setf opl " OpenSCAD -au BufNewFile,BufRead *.scad setf openscad +au BufNewFile,BufRead *.scad setf openscad " Oracle config file au BufNewFile,BufRead *.ora setf ora @@ -1358,6 +1392,9 @@ au BufNewFile,BufRead *.dpr,*.lpr setf pascal " Free Pascal makefile definition file au BufNewFile,BufRead *.fpc setf fpcmake +" Path of Exile item filter +au BufNewFile,BufRead *.filter setf poefilter + " PDF au BufNewFile,BufRead *.pdf setf pdf @@ -1389,7 +1426,8 @@ au BufNewFile,BufRead *.pod setf pod " Also Phtml (was used for PHP 2 in the past). " Also .ctp for Cake template file. " Also .phpt for php tests. -au BufNewFile,BufRead *.php,*.php\d,*.phtml,*.ctp,*.phpt setf php +" Also .theme for Drupal theme files. +au BufNewFile,BufRead *.php,*.php\d,*.phtml,*.ctp,*.phpt,*.theme setf php " PHP config au BufNewFile,BufRead php.ini-* setf dosini @@ -1710,6 +1748,12 @@ au BufNewFile,BufRead *.sdl,*.pr setf sdl " sed au BufNewFile,BufRead *.sed setf sed +" SubRip +au BufNewFile,BufRead *.srt setf srt + +" SubStation Alpha +au BufNewFile,BufRead *.ass,*.ssa setf ssa + " svelte au BufNewFile,BufRead *.svelte setf svelte @@ -1820,7 +1864,7 @@ au BufNewFile,BufRead *.score setf slrnsc au BufNewFile,BufRead *.st setf st " Smalltalk (and Rexx, TeX, and Visual Basic) -au BufNewFile,BufRead *.cls call dist#ft#FTcls() +au BufNewFile,BufRead *.cls call dist#ft#FTcls() " Smarty templates au BufNewFile,BufRead *.tpl setf smarty @@ -1927,8 +1971,8 @@ au BufNewFile,BufRead *.cm setf voscm au BufNewFile,BufRead *.swift setf swift au BufNewFile,BufRead *.swift.gyb setf swiftgyb -" Swift Intermediate Language -au BufNewFile,BufRead *.sil setf sil +" Swift Intermediate Language or SILE +au BufNewFile,BufRead *.sil call dist#ft#FTsil() " Sysctl au BufNewFile,BufRead */etc/sysctl.conf,*/etc/sysctl.d/*.conf setf sysctl @@ -2055,7 +2099,7 @@ au BufNewFile,BufReadPost *.tutor setf tutor " TWIG files au BufNewFile,BufReadPost *.twig setf twig -" Typescript or Qt translation file (which is XML) +" TypeScript or Qt translation file (which is XML) au BufNewFile,BufReadPost *.ts \ if getline(1) =~ '<?xml' | \ setf xml | @@ -2063,6 +2107,9 @@ au BufNewFile,BufReadPost *.ts \ setf typescript | \ endif +" TypeScript module and common +au BufNewFile,BufRead *.mts,*.cts setf typescript + " TypeScript with React au BufNewFile,BufRead *.tsx setf typescriptreact @@ -2095,6 +2142,14 @@ au BufNewFile,BufRead */.config/upstart/*.override setf upstart " Vala au BufNewFile,BufRead *.vala setf vala +" VDF +au BufNewFile,BufRead *.vdf setf vdf + +" VDM +au BufRead,BufNewFile *.vdmpp,*.vpp setf vdmpp +au BufRead,BufNewFile *.vdmrt setf vdmrt +au BufRead,BufNewFile *.vdmsl,*.vdm setf vdmsl + " Vera au BufNewFile,BufRead *.vr,*.vri,*.vrh setf vera @@ -2246,7 +2301,7 @@ au BufNewFile,BufRead *.fsproj,*.fsproj.user setf xml au BufNewFile,BufRead *.vbproj,*.vbproj.user setf xml " Qt Linguist translation source and Qt User Interface Files are XML -" However, for .ts Typescript is more common. +" However, for .ts TypeScript is more common. au BufNewFile,BufRead *.ui setf xml " TPM's are RDF-based descriptions of TeX packages (Nikolai Weibull) @@ -2564,6 +2619,9 @@ au BufNewFile,BufRead *.txt \| setf text \| endif +" Blueprint markup files +au BufNewFile,BufRead *.blp setf blueprint + if !exists('g:did_load_ftdetect') " Use the filetype detect plugins. They may overrule any of the previously " detected filetypes. diff --git a/runtime/ftplugin/chatito.vim b/runtime/ftplugin/chatito.vim new file mode 100644 index 0000000000..af212e9581 --- /dev/null +++ b/runtime/ftplugin/chatito.vim @@ -0,0 +1,15 @@ +" Vim filetype plugin +" Language: Chatito +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Sep 19 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setlocal comments=:#,:// commentstring=#\ %s +" indent of 4 spaces is mandated by the spec +setlocal expandtab softtabstop=4 shiftwidth=4 + +let b:undo_ftplugin = 'setl com< cms< et< sts< sw<' diff --git a/runtime/ftplugin/crontab.vim b/runtime/ftplugin/crontab.vim new file mode 100644 index 0000000000..8dac007ccc --- /dev/null +++ b/runtime/ftplugin/crontab.vim @@ -0,0 +1,16 @@ +" Vim filetype plugin +" Language: crontab +" Maintainer: Keith Smiley <keithbsmiley@gmail.com> +" Last Change: 2022 Sep 11 + +" Only do this when not done yet for this buffer +if exists("b:did_ftplugin") + finish +endif + +" Don't load another plugin for this buffer +let b:did_ftplugin = 1 + +let b:undo_ftplugin = "setl commentstring<" + +setlocal commentstring=#\ %s diff --git a/runtime/ftplugin/elixir.vim b/runtime/ftplugin/elixir.vim index c423c2acb7..50f63673dc 100644 --- a/runtime/ftplugin/elixir.vim +++ b/runtime/ftplugin/elixir.vim @@ -1,7 +1,7 @@ " Elixir filetype plugin " Language: Elixir " Maintainer: Mitchell Hanberg <vimNOSPAM@mitchellhanberg.com> -" Last Change: 2022 August 10 +" Last Change: 2022 Sep 20 if exists("b:did_ftplugin") finish @@ -23,7 +23,11 @@ if exists('loaded_matchit') && !exists('b:match_words') \ ',{:},\[:\],(:)' endif +setlocal shiftwidth=2 softtabstop=2 expandtab iskeyword+=!,? +setlocal comments=:# setlocal commentstring=#\ %s +let b:undo_ftplugin = 'setlocal sw< sts< et< isk< com< cms<' + let &cpo = s:save_cpo unlet s:save_cpo diff --git a/runtime/ftplugin/erlang.vim b/runtime/ftplugin/erlang.vim index c775247f51..31fa0c3213 100644 --- a/runtime/ftplugin/erlang.vim +++ b/runtime/ftplugin/erlang.vim @@ -5,7 +5,7 @@ " Contributors: Ricardo Catalinas Jiménez <jimenezrick@gmail.com> " Eduardo Lopez (http://github.com/tapichu) " Arvid Bjurklint (http://github.com/slarwise) -" Last Update: 2021-Jan-08 +" Last Update: 2021-Nov-22 " License: Vim license " URL: https://github.com/vim-erlang/vim-erlang-runtime @@ -30,6 +30,28 @@ setlocal commentstring=%%s setlocal formatoptions+=ro +if get(g:, 'erlang_extend_path', 1) + " typical erlang.mk paths + let &l:path = join([ + \ 'deps/*/include', + \ 'deps/*/src', + \ 'deps/*/test', + \ 'deps/*/apps/*/include', + \ 'deps/*/apps/*/src', + \ &g:path], ',') + " typical rebar3 paths + let &l:path = join([ + \ 'apps/*/include', + \ 'apps/*/src', + \ '_build/default/lib/*/src', + \ '_build/default/*/include', + \ &l:path], ',') + " typical erlang paths + let &l:path = join(['include', 'src', 'test', &l:path], ',') + + set wildignore+=*/.erlang.mk/*,*.beam +endif + setlocal suffixesadd=.erl,.hrl let &l:include = '^\s*-\%(include\|include_lib\)\s*("\zs\f*\ze")' diff --git a/runtime/ftplugin/gitattributes.vim b/runtime/ftplugin/gitattributes.vim new file mode 100644 index 0000000000..2025d009d2 --- /dev/null +++ b/runtime/ftplugin/gitattributes.vim @@ -0,0 +1,13 @@ +" Vim filetype plugin +" Language: git attributes +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Sep 08 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setl comments=:# commentstring=#\ %s + +let b:undo_ftplugin = 'setl com< cms<' diff --git a/runtime/ftplugin/gitignore.vim b/runtime/ftplugin/gitignore.vim new file mode 100644 index 0000000000..3502dd2717 --- /dev/null +++ b/runtime/ftplugin/gitignore.vim @@ -0,0 +1,13 @@ +" Vim filetype plugin +" Language: git ignore +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Sep 10 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setl comments=:# commentstring=#\ %s + +let b:undo_ftplugin = 'setl com< cms<' diff --git a/runtime/ftplugin/gyp.vim b/runtime/ftplugin/gyp.vim new file mode 100644 index 0000000000..becfcadb6d --- /dev/null +++ b/runtime/ftplugin/gyp.vim @@ -0,0 +1,14 @@ +" Vim filetype plugin +" Language: GYP +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Sep 27 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setlocal formatoptions-=t +setlocal commentstring=#\ %s comments=b:#,fb:- + +let b:undo_ftplugin = 'setlocal fo< cms< com<' diff --git a/runtime/ftplugin/hare.vim b/runtime/ftplugin/hare.vim new file mode 100644 index 0000000000..bb10daf38c --- /dev/null +++ b/runtime/ftplugin/hare.vim @@ -0,0 +1,27 @@ +" Vim filetype plugin +" Language: Hare +" Maintainer: Amelia Clarke <me@rsaihe.dev> +" Previous Maintainer: Drew DeVault <sir@cmpwn.com> +" Last Updated: 2022-09-21 + +" Only do this when not done yet for this buffer +if exists('b:did_ftplugin') + finish +endif + +" Don't load another plugin for this buffer +let b:did_ftplugin = 1 + +setlocal noexpandtab +setlocal tabstop=8 +setlocal shiftwidth=0 +setlocal softtabstop=0 +setlocal textwidth=80 +setlocal commentstring=//\ %s + +" Set 'formatoptions' to break comment lines but not other lines, +" and insert the comment leader when hitting <CR> or using "o". +setlocal fo-=t fo+=croql + +compiler hare +" vim: tabstop=2 shiftwidth=2 expandtab diff --git a/runtime/ftplugin/heex.vim b/runtime/ftplugin/heex.vim new file mode 100644 index 0000000000..5274d59fbf --- /dev/null +++ b/runtime/ftplugin/heex.vim @@ -0,0 +1,16 @@ +" Elixir filetype plugin +" Language: HEEx +" Maintainer: Mitchell Hanberg <vimNOSPAM@mitchellhanberg.com> +" Last Change: 2022 Sep 21 + +if exists("b:did_ftplugin") + finish +endif +let b:did_ftplugin = 1 + +setlocal shiftwidth=2 softtabstop=2 expandtab + +setlocal comments=:<%!-- +setlocal commentstring=<%!--\ %s\ --%> + +let b:undo_ftplugin = 'set sw< sts< et< com< cms<' diff --git a/runtime/ftplugin/jsonnet.vim b/runtime/ftplugin/jsonnet.vim new file mode 100644 index 0000000000..1e621e1867 --- /dev/null +++ b/runtime/ftplugin/jsonnet.vim @@ -0,0 +1,17 @@ +" Vim filetype plugin +" Language: Jsonnet +" Maintainer: Cezary Drożak <cezary@drozak.net> +" URL: https://github.com/google/vim-jsonnet +" Last Change: 2022-09-08 + +" Only do this when not done yet for this buffer +if exists("b:did_ftplugin") + finish +endif + +" Don't load another plugin for this buffer +let b:did_ftplugin = 1 + +setlocal commentstring=//\ %s + +let b:undo_ftplugin = "setlocal commentstring<" diff --git a/runtime/ftplugin/lua.lua b/runtime/ftplugin/lua.lua new file mode 100644 index 0000000000..415cf28f9a --- /dev/null +++ b/runtime/ftplugin/lua.lua @@ -0,0 +1,3 @@ +if vim.g.ts_highlight_lua then + vim.treesitter.start() +end diff --git a/runtime/ftplugin/lua.vim b/runtime/ftplugin/lua.vim index 2604257594..aaa61f71d9 100644 --- a/runtime/ftplugin/lua.vim +++ b/runtime/ftplugin/lua.vim @@ -1,46 +1,46 @@ " Vim filetype plugin file. -" Language: Lua +" Language: Lua " Maintainer: Doug Kearns <dougkearns@gmail.com> " Previous Maintainer: Max Ischenko <mfi@ukr.net> -" Last Change: 2021 Nov 15 +" Contributor: Dorai Sitaram <ds26@gte.com> +" Last Change: 2022 Sep 05 -" Only do this when not done yet for this buffer if exists("b:did_ftplugin") finish endif - -" Don't load another plugin for this buffer let b:did_ftplugin = 1 let s:cpo_save = &cpo set cpo&vim -" Set 'formatoptions' to break comment lines but not other lines, and insert -" the comment leader when hitting <CR> or using "o". +setlocal comments=:-- +setlocal commentstring=--\ %s setlocal formatoptions-=t formatoptions+=croql -setlocal comments=:-- -setlocal commentstring=--%s +let &l:define = '\<function\|\<local\%(\s\+function\)\=' + setlocal suffixesadd=.lua -let b:undo_ftplugin = "setlocal fo< com< cms< sua<" +let b:undo_ftplugin = "setlocal cms< com< def< fo< sua<" if exists("loaded_matchit") && !exists("b:match_words") let b:match_ignorecase = 0 let b:match_words = - \ '\<\%(do\|function\|if\)\>:' . - \ '\<\%(return\|else\|elseif\)\>:' . - \ '\<end\>,' . - \ '\<repeat\>:\<until\>,' . - \ '\%(--\)\=\[\(=*\)\[:]\1]' - let b:undo_ftplugin .= " | unlet! b:match_words b:match_ignorecase" + \ '\<\%(do\|function\|if\)\>:' .. + \ '\<\%(return\|else\|elseif\)\>:' .. + \ '\<end\>,' .. + \ '\<repeat\>:\<until\>,' .. + \ '\%(--\)\=\[\(=*\)\[:]\1]' + let b:undo_ftplugin ..= " | unlet! b:match_words b:match_ignorecase" endif if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter") - let b:browsefilter = "Lua Source Files (*.lua)\t*.lua\n" . - \ "All Files (*.*)\t*.*\n" - let b:undo_ftplugin .= " | unlet! b:browsefilter" + let b:browsefilter = "Lua Source Files (*.lua)\t*.lua\n" .. + \ "All Files (*.*)\t*.*\n" + let b:undo_ftplugin ..= " | unlet! b:browsefilter" endif let &cpo = s:cpo_save unlet s:cpo_save + +" vim: nowrap sw=2 sts=2 ts=8 noet: diff --git a/runtime/ftplugin/lynx.vim b/runtime/ftplugin/lynx.vim new file mode 100644 index 0000000000..b76c69f0ae --- /dev/null +++ b/runtime/ftplugin/lynx.vim @@ -0,0 +1,29 @@ +" Vim filetype plugin file +" Language: Lynx Web Browser Configuration +" Maintainer: Doug Kearns <dougkearns@gmail.com> +" Last Change: 2022 Sep 09 + +if exists("b:did_ftplugin") + finish +endif +let b:did_ftplugin = 1 + +let s:cpo_save = &cpo +set cpo&vim + +setlocal comments=:# +setlocal commentstring=#\ %s +setlocal formatoptions-=t formatoptions+=croql + +let b:undo_ftplugin = "setl cms< com< fo<" + +if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter") + let b:browsefilter = "Lynx Configuration Files (lynx.cfg .lynxrc)\tlynx.cfg;.lynxrc\n" .. + \ "All Files (*.*)\t*.*\n" + let b:undo_ftplugin ..= " | unlet! b:browsefilter" +endif + +let &cpo = s:cpo_save +unlet s:cpo_save + +" vim: nowrap sw=2 sts=2 ts=8 noet: diff --git a/runtime/ftplugin/man.vim b/runtime/ftplugin/man.vim index d7a08a9941..277ce3c0b3 100644 --- a/runtime/ftplugin/man.vim +++ b/runtime/ftplugin/man.vim @@ -17,12 +17,12 @@ setlocal iskeyword=@-@,:,a-z,A-Z,48-57,_,.,-,(,) setlocal nonumber norelativenumber setlocal foldcolumn=0 colorcolumn=0 nolist nofoldenable -setlocal tagfunc=man#goto_tag +setlocal tagfunc=v:lua.require'man'.goto_tag if !exists('g:no_plugin_maps') && !exists('g:no_man_maps') nnoremap <silent> <buffer> j gj nnoremap <silent> <buffer> k gk - nnoremap <silent> <buffer> gO :call man#show_toc()<CR> + nnoremap <silent> <buffer> gO :lua require'man'.show_toc()<CR> nnoremap <silent> <buffer> <2-LeftMouse> :Man<CR> if get(b:, 'pager') nnoremap <silent> <buffer> <nowait> q :lclose<CR><C-W>q diff --git a/runtime/ftplugin/racket.vim b/runtime/ftplugin/racket.vim new file mode 100644 index 0000000000..3aa413397e --- /dev/null +++ b/runtime/ftplugin/racket.vim @@ -0,0 +1,82 @@ +" Vim filetype plugin +" Language: Racket +" Maintainer: D. Ben Knoble <ben.knoble+github@gmail.com> +" Previous Maintainer: Will Langstroth <will@langstroth.com> +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 29 + +if exists("b:did_ftplugin") + finish +endif +let b:did_ftplugin = 1 + +let s:cpo_save = &cpo +set cpo&vim + +" quick hack to allow adding values +setlocal iskeyword=@,!,#-',*-:,<-Z,a-z,~,_,94 + +" Enable auto begin new comment line when continuing from an old comment line +setlocal comments=:;;;;,:;;;,:;;,:; +setlocal formatoptions+=r + +"setlocal commentstring=;;%s +setlocal commentstring=#\|\ %s\ \|# + +setlocal formatprg=raco\ fmt + +" Undo our settings when the filetype changes away from Racket +" (this should be amended if settings/mappings are added above!) +let b:undo_ftplugin = + \ "setlocal iskeyword< lispwords< lisp< comments< formatoptions< formatprg<" + \. " | setlocal commentstring<" + +if !exists("no_plugin_maps") && !exists("no_racket_maps") + " Simply setting keywordprg like this works: + " setlocal keywordprg=raco\ docs + " but then vim says: + " "press ENTER or type a command to continue" + " We avoid the annoyance of having to hit enter by remapping K directly. + function s:RacketDoc(word) abort + execute 'silent !raco docs --' shellescape(a:word) + redraw! + endfunction + nnoremap <buffer> <Plug>RacketDoc :call <SID>RacketDoc(expand('<cword>'))<CR> + nmap <buffer> K <Plug>RacketDoc + + " For the visual mode K mapping, it's slightly more convoluted to get the + " selected text: + function! s:Racket_visual_doc() + try + let l:old_a = @a + normal! gv"ay + call system("raco docs '". @a . "'") + redraw! + return @a + finally + let @a = l:old_a + endtry + endfunction + + xnoremap <buffer> <Plug>RacketDoc :call <SID>Racket_visual_doc()<cr> + xmap <buffer> K <Plug>RacketDoc + + let b:undo_ftplugin .= + \ " | silent! execute 'nunmap <buffer> K'" + \. " | silent! execute 'xunmap <buffer> K'" +endif + +if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter") + let b:browsefilter = + \ "Racket Source Files (*.rkt *.rktl)\t*.rkt;*.rktl\n" + \. "All Files (*.*)\t*.*\n" + let b:undo_ftplugin .= " | unlet! b:browsefilter" +endif + +if exists("loaded_matchit") && !exists("b:match_words") + let b:match_words = '#|:|#' + let b:undo_ftplugin .= " | unlet! b:match_words" +endif + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/ftplugin/sh.vim b/runtime/ftplugin/sh.vim index 93a46f63e2..b6fdb8f3e2 100644 --- a/runtime/ftplugin/sh.vim +++ b/runtime/ftplugin/sh.vim @@ -1,12 +1,12 @@ " Vim filetype plugin file -" Language: sh -" -" This runtime file is looking for a new maintainer. -" -" Former maintainer: Dan Sharp -" Last Changed: 20 Jan 2009 - -if exists("b:did_ftplugin") | finish | endif +" Language: sh +" Maintainer: Doug Kearns <dougkearns@gmail.com> +" Previous Maintainer: Dan Sharp +" Last Change: 2022 Sep 07 + +if exists("b:did_ftplugin") + finish +endif let b:did_ftplugin = 1 " Make sure the continuation lines below do not cause problems in @@ -14,28 +14,35 @@ let b:did_ftplugin = 1 let s:save_cpo = &cpo set cpo-=C -setlocal commentstring=#%s +setlocal comments=:# +setlocal commentstring=#\ %s +setlocal formatoptions-=t formatoptions+=croql + +let b:undo_ftplugin = "setl com< cms< fo<" " Shell: thanks to Johannes Zellner -if exists("loaded_matchit") - let s:sol = '\%(;\s*\|^\s*\)\@<=' " start of line - let b:match_words = - \ s:sol.'if\>:' . s:sol.'elif\>:' . s:sol.'else\>:' . s:sol. 'fi\>,' . - \ s:sol.'\%(for\|while\)\>:' . s:sol. 'done\>,' . - \ s:sol.'case\>:' . s:sol. 'esac\>' +if exists("loaded_matchit") && !exists("b:match_words") + let b:match_ignorecase = 0 + let s:sol = '\%(;\s*\|^\s*\)\@<=' " start of line + let b:match_words = + \ s:sol .. 'if\>:' .. s:sol.'elif\>:' .. s:sol.'else\>:' .. s:sol .. 'fi\>,' .. + \ s:sol .. '\%(for\|while\)\>:' .. s:sol .. 'done\>,' .. + \ s:sol .. 'case\>:' .. s:sol .. 'esac\>' + unlet s:sol + let b:undo_ftplugin ..= " | unlet! b:match_ignorecase b:match_words" endif " Change the :browse e filter to primarily show shell-related files. -if has("gui_win32") - let b:browsefilter="Bourne Shell Scripts (*.sh)\t*.sh\n" . - \ "Korn Shell Scripts (*.ksh)\t*.ksh\n" . - \ "Bash Shell Scripts (*.bash)\t*.bash\n" . - \ "All Files (*.*)\t*.*\n" +if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter") + let b:browsefilter = "Bourne Shell Scripts (*.sh)\t*.sh\n" .. + \ "Korn Shell Scripts (*.ksh)\t*.ksh\n" .. + \ "Bash Shell Scripts (*.bash)\t*.bash\n" .. + \ "All Files (*.*)\t*.*\n" + let b:undo_ftplugin ..= " | unlet! b:browsefilter" endif -" Undo the stuff we changed. -let b:undo_ftplugin = "setlocal cms< | unlet! b:browsefilter b:match_words" - " Restore the saved compatibility options. let &cpo = s:save_cpo unlet s:save_cpo + +" vim: nowrap sw=2 sts=2 ts=8 noet: diff --git a/runtime/ftplugin/vdf.vim b/runtime/ftplugin/vdf.vim new file mode 100644 index 0000000000..973d7c0e48 --- /dev/null +++ b/runtime/ftplugin/vdf.vim @@ -0,0 +1,14 @@ +" Vim filetype plugin +" Language: Valve Data Format +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Sep 15 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setl comments=:// commentstring=//\ %s +setl foldmethod=syntax + +let b:undo_ftplugin = 'setl com< cms< fdm<' diff --git a/runtime/ftplugin/vim.vim b/runtime/ftplugin/vim.vim index 772899cb42..82a4b13f9f 100644 --- a/runtime/ftplugin/vim.vim +++ b/runtime/ftplugin/vim.vim @@ -1,7 +1,7 @@ " Vim filetype plugin " Language: Vim " Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2022 Aug 4 +" Last Change: 2022 Sep 09 " Only do this when not done yet for this buffer if exists("b:did_ftplugin") diff --git a/runtime/ftplugin/zimbu.vim b/runtime/ftplugin/zimbu.vim index e365ccf07e..cbe2f55572 100644 --- a/runtime/ftplugin/zimbu.vim +++ b/runtime/ftplugin/zimbu.vim @@ -1,7 +1,7 @@ " Vim filetype plugin file " Language: Zimbu " Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2021 Nov 12 +" Last Change: 2022 Sep 07 " Only do this when not done yet for this buffer if exists("b:did_ftplugin") @@ -28,7 +28,7 @@ endif " Set 'comments' to format dashed lists in comments. " And to keep Zudocu comment characters. -setlocal comments=sO:#\ -,mO:#\ \ ,:#=,:#-,:#%,:# +setlocal comments=sO:#\ -,mO:#\ \ ,exO:#/,s:/*,m:\ ,ex:*/,:#=,:#-,:#%,:# setlocal errorformat^=%f\ line\ %l\ col\ %c:\ %m,ERROR:\ %m diff --git a/runtime/ftplugin/zsh.vim b/runtime/ftplugin/zsh.vim index 34410f1c62..0ca8077305 100644 --- a/runtime/ftplugin/zsh.vim +++ b/runtime/ftplugin/zsh.vim @@ -2,7 +2,7 @@ " Language: Zsh shell script " Maintainer: Christian Brabandt <cb@256bit.org> " Previous Maintainer: Nikolai Weibull <now@bitwi.se> -" Latest Revision: 2020-09-01 +" Latest Revision: 2021-04-03 " License: Vim (see :h license) " Repository: https://github.com/chrisbra/vim-zsh diff --git a/runtime/indent/chatito.vim b/runtime/indent/chatito.vim new file mode 100644 index 0000000000..1ff5e9e3f1 --- /dev/null +++ b/runtime/indent/chatito.vim @@ -0,0 +1,32 @@ +" Vim indent file +" Language: Chatito +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Sep 20 + +if exists('b:did_indent') + finish +endif +let b:did_indent = 1 + +setlocal indentexpr=GetChatitoIndent() +setlocal indentkeys=o,O,*<Return>,0#,!^F + +let b:undo_indent = 'setl inde< indk<' + +if exists('*GetChatitoIndent') + finish +endif + +function GetChatitoIndent() + let l:prev = v:lnum - 1 + if getline(prevnonblank(l:prev)) =~# '^[~%@]\[' + " shift indent after definitions + return shiftwidth() + elseif getline(l:prev) !~# '^\s*$' + " maintain indent in sentences + return indent(l:prev) + else + " reset indent after a blank line + return 0 + end +endfunction diff --git a/runtime/indent/erlang.vim b/runtime/indent/erlang.vim index 4e7bf4ef4d..7aa38587a6 100644 --- a/runtime/indent/erlang.vim +++ b/runtime/indent/erlang.vim @@ -4,7 +4,7 @@ " Contributors: Edwin Fine <efine145_nospam01 at usa dot net> " Pawel 'kTT' Salata <rockplayer.pl@gmail.com> " Ricardo Catalinas Jiménez <jimenezrick@gmail.com> -" Last Update: 2020-Jun-11 +" Last Update: 2022-Sep-06 " License: Vim license " URL: https://github.com/vim-erlang/vim-erlang-runtime @@ -30,7 +30,9 @@ else endif setlocal indentexpr=ErlangIndent() -setlocal indentkeys+=0=end,0=of,0=catch,0=after,0=when,0=),0=],0=},0=>> +setlocal indentkeys+=0=end,0=of,0=catch,0=after,0=else,0=when,0=),0=],0=},0=>> + +let b:undo_indent = "setl inde< indk<" " Only define the functions once if exists("*ErlangIndent") @@ -235,8 +237,8 @@ function! s:GetTokensFromLine(line, string_continuation, atom_continuation, " Two-character tokens elseif i + 1 < linelen && - \ index(['->', '<<', '>>', '||', '==', '/=', '=<', '>=', '++', '--', - \ '::'], + \ index(['->', '<<', '>>', '||', '==', '/=', '=<', '>=', '?=', '++', + \ '--', '::'], \ a:line[i : i + 1]) != -1 call add(indtokens, [a:line[i : i + 1], vcol, i]) let next_i = i + 2 @@ -558,8 +560,8 @@ function! s:IsCatchStandalone(lnum, i) let is_standalone = 0 elseif prev_token =~# '[a-z]' if index(['after', 'and', 'andalso', 'band', 'begin', 'bnot', 'bor', 'bsl', - \ 'bsr', 'bxor', 'case', 'catch', 'div', 'not', 'or', 'orelse', - \ 'rem', 'try', 'xor'], prev_token) != -1 + \ 'bsr', 'bxor', 'case', 'catch', 'div', 'maybe', 'not', 'or', + \ 'orelse', 'rem', 'try', 'xor'], prev_token) != -1 " If catch is after these keywords, it is standalone let is_standalone = 1 else @@ -568,7 +570,7 @@ function! s:IsCatchStandalone(lnum, i) " " Keywords: " - may precede 'catch': end - " - may not precede 'catch': fun if of receive when + " - may not precede 'catch': else fun if of receive when " - unused: cond let query let is_standalone = 0 endif @@ -577,7 +579,7 @@ function! s:IsCatchStandalone(lnum, i) let is_standalone = 0 else " This 'else' branch includes the following tokens: - " -> == /= =< < >= > =:= =/= + - * / ++ -- :: < > ; ( [ { ? = ! . | + " -> == /= =< < >= > ?= =:= =/= + - * / ++ -- :: < > ; ( [ { ? = ! . | let is_standalone = 1 endif @@ -590,6 +592,7 @@ endfunction " Purpose: " This function is called when a begin-type element ('begin', 'case', " '[', '<<', etc.) is found. It asks the caller to return if the stack +" if already empty. " Parameters: " stack: [token] " token: string @@ -758,7 +761,7 @@ endfunction function! s:SearchEndPair(lnum, curr_col) return s:SearchPair( \ a:lnum, a:curr_col, - \ '\C\<\%(case\|try\|begin\|receive\|if\)\>\|' . + \ '\C\<\%(case\|try\|begin\|receive\|if\|maybe\)\>\|' . \ '\<fun\>\%(\s\|\n\|%.*$\|[A-Z_@][a-zA-Z_@]*\)*(', \ '', \ '\<end\>') @@ -847,6 +850,7 @@ function! s:ErlangCalcIndent2(lnum, stack) if ret | return res | endif " case EXPR of BRANCHES end + " if BRANCHES end " try EXPR catch BRANCHES end " try EXPR after BODY end " try EXPR catch BRANCHES after BODY end @@ -855,15 +859,17 @@ function! s:ErlangCalcIndent2(lnum, stack) " try EXPR of BRANCHES catch BRANCHES after BODY end " receive BRANCHES end " receive BRANCHES after BRANCHES end + " maybe EXPR end + " maybe EXPR else BRANCHES end " This branch is not Emacs-compatible - elseif (index(['of', 'receive', 'after', 'if'], token) != -1 || + elseif (index(['of', 'receive', 'after', 'if', 'else'], token) != -1 || \ (token ==# 'catch' && !s:IsCatchStandalone(lnum, i))) && \ !last_token_of_line && \ (empty(stack) || stack ==# ['when'] || stack ==# ['->'] || \ stack ==# ['->', ';']) - " If we are after of/receive, but these are not the last + " If we are after of/receive/etc, but these are not the last " tokens of the line, we want to indent like this: " " % stack == [] @@ -889,21 +895,21 @@ function! s:ErlangCalcIndent2(lnum, stack) " stack = ['when'] => LTI is a guard if empty(stack) || stack == ['->', ';'] call s:Log(' LTI is in a condition after ' . - \'"of/receive/after/if/catch" -> return') + \'"of/receive/after/if/else/catch" -> return') return stored_vcol elseif stack == ['->'] call s:Log(' LTI is in a branch after ' . - \'"of/receive/after/if/catch" -> return') + \'"of/receive/after/if/else/catch" -> return') return stored_vcol + shiftwidth() elseif stack == ['when'] call s:Log(' LTI is in a guard after ' . - \'"of/receive/after/if/catch" -> return') + \'"of/receive/after/if/else/catch" -> return') return stored_vcol + shiftwidth() else return s:UnexpectedToken(token, stack) endif - elseif index(['case', 'if', 'try', 'receive'], token) != -1 + elseif index(['case', 'if', 'try', 'receive', 'maybe'], token) != -1 " stack = [] => LTI is a condition " stack = ['->'] => LTI is a branch @@ -913,45 +919,47 @@ function! s:ErlangCalcIndent2(lnum, stack) " pass elseif (token ==# 'case' && stack[0] ==# 'of') || \ (token ==# 'if') || + \ (token ==# 'maybe' && stack[0] ==# 'else') || \ (token ==# 'try' && (stack[0] ==# 'of' || \ stack[0] ==# 'catch' || \ stack[0] ==# 'after')) || \ (token ==# 'receive') " From the indentation point of view, the keyword - " (of/catch/after/end) before the LTI is what counts, so + " (of/catch/after/else/end) before the LTI is what counts, so " when we reached these tokens, and the stack already had - " a catch/after/end, we didn't modify it. + " a catch/after/else/end, we didn't modify it. " - " This way when we reach case/try/receive (i.e. now), - " there is at most one of/catch/after/end token in the + " This way when we reach case/try/receive/maybe (i.e. now), + " there is at most one of/catch/after/else/end token in the " stack. if token ==# 'case' || token ==# 'try' || - \ (token ==# 'receive' && stack[0] ==# 'after') + \ (token ==# 'receive' && stack[0] ==# 'after') || + \ (token ==# 'maybe' && stack[0] ==# 'else') call s:Pop(stack) endif if empty(stack) call s:Log(' LTI is in a condition; matching ' . - \'"case/if/try/receive" found') + \'"case/if/try/receive/maybe" found') let stored_vcol = curr_vcol + shiftwidth() elseif stack[0] ==# 'align_to_begin_element' call s:Pop(stack) let stored_vcol = curr_vcol elseif len(stack) > 1 && stack[0] ==# '->' && stack[1] ==# ';' call s:Log(' LTI is in a condition; matching ' . - \'"case/if/try/receive" found') + \'"case/if/try/receive/maybe" found') call s:Pop(stack) call s:Pop(stack) let stored_vcol = curr_vcol + shiftwidth() elseif stack[0] ==# '->' call s:Log(' LTI is in a branch; matching ' . - \'"case/if/try/receive" found') + \'"case/if/try/receive/maybe" found') call s:Pop(stack) let stored_vcol = curr_vcol + 2 * shiftwidth() elseif stack[0] ==# 'when' call s:Log(' LTI is in a guard; matching ' . - \'"case/if/try/receive" found') + \'"case/if/try/receive/maybe" found') call s:Pop(stack) let stored_vcol = curr_vcol + 2 * shiftwidth() + 2 endif @@ -1213,7 +1221,7 @@ function! s:ErlangCalcIndent2(lnum, stack) if empty(stack) call s:Push(stack, ';') - elseif index([';', '->', 'when', 'end', 'after', 'catch'], + elseif index([';', '->', 'when', 'end', 'after', 'catch', 'else'], \stack[0]) != -1 " Pass: " @@ -1223,10 +1231,10 @@ function! s:ErlangCalcIndent2(lnum, stack) " should keep that, because they signify the type of the " LTI (branch, condition or guard). " - From the indentation point of view, the keyword - " (of/catch/after/end) before the LTI is what counts, so - " if the stack already has a catch/after/end, we don't - " modify it. This way when we reach case/try/receive, - " there will be at most one of/catch/after/end token in + " (of/catch/after/else/end) before the LTI is what counts, so + " if the stack already has a catch/after/else/end, we don't + " modify it. This way when we reach case/try/receive/maybe, + " there will be at most one of/catch/after/else/end token in " the stack. else return s:UnexpectedToken(token, stack) @@ -1242,7 +1250,8 @@ function! s:ErlangCalcIndent2(lnum, stack) " stack = ['->'] -> LTI is a condition " stack = ['->', ';'] -> LTI is a branch call s:Push(stack, '->') - elseif index(['->', 'when', 'end', 'after', 'catch'], stack[0]) != -1 + elseif index(['->', 'when', 'end', 'after', 'catch', 'else'], + \stack[0]) != -1 " Pass: " " - If the stack top is another '->', then one '->' is @@ -1250,10 +1259,10 @@ function! s:ErlangCalcIndent2(lnum, stack) " - If the stack top is a 'when', then we should keep " that, because this signifies that LTI is a in a guard. " - From the indentation point of view, the keyword - " (of/catch/after/end) before the LTI is what counts, so - " if the stack already has a catch/after/end, we don't - " modify it. This way when we reach case/try/receive, - " there will be at most one of/catch/after/end token in + " (of/catch/after/else/end) before the LTI is what counts, so + " if the stack already has a catch/after/else/end, we don't + " modify it. This way when we reach case/try/receive/maybe, + " there will be at most one of/catch/after/else/end token in " the stack. else return s:UnexpectedToken(token, stack) @@ -1283,7 +1292,8 @@ function! s:ErlangCalcIndent2(lnum, stack) " LTI call s:Push(stack, token) endif - elseif index(['->', 'when', 'end', 'after', 'catch'], stack[0]) != -1 + elseif index(['->', 'when', 'end', 'after', 'catch', 'else'], + \stack[0]) != -1 " Pass: " - If the stack top is another 'when', then one 'when' is " enough. @@ -1291,21 +1301,63 @@ function! s:ErlangCalcIndent2(lnum, stack) " should keep that, because they signify the type of the " LTI (branch, condition or guard). " - From the indentation point of view, the keyword - " (of/catch/after/end) before the LTI is what counts, so - " if the stack already has a catch/after/end, we don't - " modify it. This way when we reach case/try/receive, - " there will be at most one of/catch/after/end token in + " (of/catch/after/else/end) before the LTI is what counts, so + " if the stack already has a catch/after/else/end, we don't + " modify it. This way when we reach case/try/receive/maybe, + " there will be at most one of/catch/after/else/end token in " the stack. else return s:UnexpectedToken(token, stack) endif - elseif token ==# 'of' || token ==# 'after' || + elseif token ==# 'of' || token ==# 'after' || token ==# 'else' || \ (token ==# 'catch' && !s:IsCatchStandalone(lnum, i)) - if token ==# 'after' - " If LTI is between an 'after' and the corresponding - " 'end', then let's return + if token ==# 'after' || token ==# 'else' + " If LTI is between an after/else and the corresponding 'end', then + " let's return because calculating the indentation based on + " after/else is enough. + " + " Example: + " receive A after + " LTI + " maybe A else + " LTI + " + " Note about Emacs compabitility {{{ + " + " It would be fine to indent the examples above the following way: + " + " receive A after + " LTI + " maybe A else + " LTI + " + " We intend it the way above because that is how Emacs does it. + " Also, this is a bit faster. + " + " We are still not 100% Emacs compatible because of placing the + " 'end' after the indented blocks. + " + " Emacs example: + " + " receive A after + " LTI + " end, + " maybe A else + " LTI + " end % Yes, it's here (in OTP 25.0, might change + " % later) + " + " vim-erlang example: + " + " receive A after + " LTI + " end, + " maybe A else + " LTI + " end + " }}} let [ret, res] = s:BeginElementFoundIfEmpty(stack, token, curr_vcol, \stored_vcol, shiftwidth()) if ret | return res | endif @@ -1313,7 +1365,8 @@ function! s:ErlangCalcIndent2(lnum, stack) if empty(stack) || stack[0] ==# '->' || stack[0] ==# 'when' call s:Push(stack, token) - elseif stack[0] ==# 'catch' || stack[0] ==# 'after' || stack[0] ==# 'end' + elseif stack[0] ==# 'catch' || stack[0] ==# 'after' || + \stack[0] ==# 'else' || stack[0] ==# 'end' " Pass: From the indentation point of view, the keyword " (of/catch/after/end) before the LTI is what counts, so " if the stack already has a catch/after/end, we don't @@ -1403,7 +1456,7 @@ function! ErlangIndent() endif let ml = matchlist(currline, - \'^\(\s*\)\(\%(end\|of\|catch\|after\)\>\|[)\]}]\|>>\)') + \'^\(\s*\)\(\%(end\|of\|catch\|after\|else\)\>\|[)\]}]\|>>\)') " If the line has a special beginning, but not a standalone catch if !empty(ml) && !(ml[2] ==# 'catch' && s:IsCatchStandalone(v:lnum, 0)) diff --git a/runtime/indent/gyp.vim b/runtime/indent/gyp.vim new file mode 100644 index 0000000000..c3980ac568 --- /dev/null +++ b/runtime/indent/gyp.vim @@ -0,0 +1,7 @@ +" Vim indent file +" Language: GYP +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Sep 27 + +" JSON indent works well +runtime! indent/json.vim diff --git a/runtime/indent/hare.vim b/runtime/indent/hare.vim new file mode 100644 index 0000000000..bc4fea4e61 --- /dev/null +++ b/runtime/indent/hare.vim @@ -0,0 +1,138 @@ +" Vim indent file +" Language: Hare +" Maintainer: Amelia Clarke <me@rsaihe.dev> +" Last Change: 2022 Sep 22 + +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +if !has("cindent") || !has("eval") + finish +endif + +setlocal cindent + +" L0 -> don't deindent labels +" (s -> use one indent after a trailing ( +" m1 -> if ) starts a line, indent it the same as its matching ( +" ks -> add an extra indent to extra lines in an if expression or for expression +" j1 -> indent code inside {} one level when in parentheses +" J1 -> see j1 +" *0 -> don't search for unclosed block comments +" #1 -> don't deindent lines that begin with # +setlocal cinoptions=L0,(s,m1,ks,j1,J1,*0,#1 + +" Controls which keys reindent the current line. +" 0{ -> { at beginning of line +" 0} -> } at beginning of line +" 0) -> ) at beginning of line +" 0] -> ] at beginning of line +" !^F -> <C-f> (not inserted) +" o -> <CR> or `o` command +" O -> `O` command +" e -> else +" 0=case -> case +setlocal indentkeys=0{,0},0),0],!^F,o,O,e,0=case + +setlocal cinwords=if,else,for,switch,match + +setlocal indentexpr=GetHareIndent() + +function! FloorCindent(lnum) + return cindent(a:lnum) / shiftwidth() * shiftwidth() +endfunction + +function! GetHareIndent() + let line = getline(v:lnum) + let prevlnum = prevnonblank(v:lnum - 1) + let prevline = getline(prevlnum) + let prevprevline = getline(prevnonblank(prevlnum - 1)) + + " This is all very hacky and imperfect, but it's tough to do much better when + " working with regex-based indenting rules. + + " If the previous line ended with =, indent by one shiftwidth. + if prevline =~# '\v\=\s*(//.*)?$' + return indent(prevlnum) + shiftwidth() + endif + + " If the previous line ended in a semicolon and the line before that ended + " with =, deindent by one shiftwidth. + if prevline =~# '\v;\s*(//.*)?$' && prevprevline =~# '\v\=\s*(//.*)?$' + return indent(prevlnum) - shiftwidth() + endif + + " TODO: The following edge-case is still indented incorrectly: + " case => + " if (foo) { + " bar; + " }; + " | // cursor is incorrectly deindented by one shiftwidth. + " + " This only happens if the {} block is the first statement in the case body. + " If `case` is typed, the case will also be incorrectly deindented by one + " shiftwidth. Are you having fun yet? + + " Deindent cases. + if line =~# '\v^\s*case' + " If the previous line was also a case, don't do any special indenting. + if prevline =~# '\v^\s*case' + return indent(prevlnum) + end + + " If the previous line was a multiline case, deindent by one shiftwidth. + if prevline =~# '\v\=\>\s*(//.*)?$' + return indent(prevlnum) - shiftwidth() + endif + + " If the previous line started a block, deindent by one shiftwidth. + " This handles the first case in a switch/match block. + if prevline =~# '\v\{\s*(//.*)?$' + return FloorCindent(v:lnum) - shiftwidth() + end + + " If the previous line ended in a semicolon and the line before that wasn't + " a case, deindent by one shiftwidth. + if prevline =~# '\v;\s*(//.*)?$' && prevprevline !~# '\v\=\>\s*(//.*)?$' + return FloorCindent(v:lnum) - shiftwidth() + end + + let l:indent = FloorCindent(v:lnum) + + " If a normal cindent would indent the same amount as the previous line, + " deindent by one shiftwidth. This fixes some issues with `case let` blocks. + if l:indent == indent(prevlnum) + return l:indent - shiftwidth() + endif + + " Otherwise, do a normal cindent. + return l:indent + endif + + " Don't indent an extra shiftwidth for cases which span multiple lines. + if prevline =~# '\v\=\>\s*(//.*)?$' && prevline !~# '\v^\s*case\W' + return indent(prevlnum) + endif + + " Indent the body of a case. + " If the previous line ended in a semicolon and the line before that was a + " case, don't do any special indenting. + if prevline =~# '\v;\s*(//.*)?$' && prevprevline =~# '\v\=\>\s*(//.*)?$' && line !~# '\v^\s*}' + return indent(prevlnum) + endif + + let l:indent = FloorCindent(v:lnum) + + " If the previous line was a case and a normal cindent wouldn't indent, indent + " an extra shiftwidth. + if prevline =~# '\v\=\>\s*(//.*)?$' && l:indent == indent(prevlnum) + return l:indent + shiftwidth() + endif + + " If everything above is false, do a normal cindent. + return l:indent +endfunction + +" vim: tabstop=2 shiftwidth=2 expandtab diff --git a/runtime/indent/json.vim b/runtime/indent/json.vim index 09c7d7a85a..510f7e8f42 100644 --- a/runtime/indent/json.vim +++ b/runtime/indent/json.vim @@ -3,6 +3,7 @@ " Maintainer: Eli Parra <eli@elzr.com> https://github.com/elzr/vim-json " Last Change: 2020 Aug 30 " https://github.com/jakar/vim-json/commit/20b650e22aa750c4ab6a66aa646bdd95d7cd548a#diff-e81fc111b2052e306d126bd9989f7b7c +" 2022 Sep 07: b:undo_indent added by Doug Kearns " Original Author: Rogerz Zhang <rogerz.zhang at gmail.com> http://github.com/rogerz/vim-json " Acknowledgement: Based off of vim-javascript maintained by Darrick Wiebe " http://www.vim.org/scripts/script.php?script_id=2765 @@ -22,6 +23,8 @@ setlocal nosmartindent setlocal indentexpr=GetJSONIndent(v:lnum) setlocal indentkeys=0{,0},0),0[,0],!^F,o,O,e +let b:undo_indent = "setl inde< indk< si<" + " Only define the function once. if exists("*GetJSONIndent") finish diff --git a/runtime/indent/lua.vim b/runtime/indent/lua.vim index 604cd333c9..0d1f934a03 100644 --- a/runtime/indent/lua.vim +++ b/runtime/indent/lua.vim @@ -3,6 +3,7 @@ " Maintainer: Marcus Aurelius Farias <marcus.cf 'at' bol.com.br> " First Author: Max Ischenko <mfi 'at' ukr.net> " Last Change: 2017 Jun 13 +" 2022 Sep 07: b:undo_indent added by Doug Kearns " Only load this indent file when no other was loaded. if exists("b:did_indent") @@ -18,6 +19,8 @@ setlocal indentkeys+=0=end,0=until setlocal autoindent +let b:undo_indent = "setlocal autoindent< indentexpr< indentkeys<" + " Only define the function once. if exists("*GetLuaIndent") finish diff --git a/runtime/indent/racket.vim b/runtime/indent/racket.vim new file mode 100644 index 0000000000..93bd38fbff --- /dev/null +++ b/runtime/indent/racket.vim @@ -0,0 +1,60 @@ +" Vim indent file +" Language: Racket +" Maintainer: D. Ben Knoble <ben.knoble+github@gmail.com> +" Previous Maintainer: Will Langstroth <will@langstroth.com> +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +setlocal lisp autoindent nosmartindent + +setlocal lispwords+=module,module*,module+,parameterize,let-values,let*-values,letrec-values,local +setlocal lispwords+=define/contract +setlocal lispwords+=λ +setlocal lispwords+=with-handlers +setlocal lispwords+=define-values,opt-lambda,case-lambda,syntax-rules,with-syntax,syntax-case,syntax-parse +setlocal lispwords+=define-for-syntax,define-syntax-parser,define-syntax-parse-rule,define-syntax-class,define-splicing-syntax-class +setlocal lispwords+=define-signature,unit,unit/sig,compund-unit/sig,define-values/invoke-unit/sig +setlocal lispwords+=define-opt/c,define-syntax-rule +setlocal lispwords+=define-test-suite +setlocal lispwords+=struct +setlocal lispwords+=with-input-from-file,with-output-to-file + +" Racket OOP +" TODO missing a lot of define-like forms here (e.g., define/augment, etc.) +setlocal lispwords+=class,class*,mixin,interface,class/derived +setlocal lispwords+=define/public,define/pubment,define/public-final +setlocal lispwords+=define/override,define/overment,define/override-final +setlocal lispwords+=define/augment,define/augride,define/augment-final +setlocal lispwords+=define/private + +" kanren +setlocal lispwords+=fresh,run,run*,project,conde,condu + +" loops +setlocal lispwords+=for,for/list,for/fold,for*,for*/list,for*/fold,for/or,for/and,for*/or,for*/and +setlocal lispwords+=for/hash,for/hasheq,for/hasheqv,for/sum,for/flvector,for*/flvector,for/vector,for*/vector,for*/sum,for*/hash,for*/hasheq,for*/hasheqv +setlocal lispwords+=for/async +setlocal lispwords+=for/set,for*/set +setlocal lispwords+=for/first,for*/first + +setlocal lispwords+=match,match*,match/values,define/match,match-lambda,match-lambda*,match-lambda** +setlocal lispwords+=match-let,match-let*,match-let-values,match-let*-values +setlocal lispwords+=match-letrec,match-define,match-define-values + +setlocal lispwords+=let/cc,let/ec + +" qi +setlocal lispwords+=define-flow,define-switch,flow-lambda,switch-lambda,on,switch,Ï€,λ01 +setlocal lispwords+=define-qi-syntax,define-qi-syntax-parser,define-qi-syntax-rule + +" gui-easy +setlocal lispwords+=if-view,case-view,cond-view,list-view,dyn-view +setlocal lispwords+=case/dep +setlocal lispwords+=define/obs + +let b:undo_indent = "setlocal lisp< ai< si< lw<" diff --git a/runtime/indent/solidity.vim b/runtime/indent/solidity.vim new file mode 100644 index 0000000000..caed726c0a --- /dev/null +++ b/runtime/indent/solidity.vim @@ -0,0 +1,442 @@ +" Vim indent file +" Language: Solidity +" Acknowledgement: Based off of vim-javascript +" Maintainer: Cothi (jiungdev@gmail.com) +" Original Author: tomlion (https://github.com/tomlion/vim-solidity) +" Last Changed: 2022 Sep 27 +" +" 0. Initialization {{{1 +" ================= + +" Only load this indent file when no other was loaded. +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +setlocal nosmartindent + +" Now, set up our indentation expression and keys that trigger it. +setlocal indentexpr=GetSolidityIndent() +setlocal indentkeys=0{,0},0),0],0\,,!^F,o,O,e + +" Only define the function once. +if exists("*GetSolidityIndent") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +" 1. Variables {{{1 +" ============ + +let s:js_keywords = '^\s*\(break\|case\|catch\|continue\|debugger\|default\|delete\|do\|else\|finally\|for\|function\|if\|in\|instanceof\|new\|return\|switch\|this\|throw\|try\|typeof\|var\|void\|while\|with\)' + +" Regex of syntax group names that are or delimit string or are comments. +let s:syng_strcom = 'string\|regex\|comment\c' + +" Regex of syntax group names that are strings. +let s:syng_string = 'regex\c' + +" Regex of syntax group names that are strings or documentation. +let s:syng_multiline = 'comment\c' + +" Regex of syntax group names that are line comment. +let s:syng_linecom = 'linecomment\c' + +" Expression used to check whether we should skip a match with searchpair(). +let s:skip_expr = "synIDattr(synID(line('.'),col('.'),1),'name') =~ '".s:syng_strcom."'" + +let s:line_term = '\s*\%(\%(\/\/\).*\)\=$' + +" Regex that defines continuation lines, not including (, {, or [. +let s:continuation_regex = '\%([\\*+/.:]\|\%(<%\)\@<![=-]\|\W[|&?]\|||\|&&\)' . s:line_term + +" Regex that defines continuation lines. +" TODO: this needs to deal with if ...: and so on +let s:msl_regex = '\%([\\*+/.:([]\|\%(<%\)\@<![=-]\|\W[|&?]\|||\|&&\)' . s:line_term + +let s:one_line_scope_regex = '\<\%(if\|else\|for\|while\)\>[^{;]*' . s:line_term + +" Regex that defines blocks. +let s:block_regex = '\%([{[]\)\s*\%(|\%([*@]\=\h\w*,\=\s*\)\%(,\s*[*@]\=\h\w*\)*|\)\=' . s:line_term + +let s:var_stmt = '^\s*var' + +let s:comma_first = '^\s*,' +let s:comma_last = ',\s*$' + +let s:ternary = '^\s\+[?|:]' +let s:ternary_q = '^\s\+?' + +" 2. Auxiliary Functions {{{1 +" ====================== + +" Check if the character at lnum:col is inside a string, comment, or is ascii. +function s:IsInStringOrComment(lnum, col) + return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_strcom +endfunction + +" Check if the character at lnum:col is inside a string. +function s:IsInString(lnum, col) + return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_string +endfunction + +" Check if the character at lnum:col is inside a multi-line comment. +function s:IsInMultilineComment(lnum, col) + return !s:IsLineComment(a:lnum, a:col) && synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_multiline +endfunction + +" Check if the character at lnum:col is a line comment. +function s:IsLineComment(lnum, col) + return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_linecom +endfunction + +" Find line above 'lnum' that isn't empty, in a comment, or in a string. +function s:PrevNonBlankNonString(lnum) + let in_block = 0 + let lnum = prevnonblank(a:lnum) + while lnum > 0 + " Go in and out of blocks comments as necessary. + " If the line isn't empty (with opt. comment) or in a string, end search. + let line = getline(lnum) + if line =~ '/\*' + if in_block + let in_block = 0 + else + break + endif + elseif !in_block && line =~ '\*/' + let in_block = 1 + elseif !in_block && line !~ '^\s*\%(//\).*$' && !(s:IsInStringOrComment(lnum, 1) && s:IsInStringOrComment(lnum, strlen(line))) + break + endif + let lnum = prevnonblank(lnum - 1) + endwhile + return lnum +endfunction + +" Find line above 'lnum' that started the continuation 'lnum' may be part of. +function s:GetMSL(lnum, in_one_line_scope) + " Start on the line we're at and use its indent. + let msl = a:lnum + let lnum = s:PrevNonBlankNonString(a:lnum - 1) + while lnum > 0 + " If we have a continuation line, or we're in a string, use line as MSL. + " Otherwise, terminate search as we have found our MSL already. + let line = getline(lnum) + let col = match(line, s:msl_regex) + 1 + if (col > 0 && !s:IsInStringOrComment(lnum, col)) || s:IsInString(lnum, strlen(line)) + let msl = lnum + else + " Don't use lines that are part of a one line scope as msl unless the + " flag in_one_line_scope is set to 1 + " + if a:in_one_line_scope + break + end + let msl_one_line = s:Match(lnum, s:one_line_scope_regex) + if msl_one_line == 0 + break + endif + endif + let lnum = s:PrevNonBlankNonString(lnum - 1) + endwhile + return msl +endfunction + +function s:RemoveTrailingComments(content) + let single = '\/\/\(.*\)\s*$' + let multi = '\/\*\(.*\)\*\/\s*$' + return substitute(substitute(a:content, single, '', ''), multi, '', '') +endfunction + +" Find if the string is inside var statement (but not the first string) +function s:InMultiVarStatement(lnum) + let lnum = s:PrevNonBlankNonString(a:lnum - 1) + +" let type = synIDattr(synID(lnum, indent(lnum) + 1, 0), 'name') + + " loop through previous expressions to find a var statement + while lnum > 0 + let line = getline(lnum) + + " if the line is a js keyword + if (line =~ s:js_keywords) + " check if the line is a var stmt + " if the line has a comma first or comma last then we can assume that we + " are in a multiple var statement + if (line =~ s:var_stmt) + return lnum + endif + + " other js keywords, not a var + return 0 + endif + + let lnum = s:PrevNonBlankNonString(lnum - 1) + endwhile + + " beginning of program, not a var + return 0 +endfunction + +" Find line above with beginning of the var statement or returns 0 if it's not +" this statement +function s:GetVarIndent(lnum) + let lvar = s:InMultiVarStatement(a:lnum) + let prev_lnum = s:PrevNonBlankNonString(a:lnum - 1) + + if lvar + let line = s:RemoveTrailingComments(getline(prev_lnum)) + + " if the previous line doesn't end in a comma, return to regular indent + if (line !~ s:comma_last) + return indent(prev_lnum) - &sw + else + return indent(lvar) + &sw + endif + endif + + return -1 +endfunction + + +" Check if line 'lnum' has more opening brackets than closing ones. +function s:LineHasOpeningBrackets(lnum) + let open_0 = 0 + let open_2 = 0 + let open_4 = 0 + let line = getline(a:lnum) + let pos = match(line, '[][(){}]', 0) + while pos != -1 + if !s:IsInStringOrComment(a:lnum, pos + 1) + let idx = stridx('(){}[]', line[pos]) + if idx % 2 == 0 + let open_{idx} = open_{idx} + 1 + else + let open_{idx - 1} = open_{idx - 1} - 1 + endif + endif + let pos = match(line, '[][(){}]', pos + 1) + endwhile + return (open_0 > 0) . (open_2 > 0) . (open_4 > 0) +endfunction + +function s:Match(lnum, regex) + let col = match(getline(a:lnum), a:regex) + 1 + return col > 0 && !s:IsInStringOrComment(a:lnum, col) ? col : 0 +endfunction + +function s:IndentWithContinuation(lnum, ind, width) + " Set up variables to use and search for MSL to the previous line. + let p_lnum = a:lnum + let lnum = s:GetMSL(a:lnum, 1) + let line = getline(lnum) + + " If the previous line wasn't a MSL and is continuation return its indent. + " TODO: the || s:IsInString() thing worries me a bit. + if p_lnum != lnum + if s:Match(p_lnum,s:continuation_regex)||s:IsInString(p_lnum,strlen(line)) + return a:ind + endif + endif + + " Set up more variables now that we know we aren't continuation bound. + let msl_ind = indent(lnum) + + " If the previous line ended with [*+/.-=], start a continuation that + " indents an extra level. + if s:Match(lnum, s:continuation_regex) + if lnum == p_lnum + return msl_ind + a:width + else + return msl_ind + endif + endif + + return a:ind +endfunction + +function s:InOneLineScope(lnum) + let msl = s:GetMSL(a:lnum, 1) + if msl > 0 && s:Match(msl, s:one_line_scope_regex) + return msl + endif + return 0 +endfunction + +function s:ExitingOneLineScope(lnum) + let msl = s:GetMSL(a:lnum, 1) + if msl > 0 + " if the current line is in a one line scope .. + if s:Match(msl, s:one_line_scope_regex) + return 0 + else + let prev_msl = s:GetMSL(msl - 1, 1) + if s:Match(prev_msl, s:one_line_scope_regex) + return prev_msl + endif + endif + endif + return 0 +endfunction + +" 3. GetSolidityIndent Function {{{1 +" ========================= + +function GetSolidityIndent() + " 3.1. Setup {{{2 + " ---------- + + " Set up variables for restoring position in file. Could use v:lnum here. + let vcol = col('.') + + " 3.2. Work on the current line {{{2 + " ----------------------------- + + let ind = -1 + " Get the current line. + let line = getline(v:lnum) + " previous nonblank line number + let prevline = prevnonblank(v:lnum - 1) + + " If we got a closing bracket on an empty line, find its match and indent + " according to it. For parentheses we indent to its column - 1, for the + " others we indent to the containing line's MSL's level. Return -1 if fail. + let col = matchend(line, '^\s*[],})]') + if col > 0 && !s:IsInStringOrComment(v:lnum, col) + call cursor(v:lnum, col) + + let lvar = s:InMultiVarStatement(v:lnum) + if lvar + let prevline_contents = s:RemoveTrailingComments(getline(prevline)) + + " check for comma first + if (line[col - 1] =~ ',') + " if the previous line ends in comma or semicolon don't indent + if (prevline_contents =~ '[;,]\s*$') + return indent(s:GetMSL(line('.'), 0)) + " get previous line indent, if it's comma first return prevline indent + elseif (prevline_contents =~ s:comma_first) + return indent(prevline) + " otherwise we indent 1 level + else + return indent(lvar) + &sw + endif + endif + endif + + + let bs = strpart('(){}[]', stridx(')}]', line[col - 1]) * 2, 2) + if searchpair(escape(bs[0], '\['), '', bs[1], 'bW', s:skip_expr) > 0 + if line[col-1]==')' && col('.') != col('$') - 1 + let ind = virtcol('.')-1 + else + let ind = indent(s:GetMSL(line('.'), 0)) + endif + endif + return ind + endif + + " If the line is comma first, dedent 1 level + if (getline(prevline) =~ s:comma_first) + return indent(prevline) - &sw + endif + + if (line =~ s:ternary) + if (getline(prevline) =~ s:ternary_q) + return indent(prevline) + else + return indent(prevline) + &sw + endif + endif + + " If we are in a multi-line comment, cindent does the right thing. + if s:IsInMultilineComment(v:lnum, 1) && !s:IsLineComment(v:lnum, 1) + return cindent(v:lnum) + endif + + " Check for multiple var assignments +" let var_indent = s:GetVarIndent(v:lnum) +" if var_indent >= 0 +" return var_indent +" endif + + " 3.3. Work on the previous line. {{{2 + " ------------------------------- + + " If the line is empty and the previous nonblank line was a multi-line + " comment, use that comment's indent. Deduct one char to account for the + " space in ' */'. + if line =~ '^\s*$' && s:IsInMultilineComment(prevline, 1) + return indent(prevline) - 1 + endif + + " Find a non-blank, non-multi-line string line above the current line. + let lnum = s:PrevNonBlankNonString(v:lnum - 1) + + " If the line is empty and inside a string, use the previous line. + if line =~ '^\s*$' && lnum != prevline + return indent(prevnonblank(v:lnum)) + endif + + " At the start of the file use zero indent. + if lnum == 0 + return 0 + endif + + " Set up variables for current line. + let line = getline(lnum) + let ind = indent(lnum) + + " If the previous line ended with a block opening, add a level of indent. + if s:Match(lnum, s:block_regex) + return indent(s:GetMSL(lnum, 0)) + &sw + endif + + " If the previous line contained an opening bracket, and we are still in it, + " add indent depending on the bracket type. + if line =~ '[[({]' + let counts = s:LineHasOpeningBrackets(lnum) + if counts[0] == '1' && searchpair('(', '', ')', 'bW', s:skip_expr) > 0 + if col('.') + 1 == col('$') + return ind + &sw + else + return virtcol('.') + endif + elseif counts[1] == '1' || counts[2] == '1' + return ind + &sw + else + call cursor(v:lnum, vcol) + end + endif + + " 3.4. Work on the MSL line. {{{2 + " -------------------------- + + let ind_con = ind + let ind = s:IndentWithContinuation(lnum, ind_con, &sw) + + " }}}2 + " + " + let ols = s:InOneLineScope(lnum) + if ols > 0 + let ind = ind + &sw + else + let ols = s:ExitingOneLineScope(lnum) + while ols > 0 && ind > 0 + let ind = ind - &sw + let ols = s:InOneLineScope(ols - 1) + endwhile + endif + + return ind +endfunction + +" }}}1 + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/indent/testdir/python.in b/runtime/indent/testdir/python.in index e6f05f22bc..57719ee430 100644 --- a/runtime/indent/testdir/python.in +++ b/runtime/indent/testdir/python.in @@ -1,6 +1,24 @@ # vim: set ft=python sw=4 et: # START_INDENT +dict = { +'a': 1, +'b': 2, +'c': 3, +} +# END_INDENT + +# START_INDENT +# INDENT_EXE let [g:python_indent.open_paren, g:python_indent.closed_paren_align_last_line] = ['shiftwidth()', v:false] +dict = { +'a': 1, +'b': 2, +'c': 3, +} +# END_INDENT + +# START_INDENT +# INDENT_EXE let g:python_indent.open_paren = 'shiftwidth() * 2' # INDENT_EXE syntax match pythonFoldMarkers /{{{\d*/ contained containedin=pythonComment # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx {{{1 diff --git a/runtime/indent/testdir/python.ok b/runtime/indent/testdir/python.ok index df3de8f186..f5ebbc2285 100644 --- a/runtime/indent/testdir/python.ok +++ b/runtime/indent/testdir/python.ok @@ -1,6 +1,24 @@ # vim: set ft=python sw=4 et: # START_INDENT +dict = { + 'a': 1, + 'b': 2, + 'c': 3, + } +# END_INDENT + +# START_INDENT +# INDENT_EXE let [g:python_indent.open_paren, g:python_indent.closed_paren_align_last_line] = ['shiftwidth()', v:false] +dict = { + 'a': 1, + 'b': 2, + 'c': 3, +} +# END_INDENT + +# START_INDENT +# INDENT_EXE let g:python_indent.open_paren = 'shiftwidth() * 2' # INDENT_EXE syntax match pythonFoldMarkers /{{{\d*/ contained containedin=pythonComment # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx {{{1 diff --git a/runtime/indent/testdir/runtest.vim b/runtime/indent/testdir/runtest.vim index 6bbd33cacd..fa4e16e381 100644 --- a/runtime/indent/testdir/runtest.vim +++ b/runtime/indent/testdir/runtest.vim @@ -11,6 +11,7 @@ syn on set nowrapscan set report=9999 set modeline +set debug=throw au! SwapExists * call HandleSwapExists() func HandleSwapExists() @@ -84,7 +85,12 @@ for fname in glob('testdir/*.in', 1, 1) exe start + 1 if pattern == '' - exe 'normal =' . (end - 1) . 'G' + try + exe 'normal =' . (end - 1) . 'G' + catch + call append(indent_at, 'ERROR: ' . v:exception) + let failed = 1 + endtry else let lnum = search(pattern) if lnum <= 0 @@ -99,7 +105,12 @@ for fname in glob('testdir/*.in', 1, 1) else exe lnum - 1 endif - normal == + try + normal == + catch + call append(indent_at, 'ERROR: ' . v:exception) + let failed = 1 + endtry endif endif endwhile diff --git a/runtime/indent/testdir/vim.in b/runtime/indent/testdir/vim.in index 873045bc2c..5eb262f50a 100644 --- a/runtime/indent/testdir/vim.in +++ b/runtime/indent/testdir/vim.in @@ -36,6 +36,13 @@ let t = [ \ }, \ ] +def Func() + var d = dd + ->extend({ + }) + eval 0 +enddef + " END_INDENT " START_INDENT diff --git a/runtime/indent/testdir/vim.ok b/runtime/indent/testdir/vim.ok index 8e70abe619..932eebef43 100644 --- a/runtime/indent/testdir/vim.ok +++ b/runtime/indent/testdir/vim.ok @@ -36,6 +36,13 @@ let t = [ \ }, \ ] +def Func() + var d = dd + ->extend({ + }) + eval 0 +enddef + " END_INDENT " START_INDENT diff --git a/runtime/indent/vim.vim b/runtime/indent/vim.vim index 8076b2df07..3beb70d255 100644 --- a/runtime/indent/vim.vim +++ b/runtime/indent/vim.vim @@ -33,7 +33,9 @@ function GetVimIndent() endtry endfunc -let s:lineContPat = '^\s*\(\\\|"\\ \)' +" Legacy script line continuation and Vim9 script operators that must mean an +" expression that continues from the previous line. +let s:lineContPat = '^\s*\(\\\|"\\ \|->\)' function GetVimIndentIntern() " If the current line has line continuation and the previous one too, use @@ -133,15 +135,15 @@ function GetVimIndentIntern() endif endif - " For a line starting with "}" find the matching "{". If it is at the start - " of the line align with it, probably end of a block. + " For a line starting with "}" find the matching "{". Align with that line, + " it is either the matching block start or dictionary start. " Use the mapped "%" from matchit to find the match, otherwise we may match " a { inside a comment or string. if cur_text =~ '^\s*}' if maparg('%') != '' exe v:lnum silent! normal % - if line('.') < v:lnum && getline('.') =~ '^\s*{' + if line('.') < v:lnum let ind = indent('.') endif else @@ -149,19 +151,33 @@ function GetVimIndentIntern() endif endif - " Below a line starting with "}" find the matching "{". If it is at the - " end of the line we must be below the end of a dictionary. - if prev_text =~ '^\s*}' - if maparg('%') != '' - exe lnum - silent! normal % - if line('.') == lnum || getline('.') !~ '^\s*{' - let ind = ind - shiftwidth() + " Look back for a line to align with + while lnum > 1 + " Below a line starting with "}" find the matching "{". + if prev_text =~ '^\s*}' + if maparg('%') != '' + exe lnum + silent! normal % + if line('.') < lnum + let lnum = line('.') + let ind = indent(lnum) + let prev_text = getline(lnum) + else + break + endif + else + " todo: use searchpair() to find a match + break endif + elseif prev_text =~ s:lineContPat + " looks like a continuation like, go back one line + let lnum = lnum - 1 + let ind = indent(lnum) + let prev_text = getline(lnum) else - " todo: use searchpair() to find a match + break endif - endif + endwhile " Below a line starting with "]" we must be below the end of a list. " Include a "}" and "},} in case a dictionary ends too. diff --git a/runtime/indent/vue.vim b/runtime/indent/vue.vim new file mode 100644 index 0000000000..7ff623b3d1 --- /dev/null +++ b/runtime/indent/vue.vim @@ -0,0 +1,12 @@ +" Vim indent file placeholder +" Language: Vue +" Maintainer: None, please volunteer if you have a real Vue indent script + +" Only load this indent file when no other was loaded. +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +" Html comes closest +runtime! indent/html.vim diff --git a/runtime/indent/yaml.vim b/runtime/indent/yaml.vim index d732c37c05..93fd8ea6f6 100644 --- a/runtime/indent/yaml.vim +++ b/runtime/indent/yaml.vim @@ -1,7 +1,7 @@ " Vim indent file " Language: YAML " Maintainer: Nikolai Pavlov <zyx.vim@gmail.com> -" Last Update: Lukas Reineke +" Last Updates: Lukas Reineke, "lacygoill" " Last Change: 2022 Jun 17 " Only load this indent file when no other was loaded. @@ -29,8 +29,8 @@ function s:FindPrevLessIndentedLine(lnum, ...) let prevlnum = prevnonblank(a:lnum-1) let curindent = a:0 ? a:1 : indent(a:lnum) while prevlnum - \&& indent(prevlnum) >= curindent - \&& getline(prevlnum) !~# '^\s*#' + \ && indent(prevlnum) >= curindent + \ && getline(prevlnum) !~# '^\s*#' let prevlnum = prevnonblank(prevlnum-1) endwhile return prevlnum @@ -54,7 +54,7 @@ let s:c_ns_anchor_name = s:c_ns_anchor_char .. '+' let s:c_ns_anchor_property = '\v\&' .. s:c_ns_anchor_name let s:ns_word_char = '\v[[:alnum:]_\-]' -let s:ns_tag_char = '\v%(%\x\x|' .. s:ns_word_char .. '|[#/;?:@&=+$.~*''()])' +let s:ns_tag_char = '\v%(\x\x|' .. s:ns_word_char .. '|[#/;?:@&=+$.~*''()])' let s:c_named_tag_handle = '\v\!' .. s:ns_word_char .. '+\!' let s:c_secondary_tag_handle = '\v\!\!' let s:c_primary_tag_handle = '\v\!' @@ -63,7 +63,7 @@ let s:c_tag_handle = '\v%(' .. s:c_named_tag_handle. \ '|' .. s:c_primary_tag_handle .. ')' let s:c_ns_shorthand_tag = '\v' .. s:c_tag_handle .. s:ns_tag_char .. '+' let s:c_non_specific_tag = '\v\!' -let s:ns_uri_char = '\v%(%\x\x|' .. s:ns_word_char .. '\v|[#/;?:@&=+$,.!~*''()[\]])' +let s:ns_uri_char = '\v%(\x\x|' .. s:ns_word_char .. '\v|[#/;?:@&=+$,.!~*''()[\]])' let s:c_verbatim_tag = '\v\!\<' .. s:ns_uri_char.. '+\>' let s:c_ns_tag_property = '\v' .. s:c_verbatim_tag. \ '\v|' .. s:c_ns_shorthand_tag. diff --git a/runtime/lua/man.lua b/runtime/lua/man.lua index 5da3d2a92f..6477786dbb 100644 --- a/runtime/lua/man.lua +++ b/runtime/lua/man.lua @@ -1,7 +1,77 @@ -require('vim.compat') +local api, fn = vim.api, vim.fn +local FIND_ARG = '-w' +local localfile_arg = true -- Always use -l if possible. #6683 local buf_hls = {} +local M = {} + +local function man_error(msg) + M.errormsg = 'man.lua: ' .. vim.inspect(msg) + error(M.errormsg) +end + +-- Run a system command and timeout after 30 seconds. +local function system(cmd, silent, env) + local stdout_data = {} + local stderr_data = {} + local stdout = vim.loop.new_pipe(false) + local stderr = vim.loop.new_pipe(false) + + local done = false + local exit_code + + local handle + handle = vim.loop.spawn(cmd[1], { + args = vim.list_slice(cmd, 2), + stdio = { nil, stdout, stderr }, + env = env, + }, function(code) + exit_code = code + stdout:close() + stderr:close() + handle:close() + done = true + end) + + if handle then + stdout:read_start(function(_, data) + stdout_data[#stdout_data + 1] = data + end) + stderr:read_start(function(_, data) + stderr_data[#stderr_data + 1] = data + end) + else + stdout:close() + stderr:close() + if not silent then + local cmd_str = table.concat(cmd, ' ') + man_error(string.format('command error: %s', cmd_str)) + end + end + + vim.wait(30000, function() + return done + end) + + if not done then + if handle then + handle:close() + stdout:close() + stderr:close() + end + local cmd_str = table.concat(cmd, ' ') + man_error(string.format('command timed out: %s', cmd_str)) + end + + if exit_code ~= 0 and not silent then + local cmd_str = table.concat(cmd, ' ') + man_error(string.format("command error '%s': %s", cmd_str, table.concat(stderr_data))) + end + + return table.concat(stdout_data) +end + local function highlight_line(line, linenr) local chars = {} local prev_char = '' @@ -152,21 +222,542 @@ local function highlight_line(line, linenr) end local function highlight_man_page() - local mod = vim.api.nvim_buf_get_option(0, 'modifiable') - vim.api.nvim_buf_set_option(0, 'modifiable', true) + local mod = vim.bo.modifiable + vim.bo.modifiable = true - local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false) + local lines = api.nvim_buf_get_lines(0, 0, -1, false) for i, line in ipairs(lines) do lines[i] = highlight_line(line, i) end - vim.api.nvim_buf_set_lines(0, 0, -1, false, lines) + api.nvim_buf_set_lines(0, 0, -1, false, lines) for _, args in ipairs(buf_hls) do - vim.api.nvim_buf_add_highlight(unpack(args)) + api.nvim_buf_add_highlight(unpack(args)) end buf_hls = {} - vim.api.nvim_buf_set_option(0, 'modifiable', mod) + vim.bo.modifiable = mod +end + +-- replace spaces in a man page name with underscores +-- intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)'; +-- while editing SQL source code, it's nice to visually select 'CREATE TABLE' +-- and hit 'K', which requires this transformation +local function spaces_to_underscores(str) + local res = str:gsub('%s', '_') + return res +end + +local function get_path(sect, name, silent) + name = name or '' + sect = sect or '' + -- Some man implementations (OpenBSD) return all available paths from the + -- search command. Previously, this function would simply select the first one. + -- + -- However, some searches will report matches that are incorrect: + -- man -w strlen may return string.3 followed by strlen.3, and therefore + -- selecting the first would get us the wrong page. Thus, we must find the + -- first matching one. + -- + -- There's yet another special case here. Consider the following: + -- If you run man -w strlen and string.3 comes up first, this is a problem. We + -- should search for a matching named one in the results list. + -- However, if you search for man -w clock_gettime, you will *only* get + -- clock_getres.2, which is the right page. Searching the resuls for + -- clock_gettime will no longer work. In this case, we should just use the + -- first one that was found in the correct section. + -- + -- Finally, we can avoid relying on -S or -s here since they are very + -- inconsistently supported. Instead, call -w with a section and a name. + local cmd + if sect == '' then + cmd = { 'man', FIND_ARG, name } + else + cmd = { 'man', FIND_ARG, sect, name } + end + + local lines = system(cmd, silent) + local results = vim.split(lines or {}, '\n', { trimempty = true }) + + if #results == 0 then + return + end + + -- find any that match the specified name + local namematches = vim.tbl_filter(function(v) + return fn.fnamemodify(v, ':t'):match(name) + end, results) or {} + local sectmatches = {} + + if #namematches > 0 and sect ~= '' then + sectmatches = vim.tbl_filter(function(v) + return fn.fnamemodify(v, ':e') == sect + end, namematches) + end + + return fn.substitute(sectmatches[1] or namematches[1] or results[1], [[\n\+$]], '', '') +end + +local function matchstr(text, pat_or_re) + local re = type(pat_or_re) == 'string' and vim.regex(pat_or_re) or pat_or_re + + local s, e = re:match_str(text) + + if s == nil then + return + end + + return text:sub(vim.str_utfindex(text, s) + 1, vim.str_utfindex(text, e)) +end + +-- attempt to extract the name and sect out of 'name(sect)' +-- otherwise just return the largest string of valid characters in ref +local function extract_sect_and_name_ref(ref) + ref = ref or '' + if ref:sub(1, 1) == '-' then -- try ':Man -pandoc' with this disabled. + man_error("manpage name cannot start with '-'") + end + local ref1 = ref:match('[^()]+%([^()]+%)') + if not ref1 then + local name = ref:match('[^()]+') + if not name then + man_error('manpage reference cannot contain only parentheses: ' .. ref) + end + return '', spaces_to_underscores(name) + end + local parts = vim.split(ref1, '(', { plain = true }) + -- see ':Man 3X curses' on why tolower. + -- TODO(nhooyr) Not sure if this is portable across OSs + -- but I have not seen a single uppercase section. + local sect = vim.split(parts[2] or '', ')', { plain = true })[1]:lower() + local name = spaces_to_underscores(parts[1]) + return sect, name +end + +-- verify_exists attempts to find the path to a manpage +-- based on the passed section and name. +-- +-- 1. If manpage could not be found with the given sect and name, +-- then try all the sections in b:man_default_sects. +-- 2. If it still could not be found, then we try again without a section. +-- 3. If still not found but $MANSECT is set, then we try again with $MANSECT +-- unset. +local function verify_exists(sect, name, silent) + if sect and sect ~= '' then + local ret = get_path(sect, name, true) + if ret then + return ret + end + end + + if vim.b.man_default_sects ~= nil then + local sects = vim.split(vim.b.man_default_sects, ',', { plain = true, trimempty = true }) + for _, sec in ipairs(sects) do + local ret = get_path(sec, name, true) + if ret then + return ret + end + end + end + + -- if none of the above worked, we will try with no section + local res_empty_sect = get_path('', name, true) + if res_empty_sect then + return res_empty_sect + end + + -- if that still didn't work, we will check for $MANSECT and try again with it + -- unset + if vim.env.MANSECT then + local mansect = vim.env.MANSECT + vim.env.MANSECT = nil + local res = get_path('', name, true) + vim.env.MANSECT = mansect + if res then + return res + end + end + + if not silent then + -- finally, if that didn't work, there is no hope + man_error('no manual entry for ' .. name) + end +end + +local EXT_RE = vim.regex([[\.\%([glx]z\|bz2\|lzma\|Z\)$]]) + +-- Extracts the name/section from the 'path/name.sect', because sometimes the actual section is +-- more specific than what we provided to `man` (try `:Man 3 App::CLI`). +-- Also on linux, name seems to be case-insensitive. So for `:Man PRIntf`, we +-- still want the name of the buffer to be 'printf'. +local function extract_sect_and_name_path(path) + local tail = fn.fnamemodify(path, ':t') + if EXT_RE:match_str(path) then -- valid extensions + tail = fn.fnamemodify(tail, ':r') + end + local name, sect = tail:match('^(.+)%.([^.]+)$') + return sect, name +end + +local function find_man() + local win = 1 + while win <= fn.winnr('$') do + local buf = fn.winbufnr(win) + if vim.bo[buf].filetype == 'man' then + vim.cmd(win .. 'wincmd w') + return true + end + win = win + 1 + end + return false +end + +local function set_options(pager) + vim.bo.swapfile = false + vim.bo.buftype = 'nofile' + vim.bo.bufhidden = 'hide' + vim.bo.modified = false + vim.bo.readonly = true + vim.bo.modifiable = false + vim.b.pager = pager + vim.bo.filetype = 'man' +end + +local function get_page(path, silent) + -- Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065). + -- Soft-wrap: ftplugin/man.lua sets wrap/breakindent/…. + -- Hard-wrap: driven by `man`. + local manwidth + if (vim.g.man_hardwrap or 1) ~= 1 then + manwidth = 999 + elseif vim.env.MANWIDTH then + manwidth = vim.env.MANWIDTH + else + manwidth = api.nvim_win_get_width(0) + end + + local cmd = localfile_arg and { 'man', '-l', path } or { 'man', path } + + -- Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db). + -- http://comments.gmane.org/gmane.editors.vim.devel/29085 + -- Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces. + return system(cmd, silent, { + 'MANPAGER=cat', + 'MANWIDTH=' .. manwidth, + 'MAN_KEEP_FORMATTING=1', + }) +end + +local function put_page(page) + vim.bo.modified = true + vim.bo.readonly = false + vim.bo.swapfile = false + + api.nvim_buf_set_lines(0, 0, -1, false, vim.split(page, '\n')) + + while fn.getline(1):match('^%s*$') do + api.nvim_buf_set_lines(0, 0, 1, false, {}) + end + -- XXX: nroff justifies text by filling it with whitespace. That interacts + -- badly with our use of $MANWIDTH=999. Hack around this by using a fixed + -- size for those whitespace regions. + vim.cmd([[silent! keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g]]) + vim.cmd('1') -- Move cursor to first line + highlight_man_page() + set_options(false) +end + +local function format_candidate(path, psect) + if matchstr(path, [[\.\%(pdf\|in\)$]]) then -- invalid extensions + return '' + end + local sect, name = extract_sect_and_name_path(path) + if sect == psect then + return name + elseif sect and name and matchstr(sect, psect .. '.\\+$') then -- invalid extensions + -- We include the section if the user provided section is a prefix + -- of the actual section. + return ('%s(%s)'):format(name, sect) + end + return '' +end + +local function move_elem_to_head(list, elem) + local list1 = vim.tbl_filter(function(v) + return v ~= elem + end, list) + return { elem, unpack(list1) } end -return { highlight_man_page = highlight_man_page } +local function get_paths(sect, name) + -- Try several sources for getting the list man directories: + -- 1. `man -w` (works on most systems) + -- 2. `manpath` + -- 3. $MANPATH + local mandirs_raw = vim.F.npcall(system, { 'man', FIND_ARG }) + or vim.F.npcall(system, { 'manpath', '-q' }) + or vim.env.MANPATH + + if not mandirs_raw then + man_error("Could not determine man directories from: 'man -w', 'manpath' or $MANPATH") + end + + local mandirs = table.concat(vim.split(mandirs_raw, '[:\n]', { trimempty = true }), ',') + local paths = fn.globpath(mandirs, 'man?/' .. name .. '*.' .. sect .. '*', false, true) + + -- Prioritize the result from verify_exists as it obeys b:man_default_sects. + local first = verify_exists(sect, name, true) + if first then + paths = move_elem_to_head(paths, first) + end + + return paths +end + +local function complete(sect, psect, name) + local pages = get_paths(sect, name) + -- We remove duplicates in case the same manpage in different languages was found. + return fn.uniq(fn.sort(vim.tbl_map(function(v) + return format_candidate(v, psect) + end, pages) or {}, 'i')) +end + +-- see extract_sect_and_name_ref on why tolower(sect) +function M.man_complete(arg_lead, cmd_line, _) + local args = vim.split(cmd_line, '%s+', { trimempty = true }) + local cmd_offset = fn.index(args, 'Man') + if cmd_offset > 0 then + -- Prune all arguments up to :Man itself. Otherwise modifier commands like + -- :tab, :vertical, etc. would lead to a wrong length. + args = vim.list_slice(args, cmd_offset + 1) + end + + if #args > 3 then + return {} + end + + if #args == 1 then + -- returning full completion is laggy. Require some arg_lead to complete + -- return complete('', '', '') + return {} + end + + if arg_lead:match('^[^()]+%([^()]*$') then + -- cursor (|) is at ':Man printf(|' or ':Man 1 printf(|' + -- The later is is allowed because of ':Man pri<TAB>'. + -- It will offer 'priclass.d(1m)' even though section is specified as 1. + local tmp = vim.split(arg_lead, '(', { plain = true }) + local name = tmp[1] + local sect = (tmp[2] or ''):lower() + return complete(sect, '', name) + end + + if not args[2]:match('^[^()]+$') then + -- cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|' + -- or ':Man 3() pri |' + return {} + end + + if #args == 2 then + local name, sect + if arg_lead == '' then + -- cursor (|) is at ':Man 1 |' + name = '' + sect = args[1]:lower() + else + -- cursor (|) is at ':Man pri|' + if arg_lead:match('/') then + -- if the name is a path, complete files + -- TODO(nhooyr) why does this complete the last one automatically + return fn.glob(arg_lead .. '*', false, true) + end + name = arg_lead + sect = '' + end + return complete(sect, sect, name) + end + + if not arg_lead:match('[^()]+$') then + -- cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|' + return {} + end + + -- cursor (|) is at ':Man 3 pri|' + local name = arg_lead + local sect = args[2]:lower() + return complete(sect, sect, name) +end + +function M.goto_tag(pattern, _, _) + local sect, name = extract_sect_and_name_ref(pattern) + + local paths = get_paths(sect, name) + local structured = {} + + for _, path in ipairs(paths) do + sect, name = extract_sect_and_name_path(path) + if sect and name then + structured[#structured + 1] = { + name = name, + title = name .. '(' .. sect .. ')', + } + end + end + + if vim.o.cscopetag then + -- return only a single entry so we work well with :cstag (#11675) + structured = { structured[1] } + end + + return vim.tbl_map(function(entry) + return { + name = entry.name, + filename = 'man://' .. entry.title, + cmd = '1', + } + end, structured) +end + +-- Called when Nvim is invoked as $MANPAGER. +function M.init_pager() + if fn.getline(1):match('^%s*$') then + api.nvim_buf_set_lines(0, 0, 1, false, {}) + else + vim.cmd('keepjumps 1') + end + highlight_man_page() + -- Guess the ref from the heading (which is usually uppercase, so we cannot + -- know the correct casing, cf. `man glDrawArraysInstanced`). + local ref = fn.substitute(matchstr(fn.getline(1), [[^[^)]\+)]]) or '', ' ', '_', 'g') + local ok, res = pcall(extract_sect_and_name_ref, ref) + vim.b.man_sect = ok and res or '' + + if not fn.bufname('%'):match('man://') then -- Avoid duplicate buffers, E95. + vim.cmd.file({ 'man://' .. fn.fnameescape(ref):lower(), mods = { silent = true } }) + end + + set_options(true) +end + +function M.open_page(count, smods, args) + if #args > 2 then + man_error('too many arguments') + end + + local ref + if #args == 0 then + ref = vim.bo.filetype == 'man' and fn.expand('<cWORD>') or fn.expand('<cword>') + if ref == '' then + man_error('no identifier under cursor') + end + elseif #args == 1 then + ref = args[1] + else + -- Combine the name and sect into a manpage reference so that all + -- verification/extraction can be kept in a single function. + -- If args[2] is a reference as well, that is fine because it is the only + -- reference that will match. + ref = ('%s(%s)'):format(args[2], args[1]) + end + + local sect, name = extract_sect_and_name_ref(ref) + if count >= 0 then + sect = tostring(count) + end + + local path = verify_exists(sect, name) + sect, name = extract_sect_and_name_path(path) + + local buf = fn.bufnr() + local save_tfu = vim.bo[buf].tagfunc + vim.bo[buf].tagfunc = "v:lua.require'man'.goto_tag" + + local target = ('%s(%s)'):format(name, sect) + + local ok, ret = pcall(function() + if smods.tab == -1 and find_man() then + vim.cmd.tag({ target, mods = { silent = true, keepalt = true } }) + else + smods.silent = true + smods.keepalt = true + vim.cmd.stag({ target, mods = smods }) + end + end) + + vim.bo[buf].tagfunc = save_tfu + + if not ok then + error(ret) + else + set_options(false) + end + + vim.b.man_sect = sect +end + +-- Called when a man:// buffer is opened. +function M.read_page(ref) + local sect, name = extract_sect_and_name_ref(ref) + local path = verify_exists(sect, name) + sect = extract_sect_and_name_path(path) + local page = get_page(path) + vim.b.man_sect = sect + put_page(page) +end + +function M.show_toc() + local bufname = fn.bufname('%') + local info = fn.getloclist(0, { winid = 1 }) + if info ~= '' and vim.w[info.winid].qf_toc == bufname then + vim.cmd.lopen() + return + end + + local toc = {} + local lnum = 2 + local last_line = fn.line('$') - 1 + local section_title_re = vim.regex([[^\%( \{3\}\)\=\S.*$]]) + local flag_title_re = vim.regex([[^\s\+\%(+\|-\)\S\+]]) + while lnum and lnum < last_line do + local text = fn.getline(lnum) + if section_title_re:match_str(text) then + -- if text is a section title + toc[#toc + 1] = { + bufnr = fn.bufnr('%'), + lnum = lnum, + text = text, + } + elseif flag_title_re:match_str(text) then + -- if text is a flag title. we strip whitespaces and prepend two + -- spaces to have a consistent format in the loclist. + toc[#toc + 1] = { + bufnr = fn.bufnr('%'), + lnum = lnum, + text = ' ' .. fn.substitute(text, [[^\s*\(.\{-}\)\s*$]], [[\1]], ''), + } + end + lnum = fn.nextnonblank(lnum + 1) + end + + fn.setloclist(0, toc, ' ') + fn.setloclist(0, {}, 'a', { title = 'Man TOC' }) + vim.cmd.lopen() + vim.w.qf_toc = bufname +end + +local function init() + local path = get_path('', 'man', true) + local page + if path ~= nil then + -- Check for -l support. + page = get_page(path, true) + end + + if page == '' or page == nil then + localfile_arg = false + end +end + +init() + +return M diff --git a/runtime/lua/man/health.lua b/runtime/lua/man/health.lua new file mode 100644 index 0000000000..11d7148216 --- /dev/null +++ b/runtime/lua/man/health.lua @@ -0,0 +1,20 @@ +local M = {} + +local report_ok = vim.fn['health#report_ok'] +local report_error = vim.fn['health#report_error'] + +local function check_runtime_file(name) + local path = vim.env.VIMRUNTIME .. '/' .. name + if vim.loop.fs_stat(path) then + report_error(string.format('%s detected. Please delete %s', name, path)) + else + report_ok(string.format('%s not in $VIMRUNTIME', name)) + end +end + +function M.check() + check_runtime_file('plugin/man.vim') + check_runtime_file('autoload/man.vim') +end + +return M diff --git a/runtime/lua/vim/F.lua b/runtime/lua/vim/F.lua index bca5ddf68b..3e370c0a84 100644 --- a/runtime/lua/vim/F.lua +++ b/runtime/lua/vim/F.lua @@ -2,8 +2,12 @@ local F = {} --- Returns {a} if it is not nil, otherwise returns {b}. --- ----@param a ----@param b +---@generic A +---@generic B +--- +---@param a A +---@param b B +---@return A | B function F.if_nil(a, b) if a == nil then return b diff --git a/runtime/lua/vim/_editor.lua b/runtime/lua/vim/_editor.lua index b8a7f71145..28e5897aa9 100644 --- a/runtime/lua/vim/_editor.lua +++ b/runtime/lua/vim/_editor.lua @@ -12,21 +12,8 @@ -- Guideline: "If in doubt, put it in the runtime". -- -- Most functions should live directly in `vim.`, not in submodules. --- The only "forbidden" names are those claimed by legacy `if_lua`: --- $ vim --- :lua for k,v in pairs(vim) do print(k) end --- buffer --- open --- window --- lastline --- firstline --- type --- line --- eval --- dict --- beep --- list --- command +-- +-- Compatibility with Vim's `if_lua` is explicitly a non-goal. -- -- Reference (#6580): -- - https://github.com/luafun/luafun @@ -36,8 +23,6 @@ -- - https://github.com/bakpakin/Fennel (pretty print, repl) -- - https://github.com/howl-editor/howl/tree/master/lib/howl/util -local vim = assert(vim) - -- These are for loading runtime modules lazily since they aren't available in -- the nvim binary as specified in executor.c for k, v in pairs({ @@ -122,9 +107,7 @@ function vim._os_proc_children(ppid) return children end --- TODO(ZyX-I): Create compatibility layer. - ---- Return a human-readable representation of the given object. +--- Gets a human-readable representation of the given object. --- ---@see https://github.com/kikito/inspect.lua ---@see https://github.com/mpeterv/vinspect @@ -152,14 +135,15 @@ do --- </pre> --- ---@see |paste| + ---@alias paste_phase -1 | 1 | 2 | 3 --- - ---@param lines |readfile()|-style list of lines to paste. |channel-lines| - ---@param phase -1: "non-streaming" paste: the call contains all lines. + ---@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. --- 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) - ---@returns false if client should cancel the paste. + ---@returns boolean # false if client should cancel the paste. function vim.paste(lines, phase) local now = vim.loop.now() local is_first_chunk = phase < 2 @@ -255,6 +239,8 @@ end ---@see |lua-loop-callbacks| ---@see |vim.schedule()| ---@see |vim.in_fast_event()| +---@param cb function +---@return function function vim.schedule_wrap(cb) return function(...) local args = vim.F.pack_len(...) @@ -399,11 +385,11 @@ end --- Get a table of lines with start, end columns for a region marked by two points --- ---@param bufnr number of buffer ----@param pos1 (line, column) tuple marking beginning of region ----@param pos2 (line, column) tuple marking end of region ----@param regtype type of selection (:help setreg) +---@param pos1 integer[] (line, column) tuple marking beginning of region +---@param pos2 integer[] (line, column) tuple marking end of region +---@param regtype string type of selection, see |setreg()| ---@param inclusive boolean indicating whether the selection is end-inclusive ----@return region lua table of the form {linenr = {startcol,endcol}} +---@return table<integer, {}> region lua table of the form {linenr = {startcol,endcol}} function vim.region(bufnr, pos1, pos2, regtype, inclusive) if not vim.api.nvim_buf_is_loaded(bufnr) then vim.fn.bufload(bufnr) @@ -448,11 +434,11 @@ end --- Defers calling `fn` until `timeout` ms passes. --- --- Use to do a one-shot timer that calls `fn` ---- Note: The {fn} is |schedule_wrap|ped automatically, so API functions are +--- Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are --- safe to call. ----@param fn Callback to call once `timeout` expires ----@param timeout Number of milliseconds to wait before calling `fn` ----@return timer luv timer object +---@param fn function Callback to call once `timeout` expires +---@param timeout integer Number of milliseconds to wait before calling `fn` +---@return table timer luv timer object function vim.defer_fn(fn, timeout) vim.validate({ fn = { fn, 'c', true } }) local timer = vim.loop.new_timer() @@ -758,7 +744,7 @@ end --- local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true)) ---</pre> ---@see |vim.inspect()| ----@return given arguments. +---@return any # given arguments. function vim.pretty_print(...) local objects = {} for i = 1, select('#', ...) do diff --git a/runtime/lua/vim/_init_packages.lua b/runtime/lua/vim/_init_packages.lua index 7e3c73667e..19c8608732 100644 --- a/runtime/lua/vim/_init_packages.lua +++ b/runtime/lua/vim/_init_packages.lua @@ -1,6 +1,3 @@ --- prevents luacheck from making lints for setting things on vim -local vim = assert(vim) - local pathtrails = {} vim._so_trails = {} for s in (package.cpath .. ';'):gmatch('[^;]*;') do diff --git a/runtime/lua/vim/_meta.lua b/runtime/lua/vim/_meta.lua index f1652718ee..9c7972873e 100644 --- a/runtime/lua/vim/_meta.lua +++ b/runtime/lua/vim/_meta.lua @@ -1,173 +1,113 @@ --- prevents luacheck from making lints for setting things on vim -local vim = assert(vim) - local a = vim.api -local validate = vim.validate - -local SET_TYPES = setmetatable({ - SET = 0, - LOCAL = 1, - GLOBAL = 2, -}, { __index = error }) - -local options_info = nil -local buf_options = nil -local glb_options = nil -local win_options = nil - -local function _setup() - if options_info ~= nil then - return - end - options_info = {} - for _, v in pairs(a.nvim_get_all_options_info()) do - options_info[v.name] = v - if v.shortname ~= '' then - options_info[v.shortname] = v - end - end - local function get_scoped_options(scope) - local result = {} - for name, option_info in pairs(options_info) do - if option_info.scope == scope then - result[name] = true +-- TODO(tjdevries): Improve option metadata so that this doesn't have to be hardcoded. +-- Can be done in a separate PR. +local key_value_options = { + fillchars = true, + fcs = true, + listchars = true, + lcs = true, + winhighlight = true, + winhl = true, +} + +--- Convert a vimoption_T style dictionary to the correct OptionType associated with it. +---@return string +local function get_option_metatype(name, info) + if info.type == 'string' then + if info.flaglist then + return 'set' + elseif info.commalist then + if key_value_options[name] then + return 'map' end + return 'array' end - - return result + return 'string' end - - buf_options = get_scoped_options('buf') - glb_options = get_scoped_options('global') - win_options = get_scoped_options('win') + return info.type end -local function make_meta_accessor(get, set, del, validator) - validator = validator or function() - return true - end - - validate({ - get = { get, 'f' }, - set = { set, 'f' }, - del = { del, 'f', true }, - validator = { validator, 'f' }, - }) +local options_info = setmetatable({}, { + __index = function(t, k) + local info = a.nvim_get_option_info(k) + info.metatype = get_option_metatype(k, info) + rawset(t, k, info) + return rawget(t, k) + end, +}) - local mt = {} - function mt:__newindex(k, v) - if not validator(k) then - return +vim.env = setmetatable({}, { + __index = function(_, k) + local v = vim.fn.getenv(k) + if v == vim.NIL then + return nil end + return v + end, - if del and v == nil then - return del(k) - end - return set(k, v) - end - function mt:__index(k) - if not validator(k) then - return - end + __newindex = function(_, k, v) + vim.fn.setenv(k, v) + end, +}) - return get(k) +local function opt_validate(option_name, target_scope) + local scope = options_info[option_name].scope + if scope ~= target_scope then + local scope_to_string = { buf = 'buffer', win = 'window' } + error( + string.format( + [['%s' is a %s option, not a %s option. See ":help %s"]], + option_name, + scope_to_string[scope] or scope, + scope_to_string[target_scope] or target_scope, + option_name + ) + ) end - return setmetatable({}, mt) end -vim.env = make_meta_accessor(function(k) - local v = vim.fn.getenv(k) - if v == vim.NIL then - return nil - end - return v -end, vim.fn.setenv) - -do -- buffer option accessor - local function new_buf_opt_accessor(bufnr) - local function get(k) - if bufnr == nil and type(k) == 'number' then - return new_buf_opt_accessor(k) - end - - return a.nvim_get_option_value(k, { buf = bufnr or 0 }) - end - - local function set(k, v) - return a.nvim_set_option_value(k, v, { buf = bufnr or 0 }) - end - - return make_meta_accessor(get, set, nil, function(k) - if type(k) == 'string' then - _setup() - if win_options[k] then - error( - string.format([['%s' is a window option, not a buffer option. See ":help %s"]], k, k) - ) - elseif glb_options[k] then - error( - string.format([['%s' is a global option, not a buffer option. See ":help %s"]], k, k) - ) - end +local function new_opt_accessor(handle, scope) + return setmetatable({}, { + __index = function(_, k) + if handle == nil and type(k) == 'number' then + return new_opt_accessor(k, scope) end + opt_validate(k, scope) + return a.nvim_get_option_value(k, { [scope] = handle or 0 }) + end, - return true - end) - end - - vim.bo = new_buf_opt_accessor(nil) + __newindex = function(_, k, v) + opt_validate(k, scope) + return a.nvim_set_option_value(k, v, { [scope] = handle or 0 }) + end, + }) end -do -- window option accessor - local function new_win_opt_accessor(winnr) - local function get(k) - if winnr == nil and type(k) == 'number' then - return new_win_opt_accessor(k) - end - return a.nvim_get_option_value(k, { win = winnr or 0 }) - end - - local function set(k, v) - return a.nvim_set_option_value(k, v, { win = winnr or 0 }) - end - - return make_meta_accessor(get, set, nil, function(k) - if type(k) == 'string' then - _setup() - if buf_options[k] then - error( - string.format([['%s' is a buffer option, not a window option. See ":help %s"]], k, k) - ) - elseif glb_options[k] then - error( - string.format([['%s' is a global option, not a window option. See ":help %s"]], k, k) - ) - end - end - - return true - end) - end - - vim.wo = new_win_opt_accessor(nil) -end +vim.bo = new_opt_accessor(nil, 'buf') +vim.wo = new_opt_accessor(nil, 'win') -- vim global option -- this ONLY sets the global option. like `setglobal` -vim.go = make_meta_accessor(function(k) - return a.nvim_get_option_value(k, { scope = 'global' }) -end, function(k, v) - return a.nvim_set_option_value(k, v, { scope = 'global' }) -end) +vim.go = setmetatable({}, { + __index = function(_, k) + return a.nvim_get_option_value(k, { scope = 'global' }) + end, + __newindex = function(_, k, v) + return a.nvim_set_option_value(k, v, { scope = 'global' }) + end, +}) -- vim `set` style options. -- it has no additional metamethod magic. -vim.o = make_meta_accessor(function(k) - return a.nvim_get_option_value(k, {}) -end, function(k, v) - return a.nvim_set_option_value(k, v, {}) -end) +vim.o = setmetatable({}, { + __index = function(_, k) + return a.nvim_get_option_value(k, {}) + end, + __newindex = function(_, k, v) + return a.nvim_set_option_value(k, v, {}) + end, +}) ---@brief [[ --- vim.opt, vim.opt_local and vim.opt_global implementation @@ -178,11 +118,8 @@ end) ---@brief ]] --- Preserves the order and does not mutate the original list -local remove_duplicate_values = function(t) +local function remove_duplicate_values(t) local result, seen = {}, {} - if type(t) == 'function' then - error(debug.traceback('asdf')) - end for _, v in ipairs(t) do if not seen[v] then table.insert(result, v) @@ -194,61 +131,6 @@ local remove_duplicate_values = function(t) return result end --- TODO(tjdevries): Improve option metadata so that this doesn't have to be hardcoded. --- Can be done in a separate PR. -local key_value_options = { - fillchars = true, - listchars = true, - winhl = true, -} - ----@class OptionTypes ---- Option Type Enum -local OptionTypes = setmetatable({ - BOOLEAN = 0, - NUMBER = 1, - STRING = 2, - ARRAY = 3, - MAP = 4, - SET = 5, -}, { - __index = function(_, k) - error('Not a valid OptionType: ' .. k) - end, - __newindex = function(_, k) - error('Cannot set a new OptionType: ' .. k) - end, -}) - ---- Convert a vimoption_T style dictionary to the correct OptionType associated with it. ----@return OptionType -local get_option_type = function(name, info) - if info.type == 'boolean' then - return OptionTypes.BOOLEAN - elseif info.type == 'number' then - return OptionTypes.NUMBER - elseif info.type == 'string' then - if not info.commalist and not info.flaglist then - return OptionTypes.STRING - end - - if key_value_options[name] then - assert(info.commalist, 'Must be a comma list to use key:value style') - return OptionTypes.MAP - end - - if info.flaglist then - return OptionTypes.SET - elseif info.commalist then - return OptionTypes.ARRAY - end - - error('Fallthrough in OptionTypes') - else - error('Not a known info.type:' .. info.type) - end -end - -- Check whether the OptionTypes is allowed for vim.opt -- If it does not match, throw an error which indicates which option causes the error. local function assert_valid_value(name, value, types) @@ -269,373 +151,323 @@ local function assert_valid_value(name, value, types) ) end +local function passthrough(_, x) + return x +end + +local function tbl_merge(left, right) + return vim.tbl_extend('force', left, right) +end + +local function tbl_remove(t, value) + if type(value) == 'string' then + t[value] = nil + else + for _, v in ipairs(value) do + t[v] = nil + end + end + + return t +end + local valid_types = { - [OptionTypes.BOOLEAN] = { 'boolean' }, - [OptionTypes.NUMBER] = { 'number' }, - [OptionTypes.STRING] = { 'string' }, - [OptionTypes.SET] = { 'string', 'table' }, - [OptionTypes.ARRAY] = { 'string', 'table' }, - [OptionTypes.MAP] = { 'string', 'table' }, + boolean = { 'boolean' }, + number = { 'number' }, + string = { 'string' }, + set = { 'string', 'table' }, + array = { 'string', 'table' }, + map = { 'string', 'table' }, } ---- Convert a lua value to a vimoption_T value -local convert_value_to_vim = (function() - -- Map of functions to take a Lua style value and convert to vimoption_T style value. - -- Each function takes (info, lua_value) -> vim_value - local to_vim_value = { - [OptionTypes.BOOLEAN] = function(_, value) - return value - end, - [OptionTypes.NUMBER] = function(_, value) - return value - end, - [OptionTypes.STRING] = function(_, value) - return value - end, - - [OptionTypes.SET] = function(info, value) - if type(value) == 'string' then - return value - end +-- Map of functions to take a Lua style value and convert to vimoption_T style value. +-- Each function takes (info, lua_value) -> vim_value +local to_vim_value = { + boolean = passthrough, + number = passthrough, + string = passthrough, - if info.flaglist and info.commalist then - local keys = {} - for k, v in pairs(value) do - if v then - table.insert(keys, k) - end - end + set = function(info, value) + if type(value) == 'string' then + return value + end - table.sort(keys) - return table.concat(keys, ',') - else - local result = '' - for k, v in pairs(value) do - if v then - result = result .. k - end + if info.flaglist and info.commalist then + local keys = {} + for k, v in pairs(value) do + if v then + table.insert(keys, k) end - - return result end - end, - [OptionTypes.ARRAY] = function(info, value) - if type(value) == 'string' then - return value - end - if not info.allows_duplicates then - value = remove_duplicate_values(value) + table.sort(keys) + return table.concat(keys, ',') + else + local result = '' + for k, v in pairs(value) do + if v then + result = result .. k + end end - return table.concat(value, ',') - end, - [OptionTypes.MAP] = function(_, value) - if type(value) == 'string' then - return value - end + return result + end + end, - local result = {} - for opt_key, opt_value in pairs(value) do - table.insert(result, string.format('%s:%s', opt_key, opt_value)) - end + array = function(info, value) + if type(value) == 'string' then + return value + end + if not info.allows_duplicates then + value = remove_duplicate_values(value) + end + return table.concat(value, ',') + end, - table.sort(result) - return table.concat(result, ',') - end, - } + map = function(_, value) + if type(value) == 'string' then + return value + end - return function(name, info, value) - if value == nil then - return vim.NIL + local result = {} + for opt_key, opt_value in pairs(value) do + table.insert(result, string.format('%s:%s', opt_key, opt_value)) end - local option_type = get_option_type(name, info) - assert_valid_value(name, value, valid_types[option_type]) + table.sort(result) + return table.concat(result, ',') + end, +} - return to_vim_value[option_type](info, value) +--- Convert a lua value to a vimoption_T value +local function convert_value_to_vim(name, info, value) + if value == nil then + return vim.NIL end -end)() ---- Converts a vimoption_T style value to a Lua value -local convert_value_to_lua = (function() - -- Map of OptionType to functions that take vimoption_T values and convert to lua values. - -- Each function takes (info, vim_value) -> lua_value - local to_lua_value = { - [OptionTypes.BOOLEAN] = function(_, value) - return value - end, - [OptionTypes.NUMBER] = function(_, value) - return value - end, - [OptionTypes.STRING] = function(_, value) - return value - end, + assert_valid_value(name, value, valid_types[info.metatype]) - [OptionTypes.ARRAY] = function(info, value) - if type(value) == 'table' then - if not info.allows_duplicates then - value = remove_duplicate_values(value) - end + return to_vim_value[info.metatype](info, value) +end - return value - end +-- Map of OptionType to functions that take vimoption_T values and convert to lua values. +-- Each function takes (info, vim_value) -> lua_value +local to_lua_value = { + boolean = passthrough, + number = passthrough, + string = passthrough, - -- Empty strings mean that there is nothing there, - -- so empty table should be returned. - if value == '' then - return {} + array = function(info, value) + if type(value) == 'table' then + if not info.allows_duplicates then + value = remove_duplicate_values(value) end - -- Handles unescaped commas in a list. - if string.find(value, ',,,') then - local comma_split = vim.split(value, ',,,') - local left = comma_split[1] - local right = comma_split[2] + return value + end - local result = {} - vim.list_extend(result, vim.split(left, ',')) - table.insert(result, ',') - vim.list_extend(result, vim.split(right, ',')) + -- Empty strings mean that there is nothing there, + -- so empty table should be returned. + if value == '' then + return {} + end - table.sort(result) + -- Handles unescaped commas in a list. + if string.find(value, ',,,') then + local left, right = unpack(vim.split(value, ',,,')) - return result - end + local result = {} + vim.list_extend(result, vim.split(left, ',')) + table.insert(result, ',') + vim.list_extend(result, vim.split(right, ',')) - if string.find(value, ',^,,', 1, true) then - local comma_split = vim.split(value, ',^,,', true) - local left = comma_split[1] - local right = comma_split[2] + table.sort(result) - local result = {} - vim.list_extend(result, vim.split(left, ',')) - table.insert(result, '^,') - vim.list_extend(result, vim.split(right, ',')) + return result + end - table.sort(result) + if string.find(value, ',^,,', 1, true) then + local left, right = unpack(vim.split(value, ',^,,', true)) - return result - end + local result = {} + vim.list_extend(result, vim.split(left, ',')) + table.insert(result, '^,') + vim.list_extend(result, vim.split(right, ',')) - return vim.split(value, ',') - end, + table.sort(result) - [OptionTypes.SET] = function(info, value) - if type(value) == 'table' then - return value - end + return result + end - -- Empty strings mean that there is nothing there, - -- so empty table should be returned. - if value == '' then - return {} - end + return vim.split(value, ',') + end, - assert(info.flaglist, 'That is the only one I know how to handle') + set = function(info, value) + if type(value) == 'table' then + return value + end - if info.flaglist and info.commalist then - local split_value = vim.split(value, ',') - local result = {} - for _, v in ipairs(split_value) do - result[v] = true - end + -- Empty strings mean that there is nothing there, + -- so empty table should be returned. + if value == '' then + return {} + end - return result - else - local result = {} - for i = 1, #value do - result[value:sub(i, i)] = true - end + assert(info.flaglist, 'That is the only one I know how to handle') - return result + if info.flaglist and info.commalist then + local split_value = vim.split(value, ',') + local result = {} + for _, v in ipairs(split_value) do + result[v] = true end - end, - [OptionTypes.MAP] = function(info, raw_value) - if type(raw_value) == 'table' then - return raw_value + return result + else + local result = {} + for i = 1, #value do + result[value:sub(i, i)] = true end - assert(info.commalist, 'Only commas are supported currently') - - local result = {} + return result + end + end, - local comma_split = vim.split(raw_value, ',') - for _, key_value_str in ipairs(comma_split) do - local key, value = unpack(vim.split(key_value_str, ':')) - key = vim.trim(key) + map = function(info, raw_value) + if type(raw_value) == 'table' then + return raw_value + end - result[key] = value - end + assert(info.commalist, 'Only commas are supported currently') - return result - end, - } + local result = {} - return function(name, info, option_value) - return to_lua_value[get_option_type(name, info)](info, option_value) - end -end)() + local comma_split = vim.split(raw_value, ',') + for _, key_value_str in ipairs(comma_split) do + local key, value = unpack(vim.split(key_value_str, ':')) + key = vim.trim(key) ---- Handles the mutation of various different values. -local value_mutator = function(name, info, current, new, mutator) - return mutator[get_option_type(name, info)](current, new) -end + result[key] = value + end ---- Handles the '^' operator -local prepend_value = (function() - local methods = { - [OptionTypes.NUMBER] = function() - error("The '^' operator is not currently supported for") - end, + return result + end, +} - [OptionTypes.STRING] = function(left, right) - return right .. left - end, +--- Converts a vimoption_T style value to a Lua value +local function convert_value_to_lua(info, option_value) + return to_lua_value[info.metatype](info, option_value) +end - [OptionTypes.ARRAY] = function(left, right) - for i = #right, 1, -1 do - table.insert(left, 1, right[i]) - end +local prepend_methods = { + number = function() + error("The '^' operator is not currently supported for") + end, - return left - end, + string = function(left, right) + return right .. left + end, - [OptionTypes.MAP] = function(left, right) - return vim.tbl_extend('force', left, right) - end, + array = function(left, right) + for i = #right, 1, -1 do + table.insert(left, 1, right[i]) + end - [OptionTypes.SET] = function(left, right) - return vim.tbl_extend('force', left, right) - end, - } + return left + end, - return function(name, info, current, new) - return value_mutator( - name, - info, - convert_value_to_lua(name, info, current), - convert_value_to_lua(name, info, new), - methods - ) - end -end)() + map = tbl_merge, + set = tbl_merge, +} ---- Handles the '+' operator -local add_value = (function() - local methods = { - [OptionTypes.NUMBER] = function(left, right) - return left + right - end, +--- Handles the '^' operator +local function prepend_value(info, current, new) + return prepend_methods[info.metatype]( + convert_value_to_lua(info, current), + convert_value_to_lua(info, new) + ) +end - [OptionTypes.STRING] = function(left, right) - return left .. right - end, +local add_methods = { + number = function(left, right) + return left + right + end, - [OptionTypes.ARRAY] = function(left, right) - for _, v in ipairs(right) do - table.insert(left, v) - end + string = function(left, right) + return left .. right + end, - return left - end, + array = function(left, right) + for _, v in ipairs(right) do + table.insert(left, v) + end - [OptionTypes.MAP] = function(left, right) - return vim.tbl_extend('force', left, right) - end, + return left + end, - [OptionTypes.SET] = function(left, right) - return vim.tbl_extend('force', left, right) - end, - } + map = tbl_merge, + set = tbl_merge, +} - return function(name, info, current, new) - return value_mutator( - name, - info, - convert_value_to_lua(name, info, current), - convert_value_to_lua(name, info, new), - methods - ) - end -end)() +--- Handles the '+' operator +local function add_value(info, current, new) + return add_methods[info.metatype]( + convert_value_to_lua(info, current), + convert_value_to_lua(info, new) + ) +end ---- Handles the '-' operator -local remove_value = (function() - local remove_one_item = function(t, val) - if vim.tbl_islist(t) then - local remove_index = nil - for i, v in ipairs(t) do - if v == val then - remove_index = i - end +local function remove_one_item(t, val) + if vim.tbl_islist(t) then + local remove_index = nil + for i, v in ipairs(t) do + if v == val then + remove_index = i end + end - if remove_index then - table.remove(t, remove_index) - end - else - t[val] = nil + if remove_index then + table.remove(t, remove_index) end + else + t[val] = nil end +end - local methods = { - [OptionTypes.NUMBER] = function(left, right) - return left - right - end, - - [OptionTypes.STRING] = function() - error('Subtraction not supported for strings.') - end, - - [OptionTypes.ARRAY] = function(left, right) - if type(right) == 'string' then - remove_one_item(left, right) - else - for _, v in ipairs(right) do - remove_one_item(left, v) - end - end +local remove_methods = { + number = function(left, right) + return left - right + end, - return left - end, + string = function() + error('Subtraction not supported for strings.') + end, - [OptionTypes.MAP] = function(left, right) - if type(right) == 'string' then - left[right] = nil - else - for _, v in ipairs(right) do - left[v] = nil - end + array = function(left, right) + if type(right) == 'string' then + remove_one_item(left, right) + else + for _, v in ipairs(right) do + remove_one_item(left, v) end + end - return left - end, - - [OptionTypes.SET] = function(left, right) - if type(right) == 'string' then - left[right] = nil - else - for _, v in ipairs(right) do - left[v] = nil - end - end + return left + end, - return left - end, - } + map = tbl_remove, + set = tbl_remove, +} - return function(name, info, current, new) - return value_mutator(name, info, convert_value_to_lua(name, info, current), new, methods) - end -end)() +--- Handles the '-' operator +local function remove_value(info, current, new) + return remove_methods[info.metatype](convert_value_to_lua(info, current), new) +end -local create_option_metatable = function(set_type) - local set_mt, option_mt +local function create_option_accessor(scope) + local option_mt - local make_option = function(name, value) - _setup() + local function make_option(name, value) local info = assert(options_info[name], 'Not a valid option name: ' .. name) if type(value) == 'table' and getmetatable(value) == option_mt then @@ -651,67 +483,58 @@ local create_option_metatable = function(set_type) }, option_mt) end - local scope - if set_type == SET_TYPES.GLOBAL then - scope = 'global' - elseif set_type == SET_TYPES.LOCAL then - scope = 'local' - end - option_mt = { -- To set a value, instead use: -- opt[my_option] = value _set = function(self) local value = convert_value_to_vim(self._name, self._info, self._value) a.nvim_set_option_value(self._name, value, { scope = scope }) - - return self end, get = function(self) - return convert_value_to_lua(self._name, self._info, self._value) + return convert_value_to_lua(self._info, self._value) end, append = function(self, right) - return self:__add(right):_set() + self._value = add_value(self._info, self._value, right) + self:_set() end, __add = function(self, right) - return make_option(self._name, add_value(self._name, self._info, self._value, right)) + return make_option(self._name, add_value(self._info, self._value, right)) end, prepend = function(self, right) - return self:__pow(right):_set() + self._value = prepend_value(self._info, self._value, right) + self:_set() end, __pow = function(self, right) - return make_option(self._name, prepend_value(self._name, self._info, self._value, right)) + return make_option(self._name, prepend_value(self._info, self._value, right)) end, remove = function(self, right) - return self:__sub(right):_set() + self._value = remove_value(self._info, self._value, right) + self:_set() end, __sub = function(self, right) - return make_option(self._name, remove_value(self._name, self._info, self._value, right)) + return make_option(self._name, remove_value(self._info, self._value, right)) end, } option_mt.__index = option_mt - set_mt = { + return setmetatable({}, { __index = function(_, k) return make_option(k, a.nvim_get_option_value(k, { scope = scope })) end, __newindex = function(_, k, v) - local opt = make_option(k, v) - opt:_set() + make_option(k, v):_set() end, - } - - return set_mt + }) end -vim.opt = setmetatable({}, create_option_metatable(SET_TYPES.SET)) -vim.opt_local = setmetatable({}, create_option_metatable(SET_TYPES.LOCAL)) -vim.opt_global = setmetatable({}, create_option_metatable(SET_TYPES.GLOBAL)) +vim.opt = create_option_accessor() +vim.opt_local = create_option_accessor('local') +vim.opt_global = create_option_accessor('global') diff --git a/runtime/lua/vim/compat.lua b/runtime/lua/vim/compat.lua deleted file mode 100644 index 2c9786d491..0000000000 --- a/runtime/lua/vim/compat.lua +++ /dev/null @@ -1,12 +0,0 @@ --- Lua 5.1 forward-compatibility layer. --- For background see https://github.com/neovim/neovim/pull/9280 --- --- Reference the lua-compat-5.2 project for hints: --- https://github.com/keplerproject/lua-compat-5.2/blob/c164c8f339b95451b572d6b4b4d11e944dc7169d/compat52/mstrict.lua --- https://github.com/keplerproject/lua-compat-5.2/blob/c164c8f339b95451b572d6b4b4d11e944dc7169d/tests/test.lua - -local lua_version = _VERSION:sub(-3) - -if lua_version >= '5.2' then - unpack = table.unpack -- luacheck: ignore 121 143 -end diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua index 3f71d4f70d..84091fbf0e 100644 --- a/runtime/lua/vim/diagnostic.lua +++ b/runtime/lua/vim/diagnostic.lua @@ -45,18 +45,24 @@ local bufnr_and_namespace_cacher_mt = { end, } -local diagnostic_cache = setmetatable({}, { - __index = function(t, bufnr) - assert(bufnr > 0, 'Invalid buffer number') - vim.api.nvim_buf_attach(bufnr, false, { - on_detach = function() - rawset(t, bufnr, nil) -- clear cache - end, - }) - t[bufnr] = {} - return t[bufnr] - end, -}) +local diagnostic_cache +do + local group = vim.api.nvim_create_augroup('DiagnosticBufWipeout', {}) + diagnostic_cache = setmetatable({}, { + __index = function(t, bufnr) + assert(bufnr > 0, 'Invalid buffer number') + vim.api.nvim_create_autocmd('BufWipeout', { + group = group, + buffer = bufnr, + callback = function() + rawset(t, bufnr, nil) + end, + }) + t[bufnr] = {} + return t[bufnr] + end, + }) +end local diagnostic_cache_extmarks = setmetatable({}, bufnr_and_namespace_cacher_mt) local diagnostic_attached_buffers = {} @@ -351,19 +357,6 @@ local function execute_scheduled_display(namespace, bufnr) M.show(namespace, bufnr, nil, args) end ---- @deprecated ---- Callback scheduled when leaving Insert mode. ---- ---- called from the Vimscript autocommand. ---- ---- See @ref schedule_display() ---- ----@private -function M._execute_scheduled_display(namespace, bufnr) - vim.deprecate('vim.diagnostic._execute_scheduled_display', nil, '0.9') - execute_scheduled_display(namespace, bufnr) -end - --- Table of autocmd events to fire the update for displaying new diagnostic information local insert_leave_auto_cmds = { 'InsertLeave', 'CursorHoldI' } @@ -721,6 +714,7 @@ function M.set(namespace, bufnr, diagnostics, opts) vim.api.nvim_exec_autocmds('DiagnosticChanged', { modeline = false, buffer = bufnr, + data = { diagnostics = diagnostics }, }) end @@ -1419,6 +1413,7 @@ function M.reset(namespace, bufnr) vim.api.nvim_exec_autocmds('DiagnosticChanged', { modeline = false, buffer = iter_bufnr, + data = { diagnostics = {} }, }) end end diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 99c98764dd..e204fe8ae2 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -177,6 +177,7 @@ local extension = { bbappend = 'bitbake', bbclass = 'bitbake', bl = 'blank', + blp = 'blueprint', bsd = 'bsdl', bsdl = 'bsdl', bst = 'bst', @@ -201,6 +202,7 @@ local extension = { return require('vim.filetype.detect').change(bufnr) end, chs = 'chaskell', + chatito = 'chatito', chopro = 'chordpro', crd = 'chordpro', crdpro = 'chordpro', @@ -422,9 +424,11 @@ local extension = { gdb = 'gdb', gdmo = 'gdmo', mo = 'gdmo', - tres = 'gdresource', tscn = 'gdresource', + tres = 'gdresource', gd = 'gdscript', + gdshader = 'gdshader', + shader = 'gdshader', ged = 'gedcom', gmi = 'gemtext', gemini = 'gemtext', @@ -444,6 +448,8 @@ local extension = { gsp = 'gsp', gjs = 'javascript.glimmer', gts = 'typescript.glimmer', + gyp = 'gyp', + gypi = 'gyp', hack = 'hack', hackpartial = 'hack', haml = 'haml', @@ -469,6 +475,8 @@ local extension = { hex = 'hex', ['h32'] = 'hex', hjson = 'hjson', + m3u = 'hlsplaylist', + m3u8 = 'hlsplaylist', hog = 'hog', hws = 'hollywood', hoon = 'hoon', @@ -538,6 +546,7 @@ local extension = { mjs = 'javascript', javascript = 'javascript', js = 'javascript', + jsm = 'javascript', cjs = 'javascript', jsx = 'javascriptreact', clp = 'jess', @@ -554,6 +563,8 @@ local extension = { ['json-patch'] = 'json', json5 = 'json5', jsonc = 'jsonc', + jsonnet = 'jsonnet', + libjsonnet = 'jsonnet', jsp = 'jsp', jl = 'julia', kv = 'kivy', @@ -605,6 +616,7 @@ local extension = { nse = 'lua', rockspec = 'lua', lua = 'lua', + lrc = 'lyrics', m = function(path, bufnr) return require('vim.filetype.detect').m(bufnr) end, @@ -695,6 +707,9 @@ local extension = { nanorc = 'nanorc', ncf = 'ncf', nginx = 'nginx', + nim = 'nim', + nims = 'nim', + nimble = 'nim', ninja = 'ninja', nix = 'nix', nqc = 'nqc', @@ -741,6 +756,7 @@ local extension = { php = 'php', phpt = 'php', phtml = 'php', + theme = 'php', pike = 'pike', pmod = 'pike', rcp = 'pilrc', @@ -758,6 +774,7 @@ local extension = { po = 'po', pot = 'po', pod = 'pod', + filter = 'poefilter', pk = 'poke', ps = 'postscr', epsi = 'postscr', @@ -900,7 +917,9 @@ local extension = { sig = function(path, bufnr) return require('vim.filetype.detect').sig(bufnr) end, - sil = 'sil', + sil = function(path, bufnr) + return require('vim.filetype.detect').sil(bufnr) + end, sim = 'simula', ['s85'] = 'sinda', sin = 'sinda', @@ -950,6 +969,9 @@ local extension = { srec = 'srec', mot = 'srec', ['s19'] = 'srec', + srt = 'srt', + ssa = 'ssa', + ass = 'ssa', st = 'st', imata = 'stata', ['do'] = 'stata', @@ -1002,6 +1024,8 @@ local extension = { ts = function(path, bufnr) return M.getlines(bufnr, 1):find('<%?xml') and 'xml' or 'typescript' end, + mts = 'typescript', + cts = 'typescript', tsx = 'typescriptreact', uc = 'uc', uit = 'uil', @@ -1011,6 +1035,12 @@ local extension = { dsm = 'vb', ctl = 'vb', vbs = 'vb', + vdf = 'vdf', + vdmpp = 'vdmpp', + vpp = 'vdmpp', + vdmrt = 'vdmrt', + vdmsl = 'vdmsl', + vdm = 'vdmsl', vr = 'vera', vri = 'vera', vrh = 'vera', @@ -1278,7 +1308,6 @@ local filename = { WORKSPACE = 'bzl', BUILD = 'bzl', ['cabal.project'] = 'cabalproject', - [vim.env.HOME .. '/cabal.config'] = 'cabalconfig', ['cabal.config'] = 'cabalconfig', calendar = 'calendar', catalog = 'catalog', @@ -1371,6 +1400,8 @@ local filename = { ['EDIT_DESCRIPTION'] = 'gitcommit', ['.gitconfig'] = 'gitconfig', ['.gitmodules'] = 'gitconfig', + ['.gitattributes'] = 'gitattributes', + ['.gitignore'] = 'gitignore', ['gitolite.conf'] = 'gitolite', ['git-rebase-todo'] = 'gitrebase', gkrellmrc = 'gkrellmrc', @@ -1427,6 +1458,7 @@ local filename = { ['.sawfishrc'] = 'lisp', ['/etc/login.access'] = 'loginaccess', ['/etc/login.defs'] = 'logindefs', + ['.luacheckrc'] = 'lua', ['lynx.cfg'] = 'lynx', ['m3overrides'] = 'm3build', ['m3makefile'] = 'm3build', @@ -1472,6 +1504,8 @@ local filename = { ['/etc/shadow-'] = 'passwd', ['/etc/shadow'] = 'passwd', ['/etc/passwd.edit'] = 'passwd', + ['latexmkrc'] = 'perl', + ['.latexmkrc'] = 'perl', ['pf.conf'] = 'pf', ['main.cf'] = 'pfmain', pinerc = 'pine', @@ -1684,6 +1718,7 @@ local pattern = { ['.*/meta%-.*/conf/.*%.conf'] = 'bitbake', ['bzr_log%..*'] = 'bzr', ['.*enlightenment/.*%.cfg'] = 'c', + ['${HOME}/cabal%.config'] = 'cabalconfig', ['cabal%.project%..*'] = starsetf('cabalproject'), ['.*/%.calendar/.*'] = starsetf('calendar'), ['.*/share/calendar/.*/calendar%..*'] = starsetf('calendar'), @@ -1702,7 +1737,7 @@ local pattern = { { priority = -1 }, }, ['[cC]hange[lL]og.*'] = starsetf(function(path, bufnr) - require('vim.filetype.detect').changelog(bufnr) + return require('vim.filetype.detect').changelog(bufnr) end), ['.*%.%.ch'] = 'chill', ['.*%.cmake%.in'] = 'cmake', @@ -1808,26 +1843,21 @@ local pattern = { ['.*/%.config/git/config'] = 'gitconfig', ['.*%.git/config%.worktree'] = 'gitconfig', ['.*%.git/worktrees/.*/config%.worktree'] = 'gitconfig', - ['.*/git/config'] = function(path, bufnr) - if vim.env.XDG_CONFIG_HOME and path:find(vim.env.XDG_CONFIG_HOME .. '/git/config') then - return 'gitconfig' - end - end, + ['${XDG_CONFIG_HOME}/git/config'] = 'gitconfig', + ['.*%.git/info/attributes'] = 'gitattributes', + ['.*/etc/gitattributes'] = 'gitattributes', + ['.*/%.config/git/attributes'] = 'gitattributes', + ['${XDG_CONFIG_HOME}/git/attributes'] = 'gitattributes', + ['.*%.git/info/exclude'] = 'gitignore', + ['.*/%.config/git/ignore'] = 'gitignore', + ['${XDG_CONFIG_HOME}/git/ignore'] = 'gitignore', ['%.gitsendemail%.msg%.......'] = 'gitsendemail', ['gkrellmrc_.'] = 'gkrellmrc', ['.*/usr/.*/gnupg/options%.skel'] = 'gpg', ['.*/%.gnupg/options'] = 'gpg', ['.*/%.gnupg/gpg%.conf'] = 'gpg', - ['.*/options'] = function(path, bufnr) - if vim.env.GNUPGHOME and path:find(vim.env.GNUPGHOME .. '/options') then - return 'gpg' - end - end, - ['.*/gpg%.conf'] = function(path, bufnr) - if vim.env.GNUPGHOME and path:find(vim.env.GNUPGHOME .. '/gpg%.conf') then - return 'gpg' - end - end, + ['${GNUPGHOME}/options'] = 'gpg', + ['${GNUPGHOME}/gpg%.conf'] = 'gpg', ['.*/etc/group'] = 'group', ['.*/etc/gshadow'] = 'group', ['.*/etc/group%.edit'] = 'group', @@ -1841,7 +1871,7 @@ local pattern = { ['.*/etc/grub%.conf'] = 'grub', -- gtkrc* and .gtkrc* ['%.?gtkrc.*'] = starsetf('gtkrc'), - [vim.env.VIMRUNTIME .. '/doc/.*%.txt'] = 'help', + ['${VIMRUNTIME}/doc/.*%.txt'] = 'help', ['hg%-editor%-.*%.txt'] = 'hgcommit', ['.*/etc/host%.conf'] = 'hostconf', ['.*/etc/hosts%.deny'] = 'hostsaccess', @@ -2245,6 +2275,9 @@ end --- Filename patterns can specify an optional priority to resolve cases when a --- file path matches multiple patterns. Higher priorities are matched first. --- When omitted, the priority defaults to 0. +--- A pattern can contain environment variables of the form "${SOME_VAR}" that will +--- be automatically expanded. If the environment variable is not set, the pattern +--- won't be matched. --- --- See $VIMRUNTIME/lua/vim/filetype.lua for more examples. --- @@ -2273,6 +2306,8 @@ end --- ['.*/etc/foo/.*'] = 'fooscript', --- -- Using an optional priority --- ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, +--- -- A pattern containing an environment variable +--- ['${XDG_CONFIG_HOME}/foo/git'] = 'git', --- ['README.(%a+)$'] = function(path, bufnr, ext) --- if ext == 'md' then --- return 'markdown' @@ -2346,8 +2381,28 @@ local function dispatch(ft, path, bufnr, ...) end end +-- Lookup table/cache for patterns that contain an environment variable pattern, e.g. ${SOME_VAR}. +local expand_env_lookup = {} + ---@private local function match_pattern(name, path, tail, pat) + if expand_env_lookup[pat] == nil then + expand_env_lookup[pat] = pat:find('%${') ~= nil + end + if expand_env_lookup[pat] then + local return_early + pat = pat:gsub('%${(%S-)}', function(env) + -- If an environment variable is present in the pattern but not set, there is no match + if not vim.env[env] then + return_early = true + return nil + end + return vim.env[env] + end) + if return_early then + return false + end + end -- If the pattern contains a / match against the full path, otherwise just the tail local fullpat = '^' .. pat .. '$' local matches diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index 2be9dcff88..7fc7f1b7ca 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -1194,6 +1194,19 @@ function M.shell(path, contents, name) return name end +-- Swift Intermediate Language or SILE +function M.sil(bufnr) + for _, line in ipairs(getlines(bufnr, 1, 100)) do + if line:find('^%s*[\\%%]') then + return 'sile' + elseif line:find('^%s*%S') then + return 'sil' + end + end + -- No clue, default to "sil" + return 'sil' +end + -- SMIL or SNMP MIB file function M.smi(bufnr) local line = getlines(bufnr, 1) diff --git a/runtime/lua/vim/fs.lua b/runtime/lua/vim/fs.lua index ce845eda15..7bd635d8b6 100644 --- a/runtime/lua/vim/fs.lua +++ b/runtime/lua/vim/fs.lua @@ -76,8 +76,11 @@ end --- The search can be narrowed to find only files or or only directories by --- specifying {type} to be "file" or "directory", respectively. --- ----@param names (string|table) Names of the files and directories to find. Must ---- be base names, paths and globs are not supported. +---@param names (string|table|fun(name: string): boolean) Names of the files +--- and directories to find. +--- Must be base names, paths and globs are not supported. +--- If a function it is called per file and dir within the +--- traversed directories to test if they match. ---@param opts (table) Optional keyword arguments: --- - path (string): Path to begin searching from. If --- omitted, the current working directory is used. @@ -98,7 +101,7 @@ end function M.find(names, opts) opts = opts or {} vim.validate({ - names = { names, { 's', 't' } }, + names = { names, { 's', 't', 'f' } }, path = { opts.path, 's', true }, upward = { opts.upward, 'b', true }, stop = { opts.stop, 's', true }, @@ -123,18 +126,31 @@ function M.find(names, opts) end if opts.upward then - ---@private - local function test(p) - local t = {} - for _, name in ipairs(names) do - local f = p .. '/' .. name - local stat = vim.loop.fs_stat(f) - if stat and (not opts.type or opts.type == stat.type) then - t[#t + 1] = f + local test + + if type(names) == 'function' then + test = function(p) + local t = {} + for name, type in M.dir(p) do + if names(name) and (not opts.type or opts.type == type) then + table.insert(t, p .. '/' .. name) + end end + return t end + else + test = function(p) + local t = {} + for _, name in ipairs(names) do + local f = p .. '/' .. name + local stat = vim.loop.fs_stat(f) + if stat and (not opts.type or opts.type == stat.type) then + t[#t + 1] = f + end + end - return t + return t + end end for _, match in ipairs(test(path)) do @@ -162,17 +178,25 @@ function M.find(names, opts) break end - for other, type in M.dir(dir) do + for other, type_ in M.dir(dir) do local f = dir .. '/' .. other - for _, name in ipairs(names) do - if name == other and (not opts.type or opts.type == type) then + if type(names) == 'function' then + if names(other) and (not opts.type or opts.type == type_) then if add(f) then return matches end end + else + for _, name in ipairs(names) do + if name == other and (not opts.type or opts.type == type_) then + if add(f) then + return matches + end + end + end end - if type == 'directory' then + if type_ == 'directory' then dirs[#dirs + 1] = f end end diff --git a/runtime/lua/vim/highlight.lua b/runtime/lua/vim/highlight.lua index ddd504a0e0..0fde515bd9 100644 --- a/runtime/lua/vim/highlight.lua +++ b/runtime/lua/vim/highlight.lua @@ -41,7 +41,7 @@ end ---@param start first position (tuple {line,col}) ---@param finish second position (tuple {line,col}) ---@param opts table with options: --- - regtype type of range (:help setreg, default charwise) +-- - regtype type of range (see |setreg()|, default charwise) -- - inclusive boolean indicating whether the range is end-inclusive (default false) -- - priority number indicating priority of highlight (default priorities.user) function M.range(bufnr, ns, higroup, start, finish, opts) diff --git a/runtime/lua/vim/inspect.lua b/runtime/lua/vim/inspect.lua index 0a53fb203b..c232f69590 100644 --- a/runtime/lua/vim/inspect.lua +++ b/runtime/lua/vim/inspect.lua @@ -89,8 +89,38 @@ local function escape(str) ) end +-- List of lua keywords +local luaKeywords = { + ['and'] = true, + ['break'] = true, + ['do'] = true, + ['else'] = true, + ['elseif'] = true, + ['end'] = true, + ['false'] = true, + ['for'] = true, + ['function'] = true, + ['goto'] = true, + ['if'] = true, + ['in'] = true, + ['local'] = true, + ['nil'] = true, + ['not'] = true, + ['or'] = true, + ['repeat'] = true, + ['return'] = true, + ['then'] = true, + ['true'] = true, + ['until'] = true, + ['while'] = true, +} + local function isIdentifier(str) - return type(str) == 'string' and not not str:match('^[_%a][_%a%d]*$') + return type(str) == 'string' + -- identifier must start with a letter and underscore, and be followed by letters, numbers, and underscores + and not not str:match('^[_%a][_%a%d]*$') + -- lua keywords are not valid identifiers + and not luaKeywords[str] end local flr = math.floor diff --git a/runtime/lua/vim/keymap.lua b/runtime/lua/vim/keymap.lua index 219de16b5c..af41794c53 100644 --- a/runtime/lua/vim/keymap.lua +++ b/runtime/lua/vim/keymap.lua @@ -36,17 +36,17 @@ local keymap = {} ---@param lhs string Left-hand side |{lhs}| of the mapping. ---@param rhs string|function Right-hand side |{rhs}| of the mapping. Can also be a Lua function. -- ----@param opts table A table of |:map-arguments|. ---- + Accepts options accepted by the {opts} parameter in |nvim_set_keymap()|, ---- with the following notable differences: ---- - replace_keycodes: Defaults to `true` if "expr" is `true`. ---- - noremap: Always overridden with the inverse of "remap" (see below). ---- + In addition to those options, the table accepts the following keys: ---- - buffer: (number or boolean) Add a mapping to the given buffer. ---- When `0` or `true`, use the current buffer. ---- - remap: (boolean) Make the mapping recursive. ---- This is the inverse of the "noremap" option from |nvim_set_keymap()|. ---- Defaults to `false`. +---@param opts table|nil A table of |:map-arguments|. +--- + Accepts options accepted by the {opts} parameter in |nvim_set_keymap()|, +--- with the following notable differences: +--- - replace_keycodes: Defaults to `true` if "expr" is `true`. +--- - noremap: Always overridden with the inverse of "remap" (see below). +--- + In addition to those options, the table accepts the following keys: +--- - buffer: (number or boolean) Add a mapping to the given buffer. +--- When `0` or `true`, use the current buffer. +--- - remap: (boolean) Make the mapping recursive. +--- This is the inverse of the "noremap" option from |nvim_set_keymap()|. +--- Defaults to `false`. ---@see |nvim_set_keymap()| function keymap.set(mode, lhs, rhs, opts) vim.validate({ @@ -57,7 +57,6 @@ function keymap.set(mode, lhs, rhs, opts) }) opts = vim.deepcopy(opts) or {} - local is_rhs_luaref = type(rhs) == 'function' mode = type(mode) == 'string' and { mode } or mode if opts.expr and opts.replace_keycodes ~= false then @@ -73,7 +72,7 @@ function keymap.set(mode, lhs, rhs, opts) opts.remap = nil end - if is_rhs_luaref then + if type(rhs) == 'function' then opts.callback = rhs rhs = '' end @@ -99,9 +98,9 @@ end --- --- vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 }) --- </pre> ----@param opts table A table of optional arguments: ---- - buffer: (number or boolean) Remove a mapping from the given buffer. ---- When "true" or 0, use the current buffer. +---@param opts table|nil A table of optional arguments: +--- - buffer: (number or boolean) Remove a mapping from the given buffer. +--- When "true" or 0, use the current buffer. ---@see |vim.keymap.set()| --- function keymap.del(modes, lhs, opts) diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index fd64c1a495..199964e24e 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -5,7 +5,6 @@ local protocol = require('vim.lsp.protocol') local util = require('vim.lsp.util') local sync = require('vim.lsp.sync') -local vim = vim local api = vim.api local nvim_err_writeln, nvim_buf_get_lines, nvim_command, nvim_buf_get_option, nvim_exec_autocmds = api.nvim_err_writeln, @@ -289,7 +288,12 @@ local function validate_client_config(config) 'flags.debounce_text_changes must be a number with the debounce time in milliseconds' ) - local cmd, cmd_args = lsp._cmd_parts(config.cmd) + local cmd, cmd_args + if type(config.cmd) == 'function' then + cmd = config.cmd + else + cmd, cmd_args = lsp._cmd_parts(config.cmd) + end local offset_encoding = valid_encodings.UTF16 if config.offset_encoding then offset_encoding = validate_encoding(config.offset_encoding) @@ -818,7 +822,7 @@ end --- }) --- </pre> --- ---- See |lsp.start_client| for all available options. The most important are: +--- See |vim.lsp.start_client()| for all available options. The most important are: --- --- `name` is an arbitrary name for the LSP client. It should be unique per --- language server. @@ -829,7 +833,7 @@ end --- --- `root_dir` path to the project root. --- By default this is used to decide if an existing client should be re-used. ---- The example above uses |vim.fs.find| and |vim.fs.dirname| to detect the +--- The example above uses |vim.fs.find()| and |vim.fs.dirname()| to detect the --- root by traversing the file system upwards starting --- from the current directory until either a `pyproject.toml` or `setup.py` --- file is found. @@ -844,26 +848,35 @@ end --- --- --- To ensure a language server is only started for languages it can handle, ---- make sure to call |vim.lsp.start| within a |FileType| autocmd. +--- make sure to call |vim.lsp.start()| within a |FileType| autocmd. --- Either use |:au|, |nvim_create_autocmd()| or put the call in a --- `ftplugin/<filetype_name>.lua` (See |ftplugin-name|) --- ----@param config table Same configuration as documented in |lsp.start_client()| +---@param config table Same configuration as documented in |vim.lsp.start_client()| ---@param opts nil|table 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 re-uses a client if name --- and root_dir matches. ----@return number client_id +--- - bufnr (number) +--- Buffer handle to attach to if starting or re-using a +--- client (0 for current). +---@return number|nil client_id function lsp.start(config, opts) opts = opts or {} local reuse_client = opts.reuse_client or function(client, conf) return client.config.root_dir == conf.root_dir and client.name == conf.name end - config.name = config.name or (config.cmd[1] and vim.fs.basename(config.cmd[1])) or nil - local bufnr = api.nvim_get_current_buf() + config.name = config.name + if not config.name and type(config.cmd) == 'table' then + config.name = config.cmd[1] and vim.fs.basename(config.cmd[1]) or nil + end + local bufnr = opts.bufnr + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end for _, clients in ipairs({ uninitialized_clients, lsp.get_active_clients() }) do for _, client in pairs(clients) do if reuse_client(client, config) then @@ -893,8 +906,13 @@ end --- The following parameters describe fields in the {config} table. --- --- ----@param cmd: (required, string or list treated like |jobstart()|) Base command ---- that initiates the LSP client. +---@param cmd: (table|string|fun(dispatchers: table):table) command string or +--- list treated like |jobstart()|. The command must launch the language server +--- process. `cmd` can also be a function that creates an RPC client. +--- The function receives a dispatchers table and must return a table with the +--- functions `request`, `notify`, `is_closing` and `terminate` +--- See |vim.lsp.rpc.request()| and |vim.lsp.rpc.notify()| +--- For TCP there is a built-in rpc client factory: |vim.lsp.rpc.connect()| --- ---@param cmd_cwd: (string, default=|getcwd()|) Directory to launch --- the `cmd` process. Not related to `root_dir`. @@ -950,7 +968,7 @@ end ---@param on_error Callback with parameters (code, ...), invoked --- when the client operation throws an error. `code` is a number describing --- the error. Other arguments may be passed depending on the error kind. See ---- |vim.lsp.rpc.client_errors| for possible errors. +--- `vim.lsp.rpc.client_errors` for possible errors. --- Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name. --- ---@param before_init Callback with parameters (initialize_params, config) @@ -986,8 +1004,8 @@ end --- notifications to the server by the given number in milliseconds. No debounce --- occurs if nil --- - exit_timeout (number|boolean, default false): Milliseconds to wait for server to ---- exit cleanly after sending the 'shutdown' request before sending kill -15. ---- If set to false, nvim exits immediately after sending the 'shutdown' request to the server. +--- exit cleanly after sending the "shutdown" request before sending kill -15. +--- If set to false, nvim exits immediately after sending the "shutdown" request to the server. --- ---@param root_dir string Directory where the LSP --- server will base its workspaceFolders, rootUri, and rootPath @@ -1065,7 +1083,7 @@ function lsp.start_client(config) --- ---@param code (number) Error code ---@param err (...) Other arguments may be passed depending on the error kind - ---@see |vim.lsp.rpc.client_errors| for possible errors. Use + ---@see `vim.lsp.rpc.client_errors` for possible errors. Use ---`vim.lsp.rpc.client_errors[code]` to get a human-friendly name. function dispatch.on_error(code, err) local _ = log.error() @@ -1134,41 +1152,47 @@ function lsp.start_client(config) local namespace = vim.lsp.diagnostic.get_namespace(client_id) vim.diagnostic.reset(namespace, bufnr) - end) - client_ids[client_id] = nil - end - if vim.tbl_isempty(client_ids) then - vim.schedule(function() - unset_defaults(bufnr) + client_ids[client_id] = nil + if vim.tbl_isempty(client_ids) then + unset_defaults(bufnr) + end end) end end - local client = active_clients[client_id] and active_clients[client_id] - or uninitialized_clients[client_id] - active_clients[client_id] = nil - uninitialized_clients[client_id] = nil - -- Client can be absent if executable starts, but initialize fails - -- init/attach won't have happened - if client then - changetracking.reset(client) - end - if code ~= 0 or (signal ~= 0 and signal ~= 15) then - local msg = - string.format('Client %s quit with exit code %s and signal %s', client_id, code, signal) - vim.schedule(function() + -- Schedule the deletion of the client object so that it exists in the execution of LspDetach + -- autocommands + vim.schedule(function() + local client = active_clients[client_id] and active_clients[client_id] + or uninitialized_clients[client_id] + active_clients[client_id] = nil + uninitialized_clients[client_id] = nil + + -- Client can be absent if executable starts, but initialize fails + -- init/attach won't have happened + if client then + changetracking.reset(client) + end + if code ~= 0 or (signal ~= 0 and signal ~= 15) then + local msg = + string.format('Client %s quit with exit code %s and signal %s', client_id, code, signal) vim.notify(msg, vim.log.levels.WARN) - end) - end + end + end) end -- Start the RPC client. - local rpc = lsp_rpc.start(cmd, cmd_args, dispatch, { - cwd = config.cmd_cwd, - env = config.cmd_env, - detached = config.detached, - }) + local rpc + if type(cmd) == 'function' then + rpc = cmd(dispatch) + else + rpc = lsp_rpc.start(cmd, cmd_args, dispatch, { + cwd = config.cmd_cwd, + env = config.cmd_env, + detached = config.detached, + }) + end -- Return nil if client fails to start if not rpc then @@ -1464,14 +1488,13 @@ function lsp.start_client(config) --- you request to stop a client which has previously been requested to --- shutdown, it will automatically escalate and force shutdown. --- - ---@param force (bool, optional) + ---@param force boolean|nil function client.stop(force) - local handle = rpc.handle - if handle:is_closing() then + if rpc.is_closing() then return end if force or not client.initialized or graceful_shutdown_failed then - handle:kill(15) + rpc.terminate() return end -- Sending a signal after a process has exited is acceptable. @@ -1480,7 +1503,7 @@ function lsp.start_client(config) rpc.notify('exit') else -- If there was an error in the shutdown request, then term to be safe. - handle:kill(15) + rpc.terminate() graceful_shutdown_failed = true end end) @@ -1492,7 +1515,7 @@ function lsp.start_client(config) ---@returns (bool) true if client is stopped or in the process of being ---stopped; false otherwise function client.is_stopped() - return rpc.handle:is_closing() + return rpc.is_closing() end ---@private @@ -1627,6 +1650,7 @@ function lsp.buf_attach_client(bufnr, client_id) if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'openClose') then client.notify('textDocument/didClose', params) end + client.attached_buffers[bufnr] = nil end) util.buf_versions[bufnr] = nil all_buffer_active_clients[bufnr] = nil diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 6a070928d9..c593e72d62 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -1,4 +1,3 @@ -local vim = vim local api = vim.api local validate = vim.validate local util = require('vim.lsp.util') @@ -111,7 +110,7 @@ end --- about the context in which a completion was triggered (how it was triggered, --- and by which trigger character, if applicable) --- ----@see |vim.lsp.protocol.constants.CompletionTriggerKind| +---@see vim.lsp.protocol.constants.CompletionTriggerKind function M.completion(context) local params = util.make_position_params() params.context = context @@ -119,35 +118,30 @@ function M.completion(context) end ---@private ---- If there is more than one client that supports the given method, ---- asks the user to select one. --- ----@returns The client that the user selected or nil -local function select_client(method, on_choice) - validate({ - on_choice = { on_choice, 'function', false }, - }) - local clients = vim.tbl_values(vim.lsp.buf_get_clients()) - clients = vim.tbl_filter(function(client) - return client.supports_method(method) - end, clients) - -- better UX when choices are always in the same order (between restarts) - table.sort(clients, function(a, b) - return a.name < b.name - end) - - if #clients > 1 then - vim.ui.select(clients, { - prompt = 'Select a language server:', - format_item = function(client) - return client.name - end, - }, on_choice) - elseif #clients < 1 then - on_choice(nil) - else - on_choice(clients[1]) - end +---@return table {start={row, col}, end={row, col}} using (1, 0) indexing +local function range_from_selection() + -- TODO: Use `vim.region()` instead https://github.com/neovim/neovim/pull/13896 + + -- [bufnum, lnum, col, off]; both row and column 1-indexed + local start = vim.fn.getpos('v') + local end_ = vim.fn.getpos('.') + local start_row = start[2] + local start_col = start[3] + local end_row = end_[2] + local end_col = end_[3] + + -- A user can start visual selection at the end and move backwards + -- Normalize the range to start < end + if start_row == end_row and end_col < start_col then + end_col, start_col = start_col, end_col + elseif end_row < start_row then + start_row, end_row = end_row, start_row + start_col, end_col = end_col, start_col + end + return { + ['start'] = { start_row, start_col - 1 }, + ['end'] = { end_row, end_col - 1 }, + } end --- Formats a buffer using the attached (and optionally filtered) language @@ -184,7 +178,12 @@ end --- Restrict formatting to the client with ID (client.id) matching this field. --- - name (string|nil): --- Restrict formatting to the client with name (client.name) matching this field. - +--- +--- - range (table|nil) Range to format. +--- Table must contain `start` and `end` keys with {row, col} tuples using +--- (1,0) indexing. +--- Defaults to current selection in visual mode +--- Defaults to `nil` in other modes, formatting the full buffer function M.format(options) options = options or {} local bufnr = options.bufnr or api.nvim_get_current_buf() @@ -206,16 +205,32 @@ function M.format(options) vim.notify('[LSP] Format request failed, no matching language servers.') end + local mode = api.nvim_get_mode().mode + local range = options.range + if not range and mode == 'v' or mode == 'V' then + range = range_from_selection() + end + + ---@private + local function set_range(client, params) + if range then + local range_params = + util.make_given_range_params(range.start, range['end'], bufnr, client.offset_encoding) + params.range = range_params.range + end + return params + end + + local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting' if options.async then local do_format do_format = function(idx, client) if not client then return end - local params = util.make_formatting_params(options.formatting_options) - client.request('textDocument/formatting', params, function(...) - local handler = client.handlers['textDocument/formatting'] - or vim.lsp.handlers['textDocument/formatting'] + local params = set_range(client, util.make_formatting_params(options.formatting_options)) + client.request(method, params, function(...) + local handler = client.handlers[method] or vim.lsp.handlers[method] handler(...) do_format(next(clients, idx)) end, bufnr) @@ -224,8 +239,8 @@ function M.format(options) else local timeout_ms = options.timeout_ms or 1000 for _, client in pairs(clients) do - local params = util.make_formatting_params(options.formatting_options) - local result, err = client.request_sync('textDocument/formatting', params, timeout_ms, bufnr) + local params = set_range(client, util.make_formatting_params(options.formatting_options)) + local result, err = client.request_sync(method, params, timeout_ms, bufnr) if result and result.result then util.apply_text_edits(result.result, bufnr, client.offset_encoding) elseif err then @@ -235,138 +250,6 @@ function M.format(options) end end ---- Formats the current buffer. ---- ----@param options (table|nil) Can be used to specify FormattingOptions. ---- Some unspecified options will be automatically derived from the current ---- Neovim options. --- ----@see https://microsoft.github.io/language-server-protocol/specification#textDocument_formatting -function M.formatting(options) - vim.notify_once( - 'vim.lsp.buf.formatting is deprecated. Use vim.lsp.buf.format { async = true } instead', - vim.log.levels.WARN - ) - local params = util.make_formatting_params(options) - local bufnr = api.nvim_get_current_buf() - select_client('textDocument/formatting', function(client) - if client == nil then - return - end - - return client.request('textDocument/formatting', params, nil, bufnr) - end) -end - ---- Performs |vim.lsp.buf.formatting()| synchronously. ---- ---- Useful for running on save, to make sure buffer is formatted prior to being ---- saved. {timeout_ms} is passed on to |vim.lsp.buf_request_sync()|. Example: ---- ---- <pre> ---- autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync() ---- </pre> ---- ----@param options table|nil with valid `FormattingOptions` entries ----@param timeout_ms (number) Request timeout ----@see |vim.lsp.buf.formatting_seq_sync| -function M.formatting_sync(options, timeout_ms) - vim.notify_once( - 'vim.lsp.buf.formatting_sync is deprecated. Use vim.lsp.buf.format instead', - vim.log.levels.WARN - ) - local params = util.make_formatting_params(options) - local bufnr = api.nvim_get_current_buf() - select_client('textDocument/formatting', function(client) - if client == nil then - return - end - - local result, err = client.request_sync('textDocument/formatting', params, timeout_ms, bufnr) - if result and result.result then - util.apply_text_edits(result.result, bufnr, client.offset_encoding) - elseif err then - vim.notify('vim.lsp.buf.formatting_sync: ' .. err, vim.log.levels.WARN) - end - end) -end - ---- Formats the current buffer by sequentially requesting formatting from attached clients. ---- ---- Useful when multiple clients with formatting capability are attached. ---- ---- Since it's synchronous, can be used for running on save, to make sure buffer is formatted ---- prior to being saved. {timeout_ms} is passed on to the |vim.lsp.client| `request_sync` method. ---- Example: ---- <pre> ---- vim.api.nvim_command[[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_seq_sync()]] ---- </pre> ---- ----@param options (table|nil) `FormattingOptions` entries ----@param timeout_ms (number|nil) Request timeout ----@param order (table|nil) List of client names. Formatting is requested from clients ----in the following order: first all clients that are not in the `order` list, then ----the remaining clients in the order as they occur in the `order` list. -function M.formatting_seq_sync(options, timeout_ms, order) - vim.notify_once( - 'vim.lsp.buf.formatting_seq_sync is deprecated. Use vim.lsp.buf.format instead', - vim.log.levels.WARN - ) - local clients = vim.tbl_values(vim.lsp.buf_get_clients()) - local bufnr = api.nvim_get_current_buf() - - -- sort the clients according to `order` - for _, client_name in pairs(order or {}) do - -- if the client exists, move to the end of the list - for i, client in pairs(clients) do - if client.name == client_name then - table.insert(clients, table.remove(clients, i)) - break - end - end - end - - -- loop through the clients and make synchronous formatting requests - for _, client in pairs(clients) do - if vim.tbl_get(client.server_capabilities, 'documentFormattingProvider') then - local params = util.make_formatting_params(options) - local result, err = client.request_sync( - 'textDocument/formatting', - params, - timeout_ms, - api.nvim_get_current_buf() - ) - if result and result.result then - util.apply_text_edits(result.result, bufnr, client.offset_encoding) - elseif err then - vim.notify( - string.format('vim.lsp.buf.formatting_seq_sync: (%s) %s', client.name, err), - vim.log.levels.WARN - ) - end - end - end -end - ---- Formats a given range. ---- ----@param options Table with valid `FormattingOptions` entries. ----@param start_pos ({number, number}, optional) mark-indexed position. ----Defaults to the start of the last visual selection. ----@param end_pos ({number, number}, optional) mark-indexed position. ----Defaults to the end of the last visual selection. -function M.range_formatting(options, start_pos, end_pos) - local params = util.make_given_range_params(start_pos, end_pos) - params.options = util.make_formatting_params(options).options - select_client('textDocument/rangeFormatting', function(client) - if client == nil then - return - end - - return client.request('textDocument/rangeFormatting', params) - end) -end - --- Renames all references to the symbol under the cursor. --- ---@param new_name string|nil If not provided, the user will be prompted for a new @@ -565,14 +448,14 @@ end --- Lists all the call sites of the symbol under the cursor in the --- |quickfix| window. If the symbol can resolve to multiple ---- items, the user can pick one in the |inputlist|. +--- items, the user can pick one in the |inputlist()|. function M.incoming_calls() call_hierarchy('callHierarchy/incomingCalls') end --- Lists all the items that are called by the symbol under the --- cursor in the |quickfix| window. If the symbol can resolve to ---- multiple items, the user can pick one in the |inputlist|. +--- multiple items, the user can pick one in the |inputlist()|. function M.outgoing_calls() call_hierarchy('callHierarchy/outgoingCalls') end @@ -681,9 +564,9 @@ end --- --- Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups --- to be defined or you won't be able to see the actual highlights. ---- |LspReferenceText| ---- |LspReferenceRead| ---- |LspReferenceWrite| +--- |hl-LspReferenceText| +--- |hl-LspReferenceRead| +--- |hl-LspReferenceWrite| function M.document_highlight() local params = util.make_position_params() request('textDocument/documentHighlight', params) @@ -885,23 +768,8 @@ function M.code_action(options) local end_ = assert(options.range['end'], 'range must have a `end` property') params = util.make_given_range_params(start, end_) elseif mode == 'v' or mode == 'V' then - -- [bufnum, lnum, col, off]; both row and column 1-indexed - local start = vim.fn.getpos('v') - local end_ = vim.fn.getpos('.') - local start_row = start[2] - local start_col = start[3] - local end_row = end_[2] - local end_col = end_[3] - - -- A user can start visual selection at the end and move backwards - -- Normalize the range to start < end - if start_row == end_row and end_col < start_col then - end_col, start_col = start_col, end_col - elseif end_row < start_row then - start_row, end_row = end_row, start_row - start_col, end_col = end_col, start_col - end - params = util.make_given_range_params({ start_row, start_col - 1 }, { end_row, end_col - 1 }) + local range = range_from_selection() + params = util.make_given_range_params(range.start, range['end']) else params = util.make_range_params() end @@ -909,34 +777,6 @@ function M.code_action(options) code_action_request(params, options) end ---- Performs |vim.lsp.buf.code_action()| for a given range. ---- ---- ----@param context table|nil `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 filter the code actions. ---- Most language servers support values like `refactor` ---- or `quickfix`. ----@param start_pos ({number, number}, optional) mark-indexed position. ----Defaults to the start of the last visual selection. ----@param end_pos ({number, number}, optional) mark-indexed position. ----Defaults to the end of the last visual selection. -function M.range_code_action(context, start_pos, end_pos) - vim.deprecate('vim.lsp.buf.range_code_action', 'vim.lsp.buf.code_action', '0.9.0') - validate({ context = { context, 't', true } }) - context = context or {} - if not context.diagnostics then - local bufnr = api.nvim_get_current_buf() - context.diagnostics = vim.lsp.diagnostic.get_line_diagnostics(bufnr) - end - local params = util.make_given_range_params(start_pos, end_pos) - params.context = context - code_action_request(params) -end - --- Executes an LSP server command. --- ---@param command_params table A valid `ExecuteCommandParams` object diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 624436bc9b..93fd621161 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -1,7 +1,6 @@ local log = require('vim.lsp.log') local protocol = require('vim.lsp.protocol') local util = require('vim.lsp.util') -local vim = vim local api = vim.api local M = {} @@ -389,7 +388,7 @@ M['textDocument/implementation'] = location_handler ---@param config table Configuration table. --- - border: (default=nil) --- - Add borders to the floating window ---- - See |vim.api.nvim_open_win()| +--- - See |nvim_open_win()| function M.signature_help(_, result, ctx, config) config = config or {} config.focus_id = ctx.method @@ -512,6 +511,52 @@ M['window/showMessage'] = function(_, result, ctx, _) return result end +--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showDocument +M['window/showDocument'] = function(_, result, ctx, _) + local uri = result.uri + + if result.external then + -- TODO(lvimuser): ask the user for confirmation + local cmd + if vim.fn.has('win32') == 1 then + cmd = { 'cmd.exe', '/c', 'start', '""', vim.fn.shellescape(uri) } + elseif vim.fn.has('macunix') == 1 then + cmd = { 'open', vim.fn.shellescape(uri) } + else + cmd = { 'xdg-open', vim.fn.shellescape(uri) } + end + + local ret = vim.fn.system(cmd) + if vim.v.shellerror ~= 0 then + return { + success = false, + error = { + code = protocol.ErrorCodes.UnknownErrorCode, + message = ret, + }, + } + end + + return { success = true } + end + + local client_id = ctx.client_id + local client = vim.lsp.get_client_by_id(client_id) + local client_name = client and client.name or string.format('id=%d', client_id) + if not client then + err_message({ 'LSP[', client_name, '] client has shut down after sending ', ctx.method }) + return vim.NIL + end + + local location = { + uri = uri, + range = result.selection, + } + + local success = util.show_document(location, client.offset_encoding, true, result.takeFocus) + return { success = success or false } +end + -- Add boilerplate error validation and logging for all of these. for k, fn in pairs(M) do M[k] = function(err, result, ctx, config) diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 27da60b4ae..4034753322 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -778,7 +778,7 @@ function protocol.make_client_capabilities() }, }, showDocument = { - support = false, + support = true, }, }, } diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 0926912066..ff62623544 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -1,4 +1,3 @@ -local vim = vim local uv = vim.loop local log = require('vim.lsp.log') local protocol = require('vim.lsp.protocol') @@ -241,8 +240,401 @@ function default_dispatchers.on_error(code, err) local _ = log.error() and log.error('client_error:', client_errors[code], err) end +---@private +local function create_read_loop(handle_body, on_no_chunk, on_error) + local parse_chunk = coroutine.wrap(request_parser_loop) + parse_chunk() + return function(err, chunk) + if err then + on_error(err) + return + end + + if not chunk then + if on_no_chunk then + on_no_chunk() + end + return + end + + while true do + local headers, body = parse_chunk(chunk) + if headers then + handle_body(body) + chunk = '' + else + break + end + end + end +end + +---@class RpcClient +---@field message_index number +---@field message_callbacks table +---@field notify_reply_callbacks table +---@field transport table +---@field dispatchers table + +---@class RpcClient +local Client = {} + +---@private +function Client:encode_and_send(payload) + local _ = log.debug() and log.debug('rpc.send', payload) + if self.transport.is_closing() then + return false + end + local encoded = vim.json.encode(payload) + self.transport.write(format_message_with_content_length(encoded)) + return true +end + +---@private +--- Sends a notification to the LSP server. +---@param method (string) The invoked LSP method +---@param params (table|nil): Parameters for the invoked LSP method +---@returns (bool) `true` if notification could be sent, `false` if not +function Client:notify(method, params) + return self:encode_and_send({ + jsonrpc = '2.0', + method = method, + params = params, + }) +end + +---@private +--- sends an error object to the remote LSP process. +function Client:send_response(request_id, err, result) + return self:encode_and_send({ + id = request_id, + jsonrpc = '2.0', + error = err, + result = result, + }) +end + +---@private +--- Sends a request to the LSP server and runs {callback} upon response. +--- +---@param method (string) The invoked LSP method +---@param params (table|nil) Parameters for the invoked LSP method +---@param callback (function) Callback to invoke +---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending +---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not +function Client:request(method, params, callback, notify_reply_callback) + validate({ + callback = { callback, 'f' }, + notify_reply_callback = { notify_reply_callback, 'f', true }, + }) + self.message_index = self.message_index + 1 + local message_id = self.message_index + local result = self:encode_and_send({ + id = message_id, + jsonrpc = '2.0', + method = method, + params = params, + }) + local message_callbacks = self.message_callbacks + local notify_reply_callbacks = self.notify_reply_callbacks + if result then + if message_callbacks then + message_callbacks[message_id] = schedule_wrap(callback) + else + return false + end + if notify_reply_callback and notify_reply_callbacks then + notify_reply_callbacks[message_id] = schedule_wrap(notify_reply_callback) + end + return result, message_id + else + return false + end +end + +---@private +function Client:on_error(errkind, ...) + assert(client_errors[errkind]) + -- TODO what to do if this fails? + pcall(self.dispatchers.on_error, errkind, ...) +end + +---@private +function Client:pcall_handler(errkind, status, head, ...) + if not status then + self:on_error(errkind, head, ...) + return status, head + end + return status, head, ... +end + +---@private +function Client:try_call(errkind, fn, ...) + return self:pcall_handler(errkind, pcall(fn, ...)) +end + +-- TODO periodically check message_callbacks for old requests past a certain +-- time and log them. This would require storing the timestamp. I could call +-- them with an error then, perhaps. + +---@private +function Client:handle_body(body) + local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } }) + if not ok then + self:on_error(client_errors.INVALID_SERVER_JSON, decoded) + return + end + local _ = log.debug() and log.debug('rpc.receive', decoded) + + if type(decoded.method) == 'string' and decoded.id then + local err + -- Schedule here so that the users functions don't trigger an error and + -- we can still use the result. + schedule(function() + local status, result + status, result, err = self:try_call( + client_errors.SERVER_REQUEST_HANDLER_ERROR, + self.dispatchers.server_request, + decoded.method, + decoded.params + ) + local _ = log.debug() + and log.debug( + 'server_request: callback result', + { status = status, result = result, err = err } + ) + if status then + if result == nil and err == nil then + error( + string.format( + 'method %q: either a result or an error must be sent to the server in response', + decoded.method + ) + ) + end + if err then + assert( + type(err) == 'table', + 'err must be a table. Use rpc_response_error to help format errors.' + ) + local code_name = assert( + protocol.ErrorCodes[err.code], + 'Errors must use protocol.ErrorCodes. Use rpc_response_error to help format errors.' + ) + err.message = err.message or code_name + end + else + -- On an exception, result will contain the error message. + err = rpc_response_error(protocol.ErrorCodes.InternalError, result) + result = nil + end + self:send_response(decoded.id, err, result) + end) + -- This works because we are expecting vim.NIL here + elseif decoded.id and (decoded.result ~= vim.NIL or decoded.error ~= vim.NIL) then + -- We sent a number, so we expect a number. + local result_id = assert(tonumber(decoded.id), 'response id must be a number') + + -- Notify the user that a response was received for the request + local notify_reply_callbacks = self.notify_reply_callbacks + local notify_reply_callback = notify_reply_callbacks and notify_reply_callbacks[result_id] + if notify_reply_callback then + validate({ + notify_reply_callback = { notify_reply_callback, 'f' }, + }) + notify_reply_callback(result_id) + notify_reply_callbacks[result_id] = nil + end + + local message_callbacks = self.message_callbacks + + -- Do not surface RequestCancelled to users, it is RPC-internal. + if decoded.error then + local mute_error = false + if decoded.error.code == protocol.ErrorCodes.RequestCancelled then + local _ = log.debug() and log.debug('Received cancellation ack', decoded) + mute_error = true + end + + if mute_error then + -- Clear any callback since this is cancelled now. + -- This is safe to do assuming that these conditions hold: + -- - The server will not send a result callback after this cancellation. + -- - If the server sent this cancellation ACK after sending the result, the user of this RPC + -- client will ignore the result themselves. + if result_id and message_callbacks then + message_callbacks[result_id] = nil + end + return + end + end + + local callback = message_callbacks and message_callbacks[result_id] + if callback then + message_callbacks[result_id] = nil + validate({ + callback = { callback, 'f' }, + }) + if decoded.error then + decoded.error = setmetatable(decoded.error, { + __tostring = format_rpc_error, + }) + end + self:try_call( + client_errors.SERVER_RESULT_CALLBACK_ERROR, + callback, + decoded.error, + decoded.result + ) + else + self:on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded) + local _ = log.error() and log.error('No callback found for server response id ' .. result_id) + end + elseif type(decoded.method) == 'string' then + -- Notification + self:try_call( + client_errors.NOTIFICATION_HANDLER_ERROR, + self.dispatchers.notification, + decoded.method, + decoded.params + ) + else + -- Invalid server message + self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded) + end +end + +---@private +---@return RpcClient +local function new_client(dispatchers, transport) + local state = { + message_index = 0, + message_callbacks = {}, + notify_reply_callbacks = {}, + transport = transport, + dispatchers = dispatchers, + } + return setmetatable(state, { __index = Client }) +end + +---@private +---@param client RpcClient +local function public_client(client) + local result = {} + + ---@private + function result.is_closing() + return client.transport.is_closing() + end + + ---@private + function result.terminate() + client.transport.terminate() + end + + --- Sends a request to the LSP server and runs {callback} upon response. + --- + ---@param method (string) The invoked LSP method + ---@param params (table|nil) Parameters for the invoked LSP method + ---@param callback (function) Callback to invoke + ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending + ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not + function result.request(method, params, callback, notify_reply_callback) + return client:request(method, params, callback, notify_reply_callback) + end + + --- Sends a notification to the LSP server. + ---@param method (string) The invoked LSP method + ---@param params (table|nil): Parameters for the invoked LSP method + ---@returns (bool) `true` if notification could be sent, `false` if not + function result.notify(method, params) + return client:notify(method, params) + end + + return result +end + +---@private +local function merge_dispatchers(dispatchers) + if dispatchers then + local user_dispatchers = dispatchers + dispatchers = {} + for dispatch_name, default_dispatch in pairs(default_dispatchers) do + local user_dispatcher = user_dispatchers[dispatch_name] + if user_dispatcher then + if type(user_dispatcher) ~= 'function' then + error(string.format('dispatcher.%s must be a function', dispatch_name)) + end + -- server_request is wrapped elsewhere. + if + not (dispatch_name == 'server_request' or dispatch_name == 'on_exit') -- TODO this blocks the loop exiting for some reason. + then + user_dispatcher = schedule_wrap(user_dispatcher) + end + dispatchers[dispatch_name] = user_dispatcher + else + dispatchers[dispatch_name] = default_dispatch + end + end + else + dispatchers = default_dispatchers + end + return dispatchers +end + +--- Create a LSP RPC client factory that connects via TCP to the given host +--- and port +--- +---@param host string +---@param port number +---@return function +local function connect(host, port) + return function(dispatchers) + dispatchers = merge_dispatchers(dispatchers) + local tcp = uv.new_tcp() + local closing = false + local transport = { + write = function(msg) + tcp:write(msg) + end, + is_closing = function() + return closing + end, + terminate = function() + if not closing then + closing = true + tcp:shutdown() + tcp:close() + dispatchers.on_exit(0, 0) + end + end, + } + local client = new_client(dispatchers, transport) + tcp:connect(host, port, function(err) + if err then + vim.schedule(function() + vim.notify( + string.format('Could not connect to %s:%s, reason: %s', host, port, vim.inspect(err)), + vim.log.levels.WARN + ) + end) + return + end + local handle_body = function(body) + client:handle_body(body) + end + tcp:read_start(create_read_loop(handle_body, transport.terminate, function(read_err) + client:on_error(client_errors.READ_ERROR, read_err) + end)) + end) + + return public_client(client) + end +end + --- Starts an LSP server process and create an LSP RPC client object to ---- interact with it. Communication with the server is currently limited to stdio. +--- interact with it. Communication with the spawned process happens via stdio. For +--- communication via TCP, spawn a process manually and use |vim.lsp.rpc.connect()| --- ---@param cmd (string) Command to start the LSP server. ---@param cmd_args (table) List of additional string arguments to pass to {cmd}. @@ -261,11 +653,8 @@ end ---@returns Methods: --- - `notify()` |vim.lsp.rpc.notify()| --- - `request()` |vim.lsp.rpc.request()| ---- ----@returns Members: ---- - {pid} (number) The LSP server's PID. ---- - {handle} A handle for low-level interaction with the LSP server process ---- |vim.loop|. +--- - `is_closing()` returns a boolean indicating if the RPC is closing. +--- - `terminate()` terminates the RPC client. local function start(cmd, cmd_args, dispatchers, extra_spawn_params) local _ = log.info() and log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params }) @@ -278,161 +667,64 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) if extra_spawn_params and extra_spawn_params.cwd then assert(is_dir(extra_spawn_params.cwd), 'cwd must be a directory') end - if dispatchers then - local user_dispatchers = dispatchers - dispatchers = {} - for dispatch_name, default_dispatch in pairs(default_dispatchers) do - local user_dispatcher = user_dispatchers[dispatch_name] - if user_dispatcher then - if type(user_dispatcher) ~= 'function' then - error(string.format('dispatcher.%s must be a function', dispatch_name)) - end - -- server_request is wrapped elsewhere. - if - not (dispatch_name == 'server_request' or dispatch_name == 'on_exit') -- TODO this blocks the loop exiting for some reason. - then - user_dispatcher = schedule_wrap(user_dispatcher) - end - dispatchers[dispatch_name] = user_dispatcher - else - dispatchers[dispatch_name] = default_dispatch - end - end - else - dispatchers = default_dispatchers - end + dispatchers = merge_dispatchers(dispatchers) local stdin = uv.new_pipe(false) local stdout = uv.new_pipe(false) local stderr = uv.new_pipe(false) - - local message_index = 0 - local message_callbacks = {} - local notify_reply_callbacks = {} - local handle, pid - do - ---@private - --- Callback for |vim.loop.spawn()| Closes all streams and runs the `on_exit` dispatcher. - ---@param code (number) Exit code - ---@param signal (number) Signal that was used to terminate (if any) - local function onexit(code, signal) - stdin:close() - stdout:close() - stderr:close() - handle:close() - -- Make sure that message_callbacks/notify_reply_callbacks can be gc'd. - message_callbacks = nil - notify_reply_callbacks = nil - dispatchers.on_exit(code, signal) - end - local spawn_params = { - args = cmd_args, - stdio = { stdin, stdout, stderr }, - detached = not is_win, - } - if extra_spawn_params then - spawn_params.cwd = extra_spawn_params.cwd - spawn_params.env = env_merge(extra_spawn_params.env) - if extra_spawn_params.detached ~= nil then - spawn_params.detached = extra_spawn_params.detached - end - end - handle, pid = uv.spawn(cmd, spawn_params, onexit) - if handle == nil then - stdin:close() - stdout:close() - stderr:close() - local msg = string.format('Spawning language server with cmd: `%s` failed', cmd) - if string.match(pid, 'ENOENT') then - msg = msg - .. '. The language server is either not installed, missing from PATH, or not executable.' - else - msg = msg .. string.format(' with error message: %s', pid) + + local client = new_client(dispatchers, { + write = function(msg) + stdin:write(msg) + end, + is_closing = function() + return handle == nil or handle:is_closing() + end, + terminate = function() + if handle then + handle:kill(15) end - vim.notify(msg, vim.log.levels.WARN) - return - end - end + end, + }) ---@private - --- Encodes {payload} into a JSON-RPC message and sends it to the remote - --- process. - --- - ---@param payload table - ---@returns true if the payload could be scheduled, false if the main event-loop is in the process of closing. - local function encode_and_send(payload) - local _ = log.debug() and log.debug('rpc.send', payload) - if handle == nil or handle:is_closing() then - return false - end - local encoded = vim.json.encode(payload) - stdin:write(format_message_with_content_length(encoded)) - return true - end - - -- FIXME: DOC: Should be placed on the RPC client object returned by - -- `start()` - -- - --- Sends a notification to the LSP server. - ---@param method (string) The invoked LSP method - ---@param params (table): Parameters for the invoked LSP method - ---@returns (bool) `true` if notification could be sent, `false` if not - local function notify(method, params) - return encode_and_send({ - jsonrpc = '2.0', - method = method, - params = params, - }) + --- Callback for |vim.loop.spawn()| Closes all streams and runs the `on_exit` dispatcher. + ---@param code (number) Exit code + ---@param signal (number) Signal that was used to terminate (if any) + local function onexit(code, signal) + stdin:close() + stdout:close() + stderr:close() + handle:close() + dispatchers.on_exit(code, signal) end - - ---@private - --- sends an error object to the remote LSP process. - local function send_response(request_id, err, result) - return encode_and_send({ - id = request_id, - jsonrpc = '2.0', - error = err, - result = result, - }) + local spawn_params = { + args = cmd_args, + stdio = { stdin, stdout, stderr }, + detached = not is_win, + } + if extra_spawn_params then + spawn_params.cwd = extra_spawn_params.cwd + spawn_params.env = env_merge(extra_spawn_params.env) + if extra_spawn_params.detached ~= nil then + spawn_params.detached = extra_spawn_params.detached + end end - - -- FIXME: DOC: Should be placed on the RPC client object returned by - -- `start()` - -- - --- Sends a request to the LSP server and runs {callback} upon response. - --- - ---@param method (string) The invoked LSP method - ---@param params (table) Parameters for the invoked LSP method - ---@param callback (function) Callback to invoke - ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending - ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not - local function request(method, params, callback, notify_reply_callback) - validate({ - callback = { callback, 'f' }, - notify_reply_callback = { notify_reply_callback, 'f', true }, - }) - message_index = message_index + 1 - local message_id = message_index - local result = encode_and_send({ - id = message_id, - jsonrpc = '2.0', - method = method, - params = params, - }) - if result then - if message_callbacks then - message_callbacks[message_id] = schedule_wrap(callback) - else - return false - end - if notify_reply_callback and notify_reply_callbacks then - notify_reply_callbacks[message_id] = schedule_wrap(notify_reply_callback) - end - return result, message_id + handle, pid = uv.spawn(cmd, spawn_params, onexit) + if handle == nil then + stdin:close() + stdout:close() + stderr:close() + local msg = string.format('Spawning language server with cmd: `%s` failed', cmd) + if string.match(pid, 'ENOENT') then + msg = msg + .. '. The language server is either not installed, missing from PATH, or not executable.' else - return false + msg = msg .. string.format(' with error message: %s', pid) end + vim.notify(msg, vim.log.levels.WARN) + return end stderr:read_start(function(_, chunk) @@ -441,195 +733,22 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) end end) - ---@private - local function on_error(errkind, ...) - assert(client_errors[errkind]) - -- TODO what to do if this fails? - pcall(dispatchers.on_error, errkind, ...) - end - ---@private - local function pcall_handler(errkind, status, head, ...) - if not status then - on_error(errkind, head, ...) - return status, head - end - return status, head, ... + local handle_body = function(body) + client:handle_body(body) end - ---@private - local function try_call(errkind, fn, ...) - return pcall_handler(errkind, pcall(fn, ...)) - end - - -- TODO periodically check message_callbacks for old requests past a certain - -- time and log them. This would require storing the timestamp. I could call - -- them with an error then, perhaps. + stdout:read_start(create_read_loop(handle_body, nil, function(err) + client:on_error(client_errors.READ_ERROR, err) + end)) - ---@private - local function handle_body(body) - local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } }) - if not ok then - on_error(client_errors.INVALID_SERVER_JSON, decoded) - return - end - local _ = log.debug() and log.debug('rpc.receive', decoded) - - if type(decoded.method) == 'string' and decoded.id then - local err - -- Schedule here so that the users functions don't trigger an error and - -- we can still use the result. - schedule(function() - local status, result - status, result, err = try_call( - client_errors.SERVER_REQUEST_HANDLER_ERROR, - dispatchers.server_request, - decoded.method, - decoded.params - ) - local _ = log.debug() - and log.debug( - 'server_request: callback result', - { status = status, result = result, err = err } - ) - if status then - if not (result or err) then - -- TODO this can be a problem if `null` is sent for result. needs vim.NIL - error( - string.format( - 'method %q: either a result or an error must be sent to the server in response', - decoded.method - ) - ) - end - if err then - assert( - type(err) == 'table', - 'err must be a table. Use rpc_response_error to help format errors.' - ) - local code_name = assert( - protocol.ErrorCodes[err.code], - 'Errors must use protocol.ErrorCodes. Use rpc_response_error to help format errors.' - ) - err.message = err.message or code_name - end - else - -- On an exception, result will contain the error message. - err = rpc_response_error(protocol.ErrorCodes.InternalError, result) - result = nil - end - send_response(decoded.id, err, result) - end) - -- This works because we are expecting vim.NIL here - elseif decoded.id and (decoded.result ~= vim.NIL or decoded.error ~= vim.NIL) then - -- We sent a number, so we expect a number. - local result_id = assert(tonumber(decoded.id), 'response id must be a number') - - -- Notify the user that a response was received for the request - local notify_reply_callback = notify_reply_callbacks and notify_reply_callbacks[result_id] - if notify_reply_callback then - validate({ - notify_reply_callback = { notify_reply_callback, 'f' }, - }) - notify_reply_callback(result_id) - notify_reply_callbacks[result_id] = nil - end - - -- Do not surface RequestCancelled to users, it is RPC-internal. - if decoded.error then - local mute_error = false - if decoded.error.code == protocol.ErrorCodes.RequestCancelled then - local _ = log.debug() and log.debug('Received cancellation ack', decoded) - mute_error = true - end - - if mute_error then - -- Clear any callback since this is cancelled now. - -- This is safe to do assuming that these conditions hold: - -- - The server will not send a result callback after this cancellation. - -- - If the server sent this cancellation ACK after sending the result, the user of this RPC - -- client will ignore the result themselves. - if result_id and message_callbacks then - message_callbacks[result_id] = nil - end - return - end - end - - local callback = message_callbacks and message_callbacks[result_id] - if callback then - message_callbacks[result_id] = nil - validate({ - callback = { callback, 'f' }, - }) - if decoded.error then - decoded.error = setmetatable(decoded.error, { - __tostring = format_rpc_error, - }) - end - try_call( - client_errors.SERVER_RESULT_CALLBACK_ERROR, - callback, - decoded.error, - decoded.result - ) - else - on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded) - local _ = log.error() - and log.error('No callback found for server response id ' .. result_id) - end - elseif type(decoded.method) == 'string' then - -- Notification - try_call( - client_errors.NOTIFICATION_HANDLER_ERROR, - dispatchers.notification, - decoded.method, - decoded.params - ) - else - -- Invalid server message - on_error(client_errors.INVALID_SERVER_MESSAGE, decoded) - end - end - - local request_parser = coroutine.wrap(request_parser_loop) - request_parser() - stdout:read_start(function(err, chunk) - if err then - -- TODO better handling. Can these be intermittent errors? - on_error(client_errors.READ_ERROR, err) - return - end - -- This should signal that we are done reading from the client. - if not chunk then - return - end - -- Flush anything in the parser by looping until we don't get a result - -- anymore. - while true do - local headers, body = request_parser(chunk) - -- If we successfully parsed, then handle the response. - if headers then - handle_body(body) - -- Set chunk to empty so that we can call request_parser to get - -- anything existing in the parser to flush. - chunk = '' - else - break - end - end - end) - - return { - pid = pid, - handle = handle, - request = request, - notify = notify, - } + return public_client(client) end return { start = start, + connect = connect, rpc_response_error = rpc_response_error, format_rpc_error = format_rpc_error, client_errors = client_errors, + create_read_loop = create_read_loop, } -- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 283099bbcf..b0f9c1660e 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1,6 +1,5 @@ local protocol = require('vim.lsp.protocol') local snippet = require('vim.lsp._snippet') -local vim = vim local validate = vim.validate local api = vim.api local list_extend = vim.list_extend @@ -110,6 +109,15 @@ local function split_lines(value) return split(value, '\n', true) end +---@private +local function create_window_without_focus() + local prev = vim.api.nvim_get_current_win() + vim.cmd.new() + local new = vim.api.nvim_get_current_win() + vim.api.nvim_set_current_win(prev) + return new +end + --- Convert byte index to `encoding` index. --- Convenience wrapper around vim.str_utfindex ---@param line string line to be indexed @@ -459,35 +467,52 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) text = split(text_edit.newText, '\n', true), } - -- Some LSP servers may return +1 range of the buffer content but nvim_buf_set_text can't accept it so we should fix it here. local max = api.nvim_buf_line_count(bufnr) - if max <= e.start_row or max <= e.end_row then - local len = #(get_line(bufnr, max - 1) or '') - if max <= e.start_row then - e.start_row = max - 1 - e.start_col = len - table.insert(e.text, 1, '') - end + -- If the whole edit is after the lines in the buffer we can simply add the new text to the end + -- of the buffer. + if max <= e.start_row then + api.nvim_buf_set_lines(bufnr, max, max, false, e.text) + else + local last_line_len = #(get_line(bufnr, math.min(e.end_row, max - 1)) or '') + -- Some LSP servers may return +1 range of the buffer content but nvim_buf_set_text can't + -- accept it so we should fix it here. if max <= e.end_row then e.end_row = max - 1 - e.end_col = len + e.end_col = last_line_len + has_eol_text_edit = true + else + -- If the replacement is over the end of a line (i.e. e.end_col is out of bounds and the + -- replacement text ends with a newline We can likely assume that the replacement is assumed + -- to be meant to replace the newline with another newline and we need to make sure this + -- doesn't add an extra empty line. E.g. when the last line to be replaced contains a '\r' + -- in the file some servers (clangd on windows) will include that character in the line + -- while nvim_buf_set_text doesn't count it as part of the line. + if + e.end_col > last_line_len + and #text_edit.newText > 0 + and string.sub(text_edit.newText, -1) == '\n' + then + table.remove(e.text, #e.text) + end end - has_eol_text_edit = true - end - api.nvim_buf_set_text(bufnr, e.start_row, e.start_col, e.end_row, e.end_col, e.text) - - -- Fix cursor position. - local row_count = (e.end_row - e.start_row) + 1 - if e.end_row < cursor.row then - cursor.row = cursor.row + (#e.text - row_count) - is_cursor_fixed = true - elseif e.end_row == cursor.row and e.end_col <= cursor.col then - cursor.row = cursor.row + (#e.text - row_count) - cursor.col = #e.text[#e.text] + (cursor.col - e.end_col) - if #e.text == 1 then - cursor.col = cursor.col + e.start_col + -- Make sure we don't go out of bounds for e.end_col + e.end_col = math.min(last_line_len, e.end_col) + + api.nvim_buf_set_text(bufnr, e.start_row, e.start_col, e.end_row, e.end_col, e.text) + + -- Fix cursor position. + local row_count = (e.end_row - e.start_row) + 1 + if e.end_row < cursor.row then + cursor.row = cursor.row + (#e.text - row_count) + is_cursor_fixed = true + elseif e.end_row == cursor.row and e.end_col <= cursor.col then + cursor.row = cursor.row + (#e.text - row_count) + cursor.col = #e.text[#e.text] + (cursor.col - e.end_col) + if #e.text == 1 then + cursor.col = cursor.col + e.start_col + end + is_cursor_fixed = true end - is_cursor_fixed = true end end @@ -755,8 +780,11 @@ local function create_file(change) -- from spec: Overwrite wins over `ignoreIfExists` local fname = vim.uri_to_fname(change.uri) if not opts.ignoreIfExists or opts.overwrite then + vim.fn.mkdir(vim.fs.dirname(fname), 'p') local file = io.open(fname, 'w') - file:close() + if file then + file:close() + end end vim.fn.bufadd(fname) end @@ -887,8 +915,8 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers return end --The active signature. If omitted or the value lies outside the range of - --`signatures` the value defaults to zero or is ignored if `signatures.length - --=== 0`. Whenever possible implementors should make an active decision about + --`signatures` the value defaults to zero or is ignored if `signatures.length == 0`. + --Whenever possible implementors should make an active decision about --the active signature and shouldn't rely on a default value. local contents = {} local active_hl @@ -1036,50 +1064,80 @@ function M.make_floating_popup_options(width, height, opts) } end ---- Jumps to a location. +--- Shows document and optionally jumps to the location. --- ---@param location table (`Location`|`LocationLink`) ----@param offset_encoding string utf-8|utf-16|utf-32 (required) ----@param reuse_win boolean Jump to existing window if buffer is already opened. ----@returns `true` if the jump succeeded -function M.jump_to_location(location, offset_encoding, reuse_win) +---@param offset_encoding "utf-8" | "utf-16" | "utf-32" +---@param 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 +function M.show_document(location, offset_encoding, opts) -- location may be Location or LocationLink local uri = location.uri or location.targetUri if uri == nil then - return + return false end if offset_encoding == nil then - vim.notify_once( - 'jump_to_location must be called with valid offset encoding', - vim.log.levels.WARN - ) + vim.notify_once('show_document must be called with valid offset encoding', vim.log.levels.WARN) end local bufnr = vim.uri_to_bufnr(uri) - -- Save position in jumplist - vim.cmd("normal! m'") - -- Push a new item into tagstack - local from = { vim.fn.bufnr('%'), vim.fn.line('.'), vim.fn.col('.'), 0 } - local items = { { tagname = vim.fn.expand('<cword>'), from = from } } - vim.fn.settagstack(vim.fn.win_getid(), { items = items }, 't') + opts = opts or {} + local focus = vim.F.if_nil(opts.focus, true) + if focus then + -- Save position in jumplist + vim.cmd("normal! m'") - --- Jump to new location (adjusting for UTF-16 encoding of characters) - local win = reuse_win and bufwinid(bufnr) - if win then + -- Push a new item into tagstack + local from = { vim.fn.bufnr('%'), vim.fn.line('.'), vim.fn.col('.'), 0 } + local items = { { tagname = vim.fn.expand('<cword>'), from = from } } + vim.fn.settagstack(vim.fn.win_getid(), { items = items }, 't') + end + + local win = opts.reuse_win and bufwinid(bufnr) + or focus and api.nvim_get_current_win() + or create_window_without_focus() + + api.nvim_buf_set_option(bufnr, 'buflisted', true) + api.nvim_win_set_buf(win, bufnr) + if focus then api.nvim_set_current_win(win) - else - api.nvim_buf_set_option(bufnr, 'buflisted', true) - api.nvim_set_current_buf(bufnr) end + + -- location may be Location or LocationLink local range = location.range or location.targetSelectionRange - local row = range.start.line - local col = get_line_byte_from_position(bufnr, range.start, offset_encoding) - api.nvim_win_set_cursor(0, { row + 1, col }) - -- Open folds under the cursor - vim.cmd('normal! zv') + if range then + --- Jump to new location (adjusting for encoding of characters) + local row = range.start.line + local col = get_line_byte_from_position(bufnr, range.start, offset_encoding) + api.nvim_win_set_cursor(win, { row + 1, col }) + api.nvim_win_call(win, function() + -- Open folds under the cursor + vim.cmd('normal! zv') + end) + end + return true end +--- Jumps to a location. +--- +---@param location table (`Location`|`LocationLink`) +---@param offset_encoding "utf-8" | "utf-16" | "utf-32" +---@param reuse_win boolean Jump to existing window if buffer is already open. +---@return boolean `true` if the jump succeeded +function M.jump_to_location(location, offset_encoding, reuse_win) + if offset_encoding == nil then + vim.notify_once( + 'jump_to_location must be called with valid offset encoding', + vim.log.levels.WARN + ) + end + + return M.show_document(location, offset_encoding, { reuse_win = reuse_win, focus = true }) +end + --- Previews a location in a floating window --- --- behavior depends on type of location: @@ -1484,7 +1542,7 @@ end --- ---@param contents table of lines to show in window ---@param syntax string of syntax to set for opened buffer ----@param opts table with optional fields (additional keys are passed on to |vim.api.nvim_open_win()|) +---@param opts table with optional fields (additional keys are passed on to |nvim_open_win()|) --- - height: (number) height of floating window --- - width: (number) width of floating window --- - wrap: (boolean, default true) wrap long lines @@ -1799,7 +1857,7 @@ end --- CAUTION: Modifies the input in-place! --- ---@param lines (table) list of lines ----@returns (string) filetype or 'markdown' if it was unchanged. +---@returns (string) filetype or "markdown" if it was unchanged. function M.try_trim_markdown_code_blocks(lines) local language_id = lines[1]:match('^```(.*)') if language_id then @@ -1972,7 +2030,7 @@ function M.make_workspace_params(added, removed) end --- Returns indentation size. --- ----@see |shiftwidth| +---@see 'shiftwidth' ---@param bufnr (number|nil): Buffer handle, defaults to current ---@returns (number) indentation size function M.get_effective_tabstop(bufnr) diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index e1b4ed4ea9..f03d608e56 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -6,7 +6,7 @@ -- or the test suite. (Eventually the test suite will be run in a worker process, -- so this wouldn't be a separate case to consider) -local vim = vim or {} +vim = vim or {} --- Returns a deep copy of the given object. Non-table objects are copied as --- in a typical Lua assignment, whereas table objects are copied recursively. @@ -14,8 +14,9 @@ local vim = vim or {} --- same functions as those in the input table. Userdata and threads are not --- copied and will throw an error. --- ----@param orig table Table to copy ----@return table Table of copied keys and (nested) values. +---@generic T: table +---@param orig T Table to copy +---@return T Table of copied keys and (nested) values. function vim.deepcopy(orig) end -- luacheck: no unused vim.deepcopy = (function() local function _id(v) @@ -62,7 +63,7 @@ end)() ---@param s string String to split ---@param sep string Separator or pattern ---@param plain boolean If `true` use `sep` literally (passed to string.find) ----@return function Iterator over the split components +---@return fun():string (function) Iterator over the split components function vim.gsplit(s, sep, plain) vim.validate({ s = { s, 's' }, sep = { sep, 's' }, plain = { plain, 'b', true } }) @@ -99,21 +100,23 @@ end --- --- Examples: --- <pre> ---- split(":aa::b:", ":") --> {'','aa','','b',''} ---- split("axaby", "ab?") --> {'','x','y'} ---- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} ---- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} +--- split(":aa::b:", ":") => {'','aa','','b',''} +--- split("axaby", "ab?") => {'','x','y'} +--- split("x*yz*o", "*", {plain=true}) => {'x','yz','o'} +--- split("|x|y|z|", "|", {trimempty=true}) => {'x', 'y', 'z'} --- </pre> --- ---@see |vim.gsplit()| --- +---@alias split_kwargs {plain: boolean, trimempty: boolean} | boolean | nil +--- ---@param s string String to split ---@param sep string Separator or pattern ----@param kwargs table Keyword arguments: +---@param kwargs? {plain: boolean, trimempty: boolean} (table|nil) Keyword arguments: --- - plain: (boolean) If `true` use `sep` literally (passed to string.find) --- - trimempty: (boolean) If `true` remove empty items from the front --- and back of the list ----@return table List of split components +---@return string[] List of split components function vim.split(s, sep, kwargs) local plain local trimempty = false @@ -156,8 +159,9 @@ end --- ---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua --- ----@param t table Table ----@return table List of keys +---@param t table<T, any> (table) Table +---@generic T: table +---@return T[] (list) List of keys function vim.tbl_keys(t) assert(type(t) == 'table', string.format('Expected table, got %s', type(t))) @@ -171,8 +175,9 @@ end --- Return a list of all values used in a table. --- However, the order of the return table of values is not guaranteed. --- ----@param t table Table ----@return table List of values +---@generic T +---@param t table<any, T> (table) Table +---@return T[] (list) List of values function vim.tbl_values(t) assert(type(t) == 'table', string.format('Expected table, got %s', type(t))) @@ -185,8 +190,9 @@ end --- Apply a function to all values of a table. --- ----@param func function|table Function or callable table ----@param t table Table +---@generic T +---@param func fun(value: T): any (function) Function +---@param t table<any, T> (table) Table ---@return table Table of transformed values function vim.tbl_map(func, t) vim.validate({ func = { func, 'c' }, t = { t, 't' } }) @@ -200,9 +206,10 @@ end --- Filter a table using a predicate function --- ----@param func function|table Function or callable table ----@param t table Table ----@return table Table of filtered values +---@generic T +---@param func fun(value: T): boolean (function) Function +---@param t table<any, T> (table) Table +---@return T[] (table) Table of filtered values function vim.tbl_filter(func, t) vim.validate({ func = { func, 'c' }, t = { t, 't' } }) @@ -302,14 +309,16 @@ end --- Merges recursively two or more map-like tables. --- ----@see |tbl_extend()| +---@see |vim.tbl_extend()| --- ----@param behavior string Decides what to do if a key is found in more than one map: +---@generic T1: table +---@generic T2: table +---@param behavior "error"|"keep"|"force" (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 ----@param ... table Two or more map-like tables ----@return table Merged table +---@param ... T2 Two or more map-like tables +---@return T1|T2 (table) Merged table function vim.tbl_deep_extend(behavior, ...) return tbl_extend(behavior, true, ...) end @@ -405,11 +414,12 @@ end --- ---@see |vim.tbl_extend()| --- ----@param dst table List which will be modified and appended to +---@generic T: table +---@param dst T List which will be modified and appended to ---@param src table List from which values will be inserted ----@param start number Start index on src. Defaults to 1 ----@param finish number Final index on src. Defaults to `#src` ----@return table dst +---@param start? number Start index on src. Defaults to 1 +---@param finish? number Final index on src. Defaults to `#src` +---@return T dst function vim.list_extend(dst, src, start, finish) vim.validate({ dst = { dst, 't' }, @@ -504,10 +514,11 @@ end --- Creates a copy of a table containing only elements from start to end (inclusive) --- ----@param list table Table +---@generic T +---@param list T[] (list) Table ---@param start number Start range of slice ---@param finish number End range of slice ----@return table Copy of table sliced from start to finish (inclusive) +---@return T[] (list) Copy of table sliced from start to finish (inclusive) function vim.list_slice(list, start, finish) local new_list = {} for i = start or 1, finish or #list do @@ -715,5 +726,30 @@ function vim.is_callable(f) return type(m.__call) == 'function' end +--- Creates a table whose members are automatically created when accessed, if they don't already +--- exist. +--- +--- They mimic defaultdict in python. +--- +--- If {create} is `nil`, this will create a defaulttable whose constructor function is +--- this function, effectively allowing to create nested tables on the fly: +--- +--- <pre> +--- local a = vim.defaulttable() +--- a.b.c = 1 +--- </pre> +--- +---@param create function|nil The function called to create a missing value. +---@return table Empty table with metamethod +function vim.defaulttable(create) + create = create or vim.defaulttable + return setmetatable({}, { + __index = function(tbl, key) + rawset(tbl, key, create()) + return rawget(tbl, key) + end, + }) +end + return vim -- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/treesitter.lua b/runtime/lua/vim/treesitter.lua index 70f2c425ed..6cd00516bf 100644 --- a/runtime/lua/vim/treesitter.lua +++ b/runtime/lua/vim/treesitter.lua @@ -3,10 +3,7 @@ local query = require('vim.treesitter.query') local language = require('vim.treesitter.language') local LanguageTree = require('vim.treesitter.languagetree') --- TODO(bfredl): currently we retain parsers for the lifetime of the buffer. --- Consider use weak references to release parser if all plugins are done with --- it. -local parsers = {} +local parsers = setmetatable({}, { __mode = 'v' }) local M = vim.tbl_extend('error', query, language) @@ -28,13 +25,15 @@ setmetatable(M, { end, }) ---- Creates a new parser. +--- Creates a new parser --- ---- It is not recommended to use this, use vim.treesitter.get_parser() instead. +--- It is not recommended to use this; use |get_parser()| instead. --- ----@param bufnr The buffer the parser will be tied to ----@param lang The language of the parser ----@param opts Options to pass to the created language tree +---@param bufnr string Buffer the parser will be tied to (0 for current buffer) +---@param lang string Language of the parser +---@param opts (table|nil) Options to pass to the created language tree +--- +---@return LanguageTree |LanguageTree| object to use for parsing function M._create_parser(bufnr, lang, opts) language.require_language(lang) if bufnr == 0 then @@ -74,16 +73,15 @@ function M._create_parser(bufnr, lang, opts) return self end ---- Gets the parser for this bufnr / ft combination. +--- Returns the parser for a specific buffer and filetype and attaches it to the buffer --- ---- If needed this will create the parser. ---- Unconditionally attach the provided callback +--- If needed, this will create the parser. --- ----@param bufnr The buffer the parser should be tied to ----@param lang The filetype of this parser ----@param opts Options object to pass to the created language tree +---@param bufnr (number|nil) Buffer the parser should be tied to (default: current buffer) +---@param lang (string|nil) Filetype of this parser (default: buffer filetype) +---@param opts (table|nil) Options to pass to the created language tree --- ----@returns The parser +---@return LanguageTree |LanguageTree| object to use for parsing function M.get_parser(bufnr, lang, opts) opts = opts or {} @@ -103,11 +101,13 @@ function M.get_parser(bufnr, lang, opts) return parsers[bufnr] end ---- Gets a string parser +--- Returns a string parser +--- +---@param str string Text to parse +---@param lang string Language of this string +---@param opts (table|nil) Options to pass to the created language tree --- ----@param str The string to parse ----@param lang The language of this string ----@param opts Options to pass to the created language tree +---@return LanguageTree |LanguageTree| object to use for parsing function M.get_string_parser(str, lang, opts) vim.validate({ str = { str, 'string' }, @@ -118,4 +118,233 @@ function M.get_string_parser(str, lang, opts) return LanguageTree.new(str, lang, opts) end +--- Determines whether a node is the ancestor of another +--- +---@param dest userdata Possible ancestor |tsnode| +---@param source userdata Possible descendant |tsnode| +--- +---@return boolean True if {dest} is an ancestor of {source} +function M.is_ancestor(dest, source) + if not (dest and source) then + return false + end + + local current = source + while current ~= nil do + if current == dest then + return true + end + + current = current:parent() + end + + return false +end + +--- Returns the node's range or an unpacked range table +--- +---@param node_or_range (userdata|table) |tsnode| or table of positions +--- +---@return table `{ start_row, start_col, end_row, end_col }` +function M.get_node_range(node_or_range) + if type(node_or_range) == 'table' then + return unpack(node_or_range) + else + return node_or_range:range() + end +end + +--- Determines whether (line, col) position is in node range +--- +---@param node userdata |tsnode| defining the range +---@param line number Line (0-based) +---@param col number Column (0-based) +--- +---@return boolean True if the position is in node range +function M.is_in_node_range(node, line, col) + local start_line, start_col, end_line, end_col = M.get_node_range(node) + if line >= start_line and line <= end_line then + if line == start_line and line == end_line then + return col >= start_col and col < end_col + elseif line == start_line then + return col >= start_col + elseif line == end_line then + return col < end_col + else + return true + end + else + return false + end +end + +--- Determines if a node contains a range +--- +---@param node userdata |tsnode| +---@param range table +--- +---@return boolean True if the {node} contains the {range} +function M.node_contains(node, range) + local start_row, start_col, end_row, end_col = node:range() + local start_fits = start_row < range[1] or (start_row == range[1] and start_col <= range[2]) + local end_fits = end_row > range[3] or (end_row == range[3] and end_col >= range[4]) + + return start_fits and end_fits +end + +--- Returns a list of highlight captures at the given position +--- +--- Each capture is represented by a table containing the capture name as a string as +--- well as a table of metadata (`priority`, `conceal`, ...; empty if none are defined). +--- +---@param bufnr number Buffer number (0 for current buffer) +---@param row number Position row +---@param col number Position column +--- +---@return table[] List of captures `{ capture = "capture name", metadata = { ... } }` +function M.get_captures_at_pos(bufnr, row, col) + if bufnr == 0 then + bufnr = a.nvim_get_current_buf() + end + local buf_highlighter = M.highlighter.active[bufnr] + + if not buf_highlighter then + return {} + end + + local matches = {} + + buf_highlighter.tree:for_each_tree(function(tstree, tree) + if not tstree then + return + end + + local root = tstree:root() + local root_start_row, _, root_end_row, _ = root:range() + + -- Only worry about trees within the line range + if root_start_row > row or root_end_row < row then + return + end + + local q = buf_highlighter:get_query(tree:lang()) + + -- Some injected languages may not have highlight queries. + if not q:query() then + return + end + + local iter = q:query():iter_captures(root, buf_highlighter.bufnr, row, row + 1) + + for capture, node, metadata in iter do + if M.is_in_node_range(node, row, col) then + local c = q._query.captures[capture] -- name of the capture in the query + if c ~= nil then + table.insert(matches, { capture = c, metadata = metadata }) + end + end + end + end, true) + return matches +end + +--- Returns a list of highlight capture names under the cursor +--- +---@param winnr (number|nil) Window handle or 0 for current window (default) +--- +---@return string[] List of capture names +function M.get_captures_at_cursor(winnr) + winnr = winnr or 0 + local bufnr = a.nvim_win_get_buf(winnr) + local cursor = a.nvim_win_get_cursor(winnr) + + local data = M.get_captures_at_pos(bufnr, cursor[1] - 1, cursor[2]) + + local captures = {} + + for _, capture in ipairs(data) do + table.insert(captures, capture.capture) + end + + return captures +end + +--- Returns the smallest named node at the given position +--- +---@param bufnr number Buffer number (0 for current buffer) +---@param row number Position row +---@param col number Position column +---@param opts table Optional keyword arguments: +--- - ignore_injections boolean Ignore injected languages (default true) +--- +---@return userdata |tsnode| under the cursor +function M.get_node_at_pos(bufnr, row, col, opts) + if bufnr == 0 then + bufnr = a.nvim_get_current_buf() + end + local ts_range = { row, col, row, col } + + local root_lang_tree = M.get_parser(bufnr) + if not root_lang_tree then + return + end + + return root_lang_tree:named_node_for_range(ts_range, opts) +end + +--- Returns the smallest named node under the cursor +--- +---@param winnr (number|nil) Window handle or 0 for current window (default) +--- +---@return string Name of node under the cursor +function M.get_node_at_cursor(winnr) + winnr = winnr or 0 + local bufnr = a.nvim_win_get_buf(winnr) + local cursor = a.nvim_win_get_cursor(winnr) + + return M.get_node_at_pos(bufnr, cursor[1] - 1, cursor[2], { ignore_injections = false }):type() +end + +--- Starts treesitter highlighting for a buffer +--- +--- Can be used in an ftplugin or FileType autocommand. +--- +--- Note: By default, disables regex syntax highlighting, which may be required for some plugins. +--- In this case, add ``vim.bo.syntax = 'on'`` after the call to `start`. +--- +--- Example: +--- <pre> +--- vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex', +--- callback = function(args) +--- vim.treesitter.start(args.buf, 'latex') +--- vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed +--- end +--- }) +--- </pre> +--- +---@param bufnr (number|nil) Buffer to be highlighted (default: current buffer) +---@param lang (string|nil) Language of the parser (default: buffer filetype) +function M.start(bufnr, lang) + bufnr = bufnr or a.nvim_get_current_buf() + + local parser = M.get_parser(bufnr, lang) + + M.highlighter.new(parser) + + vim.b[bufnr].ts_highlight = true +end + +--- Stops treesitter highlighting for a buffer +--- +---@param bufnr (number|nil) Buffer to stop highlighting (default: current buffer) +function M.stop(bufnr) + bufnr = bufnr or a.nvim_get_current_buf() + + if M.highlighter.active[bufnr] then + M.highlighter.active[bufnr]:destroy() + end + + vim.bo[bufnr].syntax = 'on' +end + return M diff --git a/runtime/lua/vim/treesitter/health.lua b/runtime/lua/vim/treesitter/health.lua index 3bd59ca282..4995c80a02 100644 --- a/runtime/lua/vim/treesitter/health.lua +++ b/runtime/lua/vim/treesitter/health.lua @@ -3,7 +3,7 @@ local ts = vim.treesitter --- Lists the parsers currently installed --- ----@return A list of parsers +---@return string[] list of parser files function M.list_parsers() return vim.api.nvim_get_runtime_file('parser/*', true) end diff --git a/runtime/lua/vim/treesitter/highlighter.lua b/runtime/lua/vim/treesitter/highlighter.lua index e27a5fa9c3..83a26aff13 100644 --- a/runtime/lua/vim/treesitter/highlighter.lua +++ b/runtime/lua/vim/treesitter/highlighter.lua @@ -2,6 +2,7 @@ local a = vim.api local query = require('vim.treesitter.query') -- support reload for quick experimentation +---@class TSHighlighter local TSHighlighter = rawget(vim.treesitter, 'TSHighlighter') or {} TSHighlighter.__index = TSHighlighter @@ -12,105 +13,18 @@ TSHighlighterQuery.__index = TSHighlighterQuery local ns = a.nvim_create_namespace('treesitter/highlighter') -local _default_highlights = {} -local _link_default_highlight_once = function(from, to) - if not _default_highlights[from] then - _default_highlights[from] = true - a.nvim_set_hl(0, from, { link = to, default = true }) - end - - return from -end - --- If @definition.special does not exist use @definition instead -local subcapture_fallback = { - __index = function(self, capture) - local rtn - local shortened = capture - while not rtn and shortened do - shortened = shortened:match('(.*)%.') - rtn = shortened and rawget(self, shortened) - end - rawset(self, capture, rtn or '__notfound') - return rtn - end, -} - -TSHighlighter.hl_map = setmetatable({ - ['error'] = 'Error', - ['text.underline'] = 'Underlined', - ['todo'] = 'Todo', - ['debug'] = 'Debug', - - -- Miscs - ['comment'] = 'Comment', - ['punctuation.delimiter'] = 'Delimiter', - ['punctuation.bracket'] = 'Delimiter', - ['punctuation.special'] = 'Delimiter', - - -- Constants - ['constant'] = 'Constant', - ['constant.builtin'] = 'Special', - ['constant.macro'] = 'Define', - ['define'] = 'Define', - ['macro'] = 'Macro', - ['string'] = 'String', - ['string.regex'] = 'String', - ['string.escape'] = 'SpecialChar', - ['character'] = 'Character', - ['character.special'] = 'SpecialChar', - ['number'] = 'Number', - ['boolean'] = 'Boolean', - ['float'] = 'Float', - - -- Functions - ['function'] = 'Function', - ['function.special'] = 'Function', - ['function.builtin'] = 'Special', - ['function.macro'] = 'Macro', - ['parameter'] = 'Identifier', - ['method'] = 'Function', - ['field'] = 'Identifier', - ['property'] = 'Identifier', - ['constructor'] = 'Special', - - -- Keywords - ['conditional'] = 'Conditional', - ['repeat'] = 'Repeat', - ['label'] = 'Label', - ['operator'] = 'Operator', - ['keyword'] = 'Keyword', - ['exception'] = 'Exception', - - ['type'] = 'Type', - ['type.builtin'] = 'Type', - ['type.qualifier'] = 'Type', - ['type.definition'] = 'Typedef', - ['storageclass'] = 'StorageClass', - ['structure'] = 'Structure', - ['include'] = 'Include', - ['preproc'] = 'PreProc', -}, subcapture_fallback) - ----@private -local function is_highlight_name(capture_name) - local firstc = string.sub(capture_name, 1, 1) - return firstc ~= string.lower(firstc) -end - ---@private function TSHighlighterQuery.new(lang, query_string) local self = setmetatable({}, { __index = TSHighlighterQuery }) self.hl_cache = setmetatable({}, { __index = function(table, capture) - local hl, is_vim_highlight = self:_get_hl_from_capture(capture) - if not is_vim_highlight then - hl = _link_default_highlight_once(lang .. hl, hl) + local name = self._query.captures[capture] + local id = 0 + if not vim.startswith(name, '_') then + id = a.nvim_get_hl_id_by_name('@' .. name .. '.' .. lang) end - local id = a.nvim_get_hl_id_by_name(hl) - rawset(table, capture, id) return id end, @@ -130,25 +44,12 @@ function TSHighlighterQuery:query() return self._query end ----@private ---- Get the hl from capture. ---- Returns a tuple { highlight_name: string, is_builtin: bool } -function TSHighlighterQuery:_get_hl_from_capture(capture) - local name = self._query.captures[capture] - - if is_highlight_name(name) then - -- From "Normal.left" only keep "Normal" - return vim.split(name, '.', true)[1], true - else - return TSHighlighter.hl_map[name] or 0, false - end -end - --- Creates a new highlighter using @param tree --- ----@param tree The language tree to use for highlighting ----@param opts Table used to configure the highlighter ---- - queries: Table to overwrite queries used by the highlighter +---@param tree LanguageTree |LanguageTree| parser object to use for highlighting +---@param opts (table|nil) Configuration of the highlighter: +--- - queries table overwrite queries used by the highlighter +---@return TSHighlighter Created highlighter object function TSHighlighter.new(tree, opts) local self = setmetatable({}, TSHighlighter) @@ -187,7 +88,7 @@ function TSHighlighter.new(tree, opts) end end - a.nvim_buf_set_option(self.bufnr, 'syntax', '') + vim.bo[self.bufnr].syntax = '' TSHighlighter.active[self.bufnr] = self @@ -196,9 +97,13 @@ function TSHighlighter.new(tree, opts) -- syntax FileType autocmds. Later on we should integrate with the -- `:syntax` and `set syntax=...` machinery properly. if vim.g.syntax_on ~= 1 then - vim.api.nvim_command('runtime! syntax/synload.vim') + vim.cmd.runtime({ 'syntax/synload.vim', bang = true }) end + a.nvim_buf_call(self.bufnr, function() + vim.opt_local.spelloptions:append('noplainbuffer') + end) + self.tree:parse() return self @@ -246,8 +151,10 @@ function TSHighlighter:on_changedtree(changes) end --- Gets the query used for @param lang ---- ----@param lang A language used by the highlighter. +-- +---@private +---@param lang string Language used by the highlighter. +---@return Query function TSHighlighter:get_query(lang) if not self._queries[lang] then self._queries[lang] = TSHighlighterQuery.new(lang) @@ -257,7 +164,7 @@ function TSHighlighter:get_query(lang) end ---@private -local function on_line_impl(self, buf, line) +local function on_line_impl(self, buf, line, spell) self.tree:for_each_tree(function(tstree, tree) if not tstree then return @@ -294,7 +201,9 @@ local function on_line_impl(self, buf, line) local start_row, start_col, end_row, end_col = node:range() local hl = highlighter_query.hl_cache[capture] - if hl and end_row >= line then + local is_spell = highlighter_query:query().captures[capture] == 'spell' + + if hl and end_row >= line and (not spell or is_spell) then a.nvim_buf_set_extmark(buf, ns, start_row, start_col, { end_line = end_row, end_col = end_col, @@ -302,6 +211,7 @@ local function on_line_impl(self, buf, line) ephemeral = true, priority = tonumber(metadata.priority) or 100, -- Low but leaves room below conceal = metadata.conceal, + spell = is_spell, }) end if start_row > line then @@ -318,7 +228,21 @@ function TSHighlighter._on_line(_, _win, buf, line, _) return end - on_line_impl(self, buf, line) + on_line_impl(self, buf, line, false) +end + +---@private +function TSHighlighter._on_spell_nav(_, _, buf, srow, _, erow, _) + local self = TSHighlighter.active[buf] + if not self then + return + end + + self:reset_highlight_state() + + for row = srow, erow do + on_line_impl(self, buf, row, true) + end end ---@private @@ -345,6 +269,7 @@ a.nvim_set_decoration_provider(ns, { on_buf = TSHighlighter._on_buf, on_win = TSHighlighter._on_win, on_line = TSHighlighter._on_line, + _on_spell_nav = TSHighlighter._on_spell_nav, }) return TSHighlighter diff --git a/runtime/lua/vim/treesitter/language.lua b/runtime/lua/vim/treesitter/language.lua index dfb6f5be84..c92d63b8c4 100644 --- a/runtime/lua/vim/treesitter/language.lua +++ b/runtime/lua/vim/treesitter/language.lua @@ -2,14 +2,16 @@ local a = vim.api local M = {} ---- Asserts that the provided language is installed, and optionally provide a path for the parser +--- Asserts that a parser for the language {lang} is installed. --- ---- Parsers are searched in the `parser` runtime directory. +--- Parsers are searched in the `parser` runtime directory, or the provided {path} --- ----@param lang The language the parser should parse ----@param path Optional path the parser is located at ----@param silent Don't throw an error if language not found -function M.require_language(lang, path, silent) +---@param lang string Language the parser should parse +---@param path (string|nil) Optional path the parser is located at +---@param silent (boolean|nil) Don't throw an error if language not found +---@param symbol_name (string|nil) Internal symbol name for the language to load +---@return boolean If the specified language is installed +function M.require_language(lang, path, silent, symbol_name) if vim._ts_has_language(lang) then return true end @@ -21,7 +23,6 @@ function M.require_language(lang, path, silent) return false end - -- TODO(bfredl): help tag? error("no parser for '" .. lang .. "' language, see :help treesitter-parsers") end path = paths[1] @@ -29,10 +30,10 @@ function M.require_language(lang, path, silent) if silent then return pcall(function() - vim._ts_add_language(path, lang) + vim._ts_add_language(path, lang, symbol_name) end) else - vim._ts_add_language(path, lang) + vim._ts_add_language(path, lang, symbol_name) end return true @@ -42,7 +43,8 @@ end --- --- Inspecting provides some useful information on the language like node names, ... --- ----@param lang The language. +---@param lang string Language +---@return table function M.inspect_language(lang) M.require_language(lang) return vim._ts_inspect_language(lang) diff --git a/runtime/lua/vim/treesitter/languagetree.lua b/runtime/lua/vim/treesitter/languagetree.lua index 4d3b0631a2..e9d70c4204 100644 --- a/runtime/lua/vim/treesitter/languagetree.lua +++ b/runtime/lua/vim/treesitter/languagetree.lua @@ -2,19 +2,35 @@ local a = vim.api local query = require('vim.treesitter.query') local language = require('vim.treesitter.language') +---@class LanguageTree +---@field _callbacks function[] Callback handlers +---@field _children LanguageTree[] Injected languages +---@field _injection_query table Queries defining injected languages +---@field _opts table Options +---@field _parser userdata Parser for language +---@field _regions table List of regions this tree should manage and parse +---@field _lang string Language name +---@field _regions table +---@field _source (number|string) Buffer or string to parse +---@field _trees userdata[] Reference to parsed |tstree| (one for each language) +---@field _valid boolean If the parsed tree is valid + local LanguageTree = {} LanguageTree.__index = LanguageTree ---- Represents a single treesitter parser for a language. ---- The language can contain child languages with in its range, ---- hence the tree. +--- A |LanguageTree| holds the treesitter parser for a given language {lang} used +--- to parse a buffer. As the buffer may contain injected languages, the LanguageTree +--- needs to store parsers for these child languages as well (which in turn may contain +--- child languages themselves, hence the name). --- ----@param source Can be a bufnr or a string of text to parse ----@param lang The language this tree represents ----@param opts Options table ----@param opts.injections A table of language to injection query strings. ---- This is useful for overriding the built-in runtime file ---- searching for the injection language query per language. +---@param source (number|string) Buffer or a string of text to parse +---@param lang string Root language this tree represents +---@param opts (table|nil) Optional keyword arguments: +--- - injections table Mapping language to injection query strings. +--- This is useful for overriding the built-in +--- runtime file searching for the injection language +--- query per language. +---@return LanguageTree |LanguageTree| parser object function LanguageTree.new(source, lang, opts) language.require_language(lang) opts = opts or {} @@ -94,6 +110,9 @@ end --- for the language this tree represents. --- This will run the injection query for this language to --- determine if any child languages should be created. +--- +---@return userdata[] Table of parsed |tstree| +---@return table Change list function LanguageTree:parse() if self._valid then return self._trees @@ -167,10 +186,10 @@ function LanguageTree:parse() return self._trees, changes end ---- Invokes the callback for each LanguageTree and it's children recursively +--- Invokes the callback for each |LanguageTree| and its children recursively --- ----@param fn The function to invoke. This is invoked with arguments (tree: LanguageTree, lang: string) ----@param include_self Whether to include the invoking tree in the results. +---@param fn function(tree: LanguageTree, lang: string) +---@param include_self boolean Whether to include the invoking tree in the results function LanguageTree:for_each_child(fn, include_self) if include_self then fn(self, self._lang) @@ -181,12 +200,11 @@ function LanguageTree:for_each_child(fn, include_self) end end ---- Invokes the callback for each treesitter trees recursively. +--- Invokes the callback for each |LanguageTree| recursively. --- ---- Note, this includes the invoking language tree's trees as well. +--- Note: This includes the invoking tree's child trees as well. --- ----@param fn The callback to invoke. The callback is invoked with arguments ---- (tree: TSTree, languageTree: LanguageTree) +---@param fn function(tree: TSTree, languageTree: LanguageTree) function LanguageTree:for_each_tree(fn) for _, tree in ipairs(self._trees) do fn(tree, self) @@ -197,11 +215,13 @@ function LanguageTree:for_each_tree(fn) end end ---- Adds a child language to this tree. +--- Adds a child language to this |LanguageTree|. --- --- If the language already exists as a child, it will first be removed. --- ----@param lang The language to add. +---@private +---@param lang string Language to add. +---@return LanguageTree Injected |LanguageTree| function LanguageTree:add_child(lang) if self._children[lang] then self:remove_child(lang) @@ -215,9 +235,10 @@ function LanguageTree:add_child(lang) return self._children[lang] end ---- Removes a child language from this tree. +--- Removes a child language from this |LanguageTree|. --- ----@param lang The language to remove. +---@private +---@param lang string Language to remove. function LanguageTree:remove_child(lang) local child = self._children[lang] @@ -229,12 +250,11 @@ function LanguageTree:remove_child(lang) end end ---- Destroys this language tree and all its children. +--- Destroys this |LanguageTree| and all its children. --- --- Any cleanup logic should be performed here. --- ---- Note: ---- This DOES NOT remove this tree from a parent. Instead, +--- Note: This DOES NOT remove this tree from a parent. Instead, --- `remove_child` must be called on the parent to remove it. function LanguageTree:destroy() -- Cleanup here @@ -243,23 +263,24 @@ function LanguageTree:destroy() end end ---- Sets the included regions that should be parsed by this parser. +--- Sets the included regions that should be parsed by this |LanguageTree|. --- A region is a set of nodes and/or ranges that will be parsed in the same context. --- ---- For example, `{ { node1 }, { node2} }` is two separate regions. ---- This will be parsed by the parser in two different contexts... thus resulting +--- For example, `{ { node1 }, { node2} }` contains two separate regions. +--- They will be parsed by the parser in two different contexts, thus resulting --- in two separate trees. --- ---- `{ { node1, node2 } }` is a single region consisting of two nodes. ---- This will be parsed by the parser in a single context... thus resulting +--- On the other hand, `{ { node1, node2 } }` is a single region consisting of +--- two nodes. This will be parsed by the parser in a single context, thus resulting --- in a single tree. --- --- This allows for embedded languages to be parsed together across different --- nodes, which is useful for templating languages like ERB and EJS. --- ---- Note, this call invalidates the tree and requires it to be parsed again. +--- Note: This call invalidates the tree and requires it to be parsed again. --- ----@param regions (table) list of regions this tree should manage and parse. +---@private +---@param regions table List of regions this tree should manage and parse. function LanguageTree:set_included_regions(regions) -- Transform the tables from 4 element long to 6 element long (with byte offset) for _, region in ipairs(regions) do @@ -288,7 +309,7 @@ function LanguageTree:set_included_regions(regions) -- Trees are no longer valid now that we have changed regions. -- TODO(vigoux,steelsojka): Look into doing this smarter so we can use some of the -- old trees for incremental parsing. Currently, this only - -- effects injected languages. + -- affects injected languages. self._trees = {} self:invalidate() end @@ -299,7 +320,7 @@ function LanguageTree:included_regions() end ---@private -local function get_node_range(node, id, metadata) +local function get_range_from_metadata(node, id, metadata) if metadata[id] and metadata[id].range then return metadata[id].range end @@ -362,7 +383,7 @@ function LanguageTree:_get_injections() elseif name == 'combined' then combined = true elseif name == 'content' and #ranges == 0 then - table.insert(ranges, get_node_range(node, id, metadata)) + table.insert(ranges, get_range_from_metadata(node, id, metadata)) -- Ignore any tags that start with "_" -- Allows for other tags to be used in matches elseif string.sub(name, 1, 1) ~= '_' then @@ -371,7 +392,7 @@ function LanguageTree:_get_injections() end if #ranges == 0 then - table.insert(ranges, get_node_range(node, id, metadata)) + table.insert(ranges, get_range_from_metadata(node, id, metadata)) end end end @@ -493,8 +514,8 @@ function LanguageTree:_on_detach(...) self:_do_callback('detach', ...) end ---- Registers callbacks for the parser. ----@param cbs table An |nvim_buf_attach()|-like table argument with the following keys : +--- Registers callbacks for the |LanguageTree|. +---@param 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_changedtree` : a callback that will be called every time the tree has syntactical changes. --- It will only be passed one argument, which is a table of the ranges (as node ranges) that @@ -536,9 +557,10 @@ local function tree_contains(tree, range) return start_fits and end_fits end ---- Determines whether {range} is contained in this language tree +--- Determines whether {range} is contained in the |LanguageTree|. --- ----@param range A range, that is a `{ start_line, start_col, end_line, end_col }` table. +---@param range table `{ start_line, start_col, end_line, end_col }` +---@return boolean function LanguageTree:contains(range) for _, tree in pairs(self._trees) do if tree_contains(tree, range) then @@ -549,9 +571,50 @@ function LanguageTree:contains(range) return false end ---- Gets the appropriate language that contains {range} +--- Gets the tree that contains {range}. +--- +---@param range table `{ start_line, start_col, end_line, end_col }` +---@param opts table|nil Optional keyword arguments: +--- - ignore_injections boolean Ignore injected languages (default true) +---@return userdata|nil Contained |tstree| +function LanguageTree:tree_for_range(range, opts) + opts = opts or {} + local ignore = vim.F.if_nil(opts.ignore_injections, true) + + if not ignore then + for _, child in pairs(self._children) do + for _, tree in pairs(child:trees()) do + if tree_contains(tree, range) then + return tree + end + end + end + end + + for _, tree in pairs(self._trees) do + if tree_contains(tree, range) then + return tree + end + end + + return nil +end + +--- Gets the smallest named node that contains {range}. +--- +---@param range table `{ start_line, start_col, end_line, end_col }` +---@param opts table|nil Optional keyword arguments: +--- - ignore_injections boolean Ignore injected languages (default true) +---@return userdata|nil Found |tsnode| +function LanguageTree:named_node_for_range(range, opts) + local tree = self:tree_for_range(range, opts) + return tree:root():named_descendant_for_range(unpack(range)) +end + +--- Gets the appropriate language that contains {range}. --- ----@param range A text range, see |LanguageTree:contains| +---@param range table `{ start_line, start_col, end_line, end_col }` +---@return LanguageTree Managing {range} function LanguageTree:language_for_range(range) for _, child in pairs(self._children) do if child:contains(range) then diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua index 103e85abfd..7ca7384a88 100644 --- a/runtime/lua/vim/treesitter/query.lua +++ b/runtime/lua/vim/treesitter/query.lua @@ -3,6 +3,11 @@ local language = require('vim.treesitter.language') -- query: pattern matching on trees -- predicate matching is implemented in lua +-- +---@class Query +---@field captures string[] List of captures used in query +---@field info table Contains used queries, predicates, directives +---@field query userdata Parsed query local Query = {} Query.__index = Query @@ -34,11 +39,24 @@ local function safe_read(filename, read_quantifier) return content end +---@private +--- Adds {ilang} to {base_langs}, only if {ilang} is different than {lang} +--- +---@return boolean true If lang == ilang +local function add_included_lang(base_langs, lang, ilang) + if lang == ilang then + return true + end + table.insert(base_langs, ilang) + return false +end + --- Gets the list of files used to make up a query --- ----@param lang The language ----@param query_name The name of the query to load ----@param is_included Internal parameter, most of the time left as `nil` +---@param lang string Language to get query for +---@param query_name string Name of the query to load (e.g., "highlights") +---@param is_included (boolean|nil) Internal parameter, most of the time left as `nil` +---@return string[] query_files List of files to load for given query and language function M.get_query_files(lang, query_name, is_included) local query_path = string.format('queries/%s/%s.scm', lang, query_name) local lang_files = dedupe_files(a.nvim_get_runtime_file(query_path, true)) @@ -47,6 +65,9 @@ function M.get_query_files(lang, query_name, is_included) return {} end + local base_query = nil + local extensions = {} + local base_langs = {} -- Now get the base languages by looking at the first line of every file @@ -55,27 +76,53 @@ function M.get_query_files(lang, query_name, is_included) -- -- {language} ::= {lang} | ({lang}) local MODELINE_FORMAT = '^;+%s*inherits%s*:?%s*([a-z_,()]+)%s*$' + local EXTENDS_FORMAT = '^;+%s*extends%s*$' - for _, file in ipairs(lang_files) do - local modeline = safe_read(file, '*l') + for _, filename in ipairs(lang_files) do + local file, err = io.open(filename, 'r') + if not file then + error(err) + end - if modeline then - local langlist = modeline:match(MODELINE_FORMAT) + local extension = false + for modeline in + function() + return file:read('*l') + end + do + if not vim.startswith(modeline, ';') then + break + end + + local langlist = modeline:match(MODELINE_FORMAT) if langlist then for _, incllang in ipairs(vim.split(langlist, ',', true)) do local is_optional = incllang:match('%(.*%)') if is_optional then if not is_included then - table.insert(base_langs, incllang:sub(2, #incllang - 1)) + if add_included_lang(base_langs, lang, incllang:sub(2, #incllang - 1)) then + extension = true + end end else - table.insert(base_langs, incllang) + if add_included_lang(base_langs, lang, incllang) then + extension = true + end end end + elseif modeline:match(EXTENDS_FORMAT) then + extension = true end end + + if extension then + table.insert(extensions, filename) + elseif base_query == nil then + base_query = filename + end + io.close(file) end local query_files = {} @@ -83,7 +130,8 @@ function M.get_query_files(lang, query_name, is_included) local base_files = M.get_query_files(base_lang, query_name, true) vim.list_extend(query_files, base_files) end - vim.list_extend(query_files, lang_files) + vim.list_extend(query_files, { base_query }) + vim.list_extend(query_files, extensions) return query_files end @@ -109,24 +157,24 @@ local explicit_queries = setmetatable({}, { end, }) ---- Sets the runtime query {query_name} for {lang} +--- Sets the runtime query named {query_name} for {lang} --- --- This allows users to override any runtime files and/or configuration --- set by plugins. --- ----@param lang string: The language to use for the query ----@param query_name string: The name of the query (i.e. "highlights") ----@param text string: The query text (unparsed). +---@param lang string Language to use for the query +---@param query_name string Name of the query (e.g., "highlights") +---@param text string Query text (unparsed). function M.set_query(lang, query_name, text) explicit_queries[lang][query_name] = M.parse_query(lang, text) end --- Returns the runtime query {query_name} for {lang}. --- ----@param lang The language to use for the query ----@param query_name The name of the query (i.e. "highlights") +---@param lang string Language to use for the query +---@param query_name string Name of the query (e.g. "highlights") --- ----@return The corresponding query, parsed. +---@return Query Parsed query function M.get_query(lang, query_name) if explicit_queries[lang][query_name] then return explicit_queries[lang][query_name] @@ -140,12 +188,9 @@ function M.get_query(lang, query_name) end end -local query_cache = setmetatable({}, { - __index = function(tbl, key) - rawset(tbl, key, {}) - return rawget(tbl, key) - end, -}) +local query_cache = vim.defaulttable(function() + return setmetatable({}, { __mode = 'v' }) +end) --- Parse {query} as a string. (If the query is in a file, the caller --- should read the contents into a string before calling). @@ -160,10 +205,10 @@ local query_cache = setmetatable({}, { --- -` info.captures` also points to `captures`. --- - `info.patterns` contains information about predicates. --- ----@param lang string The language ----@param query string A string containing the query (s-expr syntax) +---@param lang string Language to use for the query +---@param query string Query in s-expr syntax --- ----@returns The query +---@return Query Parsed query function M.parse_query(lang, query) language.require_language(lang) local cached = query_cache[lang][query] @@ -181,9 +226,15 @@ end --- Gets the text corresponding to a given node --- ----@param node the node ----@param source The buffer or string from which the node is extracted -function M.get_node_text(node, source) +---@param node userdata |tsnode| +---@param source (number|string) Buffer or string from which the {node} is extracted +---@param opts (table|nil) Optional parameters. +--- - concat: (boolean) Concatenate result in a string (default true) +---@return (string[]|string) +function M.get_node_text(node, source, opts) + opts = opts or {} + local concat = vim.F.if_nil(opts.concat, true) + local start_row, start_col, start_byte = node:start() local end_row, end_col, end_byte = node:end_() @@ -210,7 +261,7 @@ function M.get_node_text(node, source) end end - return table.concat(lines, '\n') + return concat and table.concat(lines, '\n') or lines elseif type(source) == 'string' then return source:sub(start_byte + 1, end_byte) end @@ -367,9 +418,8 @@ local directive_handlers = { --- Adds a new predicate to be used in queries --- ----@param name the name of the predicate, without leading # ----@param handler the handler function to be used ---- signature will be (match, pattern, bufnr, predicate) +---@param name string Name of the predicate, without leading # +---@param handler function(match:string, pattern:string, bufnr:number, predicate:function) function M.add_predicate(name, handler, force) if predicate_handlers[name] and not force then error(string.format('Overriding %s', name)) @@ -385,9 +435,8 @@ end --- can set node level data by using the capture id on the --- metadata table `metadata[capture_id].key = value` --- ----@param name the name of the directive, without leading # ----@param handler the handler function to be used ---- signature will be (match, pattern, bufnr, predicate, metadata) +---@param name string Name of the directive, without leading # +---@param handler function(match:string, pattern:string, bufnr:number, predicate:function, metadata:table) function M.add_directive(name, handler, force) if directive_handlers[name] and not force then error(string.format('Overriding %s', name)) @@ -397,12 +446,13 @@ function M.add_directive(name, handler, force) end --- Lists the currently available directives to use in queries. ----@return The list of supported directives. +---@return string[] List of supported directives. function M.list_directives() return vim.tbl_keys(directive_handlers) end ----@return The list of supported predicates. +--- Lists the currently available predicates to use in queries. +---@return string[] List of supported predicates. function M.list_predicates() return vim.tbl_keys(predicate_handlers) end @@ -489,17 +539,16 @@ end --- Iterate over all captures from all matches inside {node} --- ---- {source} is needed if the query contains predicates, then the caller +--- {source} is needed if the query contains predicates; then the caller --- must ensure to use a freshly parsed tree consistent with the current --- text of the buffer (if relevant). {start_row} and {end_row} can be used to limit --- matches inside a row range (this is typically used with root node ---- as the node, i e to get syntax highlight matches in the current ---- viewport). When omitted the start and end row values are used from the given node. +--- as the {node}, i.e., to get syntax highlight matches in the current +--- viewport). When omitted, the {start} and {end} row values are used from the given node. --- ---- The iterator returns three values, a numeric id identifying the capture, +--- The iterator returns three values: a numeric id identifying the capture, --- the captured node, and metadata from any directives processing the match. --- The following example shows how to get captures by name: ---- --- <pre> --- for id, node, metadata in query:iter_captures(tree:root(), bufnr, first, last) do --- local name = query.captures[id] -- name of the capture in the query @@ -510,13 +559,14 @@ end --- end --- </pre> --- ----@param node The node under which the search will occur ----@param source The source buffer or string to extract text from ----@param start The starting line of the search ----@param stop The stopping line of the search (end-exclusive) +---@param node userdata |tsnode| under which the search will occur +---@param source (number|string) Source buffer or string to extract text from +---@param start number Starting line for the search +---@param stop number Stopping line for the search (end-exclusive) --- ----@returns The matching capture id ----@returns The captured node +---@return number capture Matching capture id +---@return table capture_node Capture for {node} +---@return table metadata for the {capture} function Query:iter_captures(node, source, start, stop) if type(source) == 'number' and source == 0 then source = vim.api.nvim_get_current_buf() @@ -546,14 +596,13 @@ end --- Iterates the matches of self on a given range. --- ---- Iterate over all matches within a node. The arguments are the same as ---- for |query:iter_captures()| but the iterated values are different: +--- Iterate over all matches within a {node}. The arguments are the same as +--- for |Query:iter_captures()| but the iterated values are different: --- an (1-based) index of the pattern in the query, a table mapping --- capture indices to nodes, and metadata from any directives processing the match. ---- If the query has more than one pattern the capture table might be sparse, +--- If the query has more than one pattern, the capture table might be sparse --- and e.g. `pairs()` method should be used over `ipairs`. ---- Here an example iterating over all captures in every match: ---- +--- Here is an example iterating over all captures in every match: --- <pre> --- for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do --- for id, node in pairs(match) do @@ -567,13 +616,14 @@ end --- end --- </pre> --- ----@param node The node under which the search will occur ----@param source The source buffer or string to search ----@param start The starting line of the search ----@param stop The stopping line of the search (end-exclusive) +---@param node userdata |tsnode| under which the search will occur +---@param source (number|string) Source buffer or string to search +---@param start number Starting line for the search +---@param stop number Stopping line for the search (end-exclusive) --- ----@returns The matching pattern id ----@returns The matching match +---@return number pattern id +---@return table match +---@return table metadata function Query:iter_matches(node, source, start, stop) if type(source) == 'number' and source == 0 then source = vim.api.nvim_get_current_buf() diff --git a/runtime/nvim.appdata.xml b/runtime/nvim.appdata.xml index 1464c27694..e8d392ec7d 100644 --- a/runtime/nvim.appdata.xml +++ b/runtime/nvim.appdata.xml @@ -26,6 +26,7 @@ </screenshots> <releases> + <release date="2022-09-30" version="0.8.0"/> <release date="2022-04-15" version="0.7.0"/> <release date="2021-12-31" version="0.6.1"/> <release date="2021-11-30" version="0.6.0"/> diff --git a/runtime/optwin.vim b/runtime/optwin.vim index 02cf573ea3..5f0bee6be4 100644 --- a/runtime/optwin.vim +++ b/runtime/optwin.vim @@ -1,7 +1,7 @@ " These commands create the option window. " " Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2022 Apr 07 +" Last Change: 2022 Oct 02 " If there already is an option window, jump to that one. let buf = bufnr('option-window') @@ -511,6 +511,8 @@ call append("$", "\tto a buffer") call <SID>OptionG("swb", &swb) call append("$", "splitbelow\ta new window is put below the current one") call <SID>BinOptionG("sb", &sb) +call append("$", "splitkeep\ta determines scroll behavior for split windows") +call <SID>BinOptionG("spk", &spk) call append("$", "splitright\ta new window is put right of the current one") call <SID>BinOptionG("spr", &spr) call append("$", "scrollbind\tthis window scrolls together with other bound windows") diff --git a/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim b/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim index 802ebd42b5..bfece6aa72 100644 --- a/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim +++ b/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim @@ -964,14 +964,7 @@ func s:DeleteCommands() nunmap K else " call mapset(s:k_map_saved) - let mode = s:k_map_saved.mode !=# ' ' ? s:k_map_saved.mode : '' - call nvim_set_keymap(mode, 'K', s:k_map_saved.rhs, { - \ 'expr': s:k_map_saved.expr ? v:true : v:false, - \ 'noremap': s:k_map_saved.noremap ? v:true : v:false, - \ 'nowait': s:k_map_saved.nowait ? v:true : v:false, - \ 'script': s:k_map_saved.script ? v:true : v:false, - \ 'silent': s:k_map_saved.silent ? v:true : v:false, - \ }) + call mapset('n', 0, s:k_map_saved) endif unlet s:k_map_saved endif diff --git a/runtime/plugin/man.lua b/runtime/plugin/man.lua new file mode 100644 index 0000000000..4b1528b0cb --- /dev/null +++ b/runtime/plugin/man.lua @@ -0,0 +1,34 @@ +if vim.g.loaded_man ~= nil then + return +end +vim.g.loaded_man = true + +vim.api.nvim_create_user_command('Man', function(params) + local man = require('man') + if params.bang then + man.init_pager() + else + local ok, err = pcall(man.open_page, params.count, params.smods, params.fargs) + if not ok then + vim.notify(man.errormsg or err, vim.log.levels.ERROR) + end + end +end, { + bang = true, + bar = true, + addr = 'other', + nargs = '*', + complete = function(...) + return require('man').man_complete(...) + end, +}) + +local augroup = vim.api.nvim_create_augroup('man', {}) + +vim.api.nvim_create_autocmd('BufReadCmd', { + group = augroup, + pattern = 'man://*', + callback = function(params) + require('man').read_page(vim.fn.matchstr(params.match, 'man://\\zs.*')) + end, +}) diff --git a/runtime/plugin/man.vim b/runtime/plugin/man.vim deleted file mode 100644 index b10677593f..0000000000 --- a/runtime/plugin/man.vim +++ /dev/null @@ -1,15 +0,0 @@ -" Maintainer: Anmol Sethi <hi@nhooyr.io> - -if exists('g:loaded_man') - finish -endif -let g:loaded_man = 1 - -command! -bang -bar -addr=other -complete=customlist,man#complete -nargs=* Man - \ if <bang>0 | call man#init_pager() | - \ else | call man#open_page(<count>, <q-mods>, <f-args>) | endif - -augroup man - autocmd! - autocmd BufReadCmd man://* call man#read_page(matchstr(expand('<amatch>'), 'man://\zs.*')) -augroup END diff --git a/runtime/plugin/matchparen.vim b/runtime/plugin/matchparen.vim index cc4f38f669..ce2225c5f8 100644 --- a/runtime/plugin/matchparen.vim +++ b/runtime/plugin/matchparen.vim @@ -5,8 +5,7 @@ " Exit quickly when: " - this plugin was already loaded (or disabled) " - when 'compatible' is set -" - the "CursorMoved" autocmd event is not available. -if exists("g:loaded_matchparen") || &cp || !exists("##CursorMoved") +if exists("g:loaded_matchparen") || &cp finish endif let g:loaded_matchparen = 1 @@ -20,7 +19,7 @@ endif augroup matchparen " Replace all matchparen autocommands - autocmd! CursorMoved,CursorMovedI,WinEnter * call s:Highlight_Matching_Pair() + autocmd! CursorMoved,CursorMovedI,WinEnter,WinScrolled * call s:Highlight_Matching_Pair() autocmd! WinLeave * call s:Remove_Matches() if exists('##TextChanged') autocmd! TextChanged,TextChangedI * call s:Highlight_Matching_Pair() diff --git a/runtime/queries/c/highlights.scm b/runtime/queries/c/highlights.scm index 260750a85b..33e6df74ab 100644 --- a/runtime/queries/c/highlights.scm +++ b/runtime/queries/c/highlights.scm @@ -101,6 +101,7 @@ [ "(" ")" "[" "]" "{" "}"] @punctuation.bracket (string_literal) @string +(string_literal) @spell (system_lib_string) @string (null) @constant.builtin @@ -148,6 +149,7 @@ (comment) @comment +(comment) @spell ;; Parameters (parameter_declaration diff --git a/runtime/queries/c/injections.scm b/runtime/queries/c/injections.scm new file mode 100644 index 0000000000..7e9e73449d --- /dev/null +++ b/runtime/queries/c/injections.scm @@ -0,0 +1,3 @@ +(preproc_arg) @c + +; (comment) @comment diff --git a/runtime/queries/help/highlights.scm b/runtime/queries/help/highlights.scm new file mode 100644 index 0000000000..6be4e49c81 --- /dev/null +++ b/runtime/queries/help/highlights.scm @@ -0,0 +1,16 @@ +(h1) @text.title +(h2) @text.title +(h3) @text.title +(column_heading) @text.title +(tag + "*" @conceal (#set! conceal "") + text: (_) @label) +(taglink + "|" @conceal (#set! conceal "") + text: (_) @text.reference) +(optionlink + text: (_) @text.literal) +(codespan + "`" @conceal (#set! conceal "") + text: (_) @string) +(argument) @parameter diff --git a/runtime/queries/lua/highlights.scm b/runtime/queries/lua/highlights.scm new file mode 100644 index 0000000000..054d787932 --- /dev/null +++ b/runtime/queries/lua/highlights.scm @@ -0,0 +1,194 @@ +;; Keywords + +"return" @keyword.return + +[ + "goto" + "in" + "local" +] @keyword + +(label_statement) @label + +(break_statement) @keyword + +(do_statement +[ + "do" + "end" +] @keyword) + +(while_statement +[ + "while" + "do" + "end" +] @repeat) + +(repeat_statement +[ + "repeat" + "until" +] @repeat) + +(if_statement +[ + "if" + "elseif" + "else" + "then" + "end" +] @conditional) + +(elseif_statement +[ + "elseif" + "then" + "end" +] @conditional) + +(else_statement +[ + "else" + "end" +] @conditional) + +(for_statement +[ + "for" + "do" + "end" +] @repeat) + +(function_declaration +[ + "function" + "end" +] @keyword.function) + +(function_definition +[ + "function" + "end" +] @keyword.function) + +;; Operators + +[ + "and" + "not" + "or" +] @keyword.operator + +[ + "+" + "-" + "*" + "/" + "%" + "^" + "#" + "==" + "~=" + "<=" + ">=" + "<" + ">" + "=" + "&" + "~" + "|" + "<<" + ">>" + "//" + ".." +] @operator + +;; Punctuations + +[ + ";" + ":" + "," + "." +] @punctuation.delimiter + +;; Brackets + +[ + "(" + ")" + "[" + "]" + "{" + "}" +] @punctuation.bracket + +;; Variables + +(identifier) @variable + +((identifier) @variable.builtin + (#eq? @variable.builtin "self")) + +;; Constants + +((identifier) @constant + (#lua-match? @constant "^[A-Z][A-Z_0-9]*$")) + +(vararg_expression) @constant + +(nil) @constant.builtin + +[ + (false) + (true) +] @boolean + +;; Tables + +(field name: (identifier) @field) + +(dot_index_expression field: (identifier) @field) + +(table_constructor +[ + "{" + "}" +] @constructor) + +;; Functions + +(parameters (identifier) @parameter) + +(function_call name: (identifier) @function.call) +(function_declaration name: (identifier) @function) + +(function_call name: (dot_index_expression field: (identifier) @function.call)) +(function_declaration name: (dot_index_expression field: (identifier) @function)) + +(method_index_expression method: (identifier) @method) + +(function_call + (identifier) @function.builtin + (#any-of? @function.builtin + ;; built-in functions in Lua 5.1 + "assert" "collectgarbage" "dofile" "error" "getfenv" "getmetatable" "ipairs" + "load" "loadfile" "loadstring" "module" "next" "pairs" "pcall" "print" + "rawequal" "rawget" "rawset" "require" "select" "setfenv" "setmetatable" + "tonumber" "tostring" "type" "unpack" "xpcall")) + +;; Others + +(comment) @comment +(comment) @spell + +(hash_bang_line) @comment + +(number) @number + +(string) @string +(string) @spell + +;; Error +(ERROR) @error diff --git a/runtime/queries/lua/injections.scm b/runtime/queries/lua/injections.scm new file mode 100644 index 0000000000..0e67329139 --- /dev/null +++ b/runtime/queries/lua/injections.scm @@ -0,0 +1,22 @@ +((function_call + name: [ + (identifier) @_cdef_identifier + (_ _ (identifier) @_cdef_identifier) + ] + arguments: (arguments (string content: _ @c))) + (#eq? @_cdef_identifier "cdef")) + +((function_call + name: (_) @_vimcmd_identifier + arguments: (arguments (string content: _ @vim))) + (#any-of? @_vimcmd_identifier "vim.cmd" "vim.api.nvim_command" "vim.api.nvim_exec" "vim.api.nvim_cmd")) + +; ((function_call +; name: (_) @_vimcmd_identifier +; arguments: (arguments (string content: _ @query) .)) +; (#eq? @_vimcmd_identifier "vim.treesitter.query.set_query")) + +; ;; highlight string as query if starts with `;; query` +; ((string ("string_content") @query) (#lua-match? @query "^%s*;+%s?query")) + +; (comment) @comment diff --git a/runtime/queries/vim/highlights.scm b/runtime/queries/vim/highlights.scm new file mode 100644 index 0000000000..3d1729b2cd --- /dev/null +++ b/runtime/queries/vim/highlights.scm @@ -0,0 +1,259 @@ +(identifier) @variable +((identifier) @constant + (#lua-match? @constant "^[A-Z][A-Z_0-9]*$")) + +;; Keywords + +[ + "if" + "else" + "elseif" + "endif" +] @conditional + +[ + "try" + "catch" + "finally" + "endtry" + "throw" +] @exception + +[ + "for" + "endfor" + "in" + "while" + "endwhile" + "break" + "continue" +] @repeat + +[ + "function" + "endfunction" +] @keyword.function + +;; Function related +(function_declaration name: (_) @function) +(call_expression function: (identifier) @function) +(parameters (identifier) @parameter) +(default_parameter (identifier) @parameter) + +[ (bang) (spread) ] @punctuation.special + +[ (no_option) (inv_option) (default_option) (option_name) ] @variable.builtin +[ + (scope) + "a:" + "$" +] @namespace + +;; Commands and user defined commands + +[ + "let" + "unlet" + "const" + "call" + "execute" + "normal" + "set" + "setlocal" + "silent" + "echo" + "echomsg" + "autocmd" + "augroup" + "return" + "syntax" + "lua" + "ruby" + "perl" + "python" + "highlight" + "command" + "delcommand" + "comclear" + "colorscheme" + "startinsert" + "stopinsert" + "global" + "runtime" + "wincmd" + "cnext" + "cprevious" + "cNext" + "vertical" + "leftabove" + "aboveleft" + "rightbelow" + "belowright" + "topleft" + "botright" + (unknown_command_name) + "edit" + "enew" + "find" + "ex" + "visual" + "view" +] @keyword +(map_statement cmd: _ @keyword) +(command_name) @function.macro + +;; Syntax command + +(syntax_statement (keyword) @string) +(syntax_statement [ + "enable" + "on" + "off" + "reset" + "case" + "spell" + "foldlevel" + "iskeyword" + "keyword" + "match" + "cluster" + "region" +] @keyword) + +(syntax_argument name: _ @keyword) + +[ + "<buffer>" + "<nowait>" + "<silent>" + "<script>" + "<expr>" + "<unique>" +] @constant.builtin + +(augroup_name) @namespace + +(au_event) @constant +(normal_statement (commands) @constant) + +;; Highlight command + +(hl_attribute + key: _ @property + val: _ @constant) + +(hl_group) @type + +(highlight_statement [ + "default" + "link" + "clear" +] @keyword) + +;; Command command + +(command) @string + +(command_attribute + name: _ @property + val: (behavior + name: _ @constant + val: (identifier)? @function)?) + +;; Edit command +(plus_plus_opt + val: _? @constant) @property +(plus_cmd "+" @property) @property + +;; Runtime command + +(runtime_statement (where) @keyword.operator) + +;; Colorscheme command + +(colorscheme_statement (name) @string) + +;; Literals + +(string_literal) @string @spell +(integer_literal) @number +(float_literal) @float +(comment) @comment @spell +(pattern) @string.special +(pattern_multi) @string.regex +(filename) @string +(heredoc (body) @string) +((heredoc (parameter) @keyword)) +((scoped_identifier + (scope) @_scope . (identifier) @boolean) + (#eq? @_scope "v:") + (#any-of? @boolean "true" "false")) + +;; Operators + +[ + "||" + "&&" + "&" + "+" + "-" + "*" + "/" + "%" + ".." + "is" + "isnot" + "==" + "!=" + ">" + ">=" + "<" + "<=" + "=~" + "!~" + "=" + "+=" + "-=" + "*=" + "/=" + "%=" + ".=" + "..=" +] @operator + +; Some characters have different meanings based on the context +(unary_operation "!" @operator) +(binary_operation "." @operator) + +;; Punctuation + +[ + "(" + ")" + "{" + "}" + "[" + "]" +] @punctuation.bracket + +(field_expression "." @punctuation.delimiter) + +[ + "," + ":" +] @punctuation.delimiter + +(ternary_expression ["?" ":"] @conditional) + +; Options +((set_value) @number + (#match? @number "^[0-9]+(\.[0-9]+)?$")) + +((set_item + option: (option_name) @_option + value: (set_value) @function) + (#any-of? @_option + "tagfunc" "tfu" + "completefunc" "cfu" + "omnifunc" "ofu" + "operatorfunc" "opfunc")) diff --git a/runtime/queries/vim/injections.scm b/runtime/queries/vim/injections.scm new file mode 100644 index 0000000000..e2dea8fe75 --- /dev/null +++ b/runtime/queries/vim/injections.scm @@ -0,0 +1,26 @@ +(lua_statement (script (body) @lua)) +(lua_statement (chunk) @lua) +; (ruby_statement (script (body) @ruby)) +; (ruby_statement (chunk) @ruby) +; (python_statement (script (body) @python)) +; (python_statement (chunk) @python) +;; (perl_statement (script (body) @perl)) +;; (perl_statement (chunk) @perl) + +; (autocmd_statement (pattern) @regex) + +((set_item + option: (option_name) @_option + value: (set_value) @vim) + (#any-of? @_option + "includeexpr" "inex" + "printexpr" "pexpr" + "formatexpr" "fex" + "indentexpr" "inde" + "foldtext" "fdt" + "foldexpr" "fde" + "diffexpr" "dex" + "patchexpr" "pex" + "charconvert" "ccv")) + +; (comment) @comment diff --git a/runtime/syntax/chatito.vim b/runtime/syntax/chatito.vim new file mode 100644 index 0000000000..d89307cf06 --- /dev/null +++ b/runtime/syntax/chatito.vim @@ -0,0 +1,62 @@ +" Vim syntax file +" Language: Chatito +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: *.chatito +" Last Change: 2022 Sep 19 + +if exists('b:current_syntax') + finish +endif + +" Comment +syn keyword chatitoTodo contained TODO FIXME XXX +syn match chatitoComment /^#.*/ contains=chatitoTodo,@Spell +syn match chatitoComment +^//.*+ contains=chatitoTodo,@Spell + +" Import +syn match chatitoImport /^import \+.*$/ transparent contains=chatitoImportKeyword,chatitoImportFile +syn keyword chatitoImportKeyword import contained nextgroup=chatitoImportFile +syn match chatitoImportFile /.*$/ contained skipwhite + +" Intent +syn match chatitoIntent /^%\[[^\]?]\+\]\((.\+)\)\=$/ contains=chatitoArgs + +" Slot +syn match chatitoSlot /^@\[[^\]?#]\+\(#[^\]?#]\+\)\=\]\((.\+)\)\=$/ contains=chatitoArgs,chatitoVariation +syn match chatitoSlot /@\[[^\]?#]\+\(#[^\]?#]\+\)\=?\=\]/ contained contains=chatitoOpt,chatitoVariation + +" Alias +syn match chatitoAlias /^\~\[[^\]?]\+\]\=$/ +syn match chatitoAlias /\~\[[^\]?]\+?\=\]/ contained contains=chatitoOpt + +" Probability +syn match chatitoProbability /\*\[\d\+\(\.\d\+\)\=%\=\]/ contained + +" Optional +syn match chatitoOpt '?' contained + +" Arguments +syn match chatitoArgs /(.\+)/ contained + +" Variation +syn match chatitoVariation /#[^\]?#]\+/ contained + +" Value +syn match chatitoValue /^ \{4\}\zs.\+$/ contains=chatitoProbability,chatitoSlot,chatitoAlias,@Spell + +" Errors +syn match chatitoError /^\t/ + +hi def link chatitoAlias String +hi def link chatitoArgs Special +hi def link chatitoComment Comment +hi def link chatitoError Error +hi def link chatitoImportKeyword Include +hi def link chatitoIntent Statement +hi def link chatitoOpt SpecialChar +hi def link chatitoProbability Number +hi def link chatitoSlot Identifier +hi def link chatitoTodo Todo +hi def link chatitoVariation Special + +let b:current_syntax = 'chatito' diff --git a/runtime/syntax/desktop.vim b/runtime/syntax/desktop.vim index 2c1102238d..461ba855b9 100644 --- a/runtime/syntax/desktop.vim +++ b/runtime/syntax/desktop.vim @@ -3,7 +3,7 @@ " Filenames: *.desktop, *.directory " Maintainer: Eisuke Kawashima ( e.kawaschima+vim AT gmail.com ) " Previous Maintainer: Mikolaj Machowski ( mikmach AT wp DOT pl ) -" Last Change: 2020-06-11 +" Last Change: 2022 Sep 22 " Version Info: desktop.vim 1.5 " References: " - https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.5.html (2020-04-27) @@ -60,10 +60,10 @@ syn match dtLocaleSuffix " Boolean Value {{{2 syn match dtBoolean - \ /^\%(DBusActivatable\|Hidden\|NoDisplay\|PrefersNonDefaultGPU\|StartupNotify\|Terminal\)\s*=\s*\%(true\|false\)/ + \ /^\%(DBusActivatable\|Hidden\|NoDisplay\|PrefersNonDefaultGPU\|SingleMainWindow\|StartupNotify\|Terminal\)\s*=\s*\%(true\|false\)/ \ contains=dtBooleanKey,dtDelim,dtBooleanValue transparent syn keyword dtBooleanKey - \ DBusActivatable Hidden NoDisplay PrefersNonDefaultGPU StartupNotify Terminal + \ DBusActivatable Hidden NoDisplay PrefersNonDefaultGPU SingleMainWindow StartupNotify Terminal \ contained nextgroup=dtDelim if s:desktop_enable_kde diff --git a/runtime/syntax/erlang.vim b/runtime/syntax/erlang.vim index b8cbf07bb2..0b256193ab 100644 --- a/runtime/syntax/erlang.vim +++ b/runtime/syntax/erlang.vim @@ -2,7 +2,7 @@ " Language: Erlang (http://www.erlang.org) " Maintainer: Csaba Hoch <csaba.hoch@gmail.com> " Contributor: Adam Rutkowski <hq@mtod.org> -" Last Update: 2020-May-26 +" Last Update: 2022-Sep-06 " License: Vim license " URL: https://github.com/vim-erlang/vim-erlang-runtime @@ -61,7 +61,8 @@ syn match erlangQuotedAtomModifier '\\\%(\o\{1,3}\|x\x\x\|x{\x\+}\|\^.\|.\)' con syn match erlangModifier '\$\%([^\\]\|\\\%(\o\{1,3}\|x\x\x\|x{\x\+}\|\^.\|.\)\)' " Operators, separators -syn match erlangOperator '==\|=:=\|/=\|=/=\|<\|=<\|>\|>=\|=>\|:=\|++\|--\|=\|!\|<-\|+\|-\|\*\|\/' +syn match erlangOperator '==\|=:=\|/=\|=/=\|<\|=<\|>\|>=\|=>\|:=\|?=\|++\|--\|=\|!\|<-\|+\|-\|\*\|\/' +syn match erlangEqualsBinary '=<<\%(<\)\@!' syn keyword erlangOperator div rem or xor bor bxor bsl bsr and band not bnot andalso orelse syn match erlangBracket '{\|}\|\[\|]\||\|||' syn match erlangPipe '|' @@ -76,7 +77,8 @@ syn match erlangGlobalFuncCall '\<\%(\a[[:alnum:]_@]*\%(\s\|\n\|%.*\n\)*\.\%(\s\ syn match erlangGlobalFuncRef '\<\%(\a[[:alnum:]_@]*\%(\s\|\n\|%.*\n\)*\.\%(\s\|\n\|%.*\n\)*\)*\a[[:alnum:]_@]*\%(\s\|\n\|%.*\n\)*:\%(\s\|\n\|%.*\n\)*\a[[:alnum:]_@]*\>\%(\%(\s\|\n\|%.*\n\)*/\)\@=' contains=erlangComment,erlangVariable " Variables, macros, records, maps -syn match erlangVariable '\<[A-Z_][[:alnum:]_@]*' +syn match erlangVariable '\<[A-Z][[:alnum:]_@]*' +syn match erlangAnonymousVariable '\<_[[:alnum:]_@]*' syn match erlangMacro '??\=[[:alnum:]_@]\+' syn match erlangMacro '\%(-define(\)\@<=[[:alnum:]_@]\+' syn region erlangQuotedMacro start=/??\=\s*'/ end=/'/ contains=erlangQuotedAtomModifier @@ -92,7 +94,7 @@ syn match erlangBitType '\%(\/\%(\s\|\n\|%.*\n\)*\)\@<=\%(integer\|float\|binary " Constants and Directives syn match erlangUnknownAttribute '^\s*-\%(\s\|\n\|%.*\n\)*\l[[:alnum:]_@]*' contains=erlangComment -syn match erlangAttribute '^\s*-\%(\s\|\n\|%.*\n\)*\%(behaviou\=r\|compile\|export\(_type\)\=\|file\|import\|module\|author\|copyright\|doc\|vsn\|on_load\|optional_callbacks\)\>' contains=erlangComment +syn match erlangAttribute '^\s*-\%(\s\|\n\|%.*\n\)*\%(behaviou\=r\|compile\|export\(_type\)\=\|file\|import\|module\|author\|copyright\|doc\|vsn\|on_load\|optional_callbacks\|feature\)\>' contains=erlangComment syn match erlangInclude '^\s*-\%(\s\|\n\|%.*\n\)*\%(include\|include_lib\)\>' contains=erlangComment syn match erlangRecordDef '^\s*-\%(\s\|\n\|%.*\n\)*record\>' contains=erlangComment syn match erlangDefine '^\s*-\%(\s\|\n\|%.*\n\)*\%(define\|undef\)\>' contains=erlangComment @@ -100,8 +102,8 @@ syn match erlangPreCondit '^\s*-\%(\s\|\n\|%.*\n\)*\%(ifdef\|ifndef\|else\|endif syn match erlangType '^\s*-\%(\s\|\n\|%.*\n\)*\%(spec\|type\|opaque\|callback\)\>' contains=erlangComment " Keywords -syn keyword erlangKeyword after begin case catch cond end fun if let of -syn keyword erlangKeyword receive when try +syn keyword erlangKeyword after begin case catch cond end fun if let of else +syn keyword erlangKeyword receive when try maybe " Build-in-functions (BIFs) syn keyword erlangBIF abs alive apply atom_to_binary atom_to_list contained @@ -174,6 +176,7 @@ hi def link erlangModifier Special " Operators, separators hi def link erlangOperator Operator +hi def link erlangEqualsBinary ErrorMsg hi def link erlangRightArrow Operator if s:old_style hi def link erlangBracket Normal @@ -191,6 +194,7 @@ hi def link erlangLocalFuncRef Normal hi def link erlangGlobalFuncCall Function hi def link erlangGlobalFuncRef Function hi def link erlangVariable Normal +hi def link erlangAnonymousVariable erlangVariable hi def link erlangMacro Normal hi def link erlangQuotedMacro Normal hi def link erlangRecord Normal @@ -203,6 +207,7 @@ hi def link erlangLocalFuncRef Normal hi def link erlangGlobalFuncCall Normal hi def link erlangGlobalFuncRef Normal hi def link erlangVariable Identifier +hi def link erlangAnonymousVariable erlangVariable hi def link erlangMacro Macro hi def link erlangQuotedMacro Macro hi def link erlangRecord Structure diff --git a/runtime/syntax/gdresource.vim b/runtime/syntax/gdresource.vim new file mode 100644 index 0000000000..7e1a2513e2 --- /dev/null +++ b/runtime/syntax/gdresource.vim @@ -0,0 +1,65 @@ +" Vim syntax file for Godot resource (scenes) +" Language: gdresource +" Maintainer: Maxim Kim <habamax@gmail.com> +" Filenames: *.tscn, *.tres +" Website: https://github.com/habamax/vim-gdscript + +if exists("b:current_syntax") + finish +endif + +let s:keepcpo = &cpo +set cpo&vim + +syn match gdResourceNumber "\<0x\%(_\=\x\)\+\>" +syn match gdResourceNumber "\<0b\%(_\=[01]\)\+\>" +syn match gdResourceNumber "\<\d\%(_\=\d\)*\>" +syn match gdResourceNumber "\<\d\%(_\=\d\)*\%(e[+-]\=\d\%(_\=\d\)*\)\=\>" +syn match gdResourceNumber "\<\d\%(_\=\d\)*\.\%(e[+-]\=\d\%(_\=\d\)*\)\=\%(\W\|$\)\@=" +syn match gdResourceNumber "\%(^\|\W\)\@1<=\%(\d\%(_\=\d\)*\)\=\.\d\%(_\=\d\)*\%(e[+-]\=\d\%(_\=\d\)*\)\=\>" + +syn keyword gdResourceKeyword true false + +syn region gdResourceString + \ start=+[uU]\="+ end='"' skip='\\\\\|\\"' + \ contains=@Spell keepend + +" Section +syn region gdResourceSection matchgroup=gdResourceSectionDelimiter + \ start='^\[' end=']\s*$' + \ oneline keepend + \ contains=gdResourceSectionName,gdResourceSectionAttribute + +syn match gdResourceSectionName '\[\@<=\S\+' contained skipwhite +syn match gdResourceSectionAttribute '\S\+\s*=\s*\S\+' + \ skipwhite keepend contained + \ contains=gdResourceSectionAttributeName,gdResourceSectionAttributeValue +syn match gdResourceSectionAttributeName '\S\+\ze\(\s*=\)' skipwhite contained +syn match gdResourceSectionAttributeValue '\(=\s*\)\zs\S\+\ze' skipwhite + \ contained + \ contains=gdResourceString,gdResourceNumber,gdResourceKeyword + + +" Section body +syn match gdResourceAttribute '^\s*\S\+\s*=.*$' + \ skipwhite keepend + \ contains=gdResourceAttributeName,gdResourceAttributeValue + +syn match gdResourceAttributeName '\S\+\ze\(\s*=\)' skipwhite contained +syn match gdResourceAttributeValue '\(=\s*\)\zs.*$' skipwhite + \ contained + \ contains=gdResourceString,gdResourceNumber,gdResourceKeyword + + +hi def link gdResourceNumber Constant +hi def link gdResourceKeyword Constant +hi def link gdResourceSectionName Statement +hi def link gdResourceSectionDelimiter Delimiter +hi def link gdResourceSectionAttributeName Type +hi def link gdResourceAttributeName Identifier +hi def link gdResourceString String + +let b:current_syntax = "gdresource" + +let &cpo = s:keepcpo +unlet s:keepcpo diff --git a/runtime/syntax/gdscript.vim b/runtime/syntax/gdscript.vim new file mode 100644 index 0000000000..48af153513 --- /dev/null +++ b/runtime/syntax/gdscript.vim @@ -0,0 +1,103 @@ +" Vim syntax file for Godot gdscript +" Language: gdscript +" Maintainer: Maxim Kim <habamax@gmail.com> +" Website: https://github.com/habamax/vim-gdscript +" Filenames: *.gd + +if exists("b:current_syntax") + finish +endif + +let s:keepcpo = &cpo +set cpo&vim + +syntax sync maxlines=100 + +syn keyword gdscriptConditional if else elif match +syn keyword gdscriptRepeat for while break continue + +syn keyword gdscriptOperator is as not and or in + +syn match gdscriptBlockStart ":\s*$" + +syn keyword gdscriptKeyword null self owner parent tool +syn keyword gdscriptBoolean false true + +syn keyword gdscriptStatement remote master puppet remotesync mastersync puppetsync sync +syn keyword gdscriptStatement return pass +syn keyword gdscriptStatement static const enum +syn keyword gdscriptStatement breakpoint assert +syn keyword gdscriptStatement onready +syn keyword gdscriptStatement class_name extends + +syn keyword gdscriptType void bool int float String contained +syn match gdscriptType ":\s*\zs\h\w*" contained +syn match gdscriptType "->\s*\zs\h\w*" contained + +syn keyword gdscriptStatement var nextgroup=gdscriptTypeDecl skipwhite +syn keyword gdscriptStatement const nextgroup=gdscriptTypeDecl skipwhite +syn match gdscriptTypeDecl "\h\w*\s*:\s*\h\w*" contains=gdscriptType contained skipwhite +syn match gdscriptTypeDecl "->\s*\h\w*" contains=gdscriptType skipwhite + +syn keyword gdscriptStatement export nextgroup=gdscriptExportTypeDecl skipwhite +syn match gdscriptExportTypeDecl "(.\{-}[,)]" contains=gdscriptOperator,gdscriptType contained skipwhite + +syn keyword gdscriptStatement setget nextgroup=gdscriptSetGet,gdscriptSetGetSeparator skipwhite +syn match gdscriptSetGet "\h\w*" nextgroup=gdscriptSetGetSeparator display contained skipwhite +syn match gdscriptSetGetSeparator "," nextgroup=gdscriptSetGet display contained skipwhite + +syn keyword gdscriptStatement class func signal nextgroup=gdscriptFunctionName skipwhite +syn match gdscriptFunctionName "\h\w*" nextgroup=gdscriptFunctionParams display contained skipwhite +syn match gdscriptFunctionParams "(.*)" contains=gdscriptTypeDecl display contained skipwhite + +syn match gdscriptNode "\$\h\w*\%(/\h\w*\)*" + +syn match gdscriptComment "#.*$" contains=@Spell,gdscriptTodo + +syn region gdscriptString matchgroup=gdscriptQuotes + \ start=+[uU]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1" + \ contains=gdscriptEscape,@Spell + +syn region gdscriptString matchgroup=gdscriptTripleQuotes + \ start=+[uU]\=\z('''\|"""\)+ end="\z1" keepend + \ contains=gdscriptEscape,@Spell + +syn match gdscriptEscape +\\[abfnrtv'"\\]+ contained +syn match gdscriptEscape "\\$" + +" Numbers +syn match gdscriptNumber "\<0x\%(_\=\x\)\+\>" +syn match gdscriptNumber "\<0b\%(_\=[01]\)\+\>" +syn match gdscriptNumber "\<\d\%(_\=\d\)*\>" +syn match gdscriptNumber "\<\d\%(_\=\d\)*\%(e[+-]\=\d\%(_\=\d\)*\)\=\>" +syn match gdscriptNumber "\<\d\%(_\=\d\)*\.\%(e[+-]\=\d\%(_\=\d\)*\)\=\%(\W\|$\)\@=" +syn match gdscriptNumber "\%(^\|\W\)\@1<=\%(\d\%(_\=\d\)*\)\=\.\d\%(_\=\d\)*\%(e[+-]\=\d\%(_\=\d\)*\)\=\>" + +" XXX, TODO, etc +syn keyword gdscriptTodo TODO XXX FIXME HACK NOTE BUG contained + +hi def link gdscriptStatement Statement +hi def link gdscriptKeyword Keyword +hi def link gdscriptConditional Conditional +hi def link gdscriptBoolean Boolean +hi def link gdscriptOperator Operator +hi def link gdscriptRepeat Repeat +hi def link gdscriptSetGet Function +hi def link gdscriptFunctionName Function +hi def link gdscriptBuiltinStruct Typedef +hi def link gdscriptComment Comment +hi def link gdscriptString String +hi def link gdscriptQuotes String +hi def link gdscriptTripleQuotes String +hi def link gdscriptEscape Special +hi def link gdscriptNode PreProc +hi def link gdscriptType Type +hi def link gdscriptNumber Number +hi def link gdscriptBlockStart Special +hi def link gdscriptTodo Todo + + +let b:current_syntax = "gdscript" + +let &cpo = s:keepcpo +unlet s:keepcpo diff --git a/runtime/syntax/gdshader.vim b/runtime/syntax/gdshader.vim new file mode 100644 index 0000000000..f0d9f7edd9 --- /dev/null +++ b/runtime/syntax/gdshader.vim @@ -0,0 +1,57 @@ +" Vim syntax file for Godot shading language +" Language: gdshader +" Maintainer: Maxim Kim <habamax@gmail.com> +" Filenames: *.gdshader + +if exists("b:current_syntax") + finish +endif + +syn keyword gdshaderConditional if else switch case default +syn keyword gdshaderRepeat for while do +syn keyword gdshaderStatement return discard +syn keyword gdshaderBoolean true false + +syn keyword gdshaderKeyword shader_type render_mode +syn keyword gdshaderKeyword in out inout +syn keyword gdshaderKeyword lowp mediump highp +syn keyword gdshaderKeyword uniform varying const +syn keyword gdshaderKeyword flat smooth + +syn keyword gdshaderType float vec2 vec3 vec4 +syn keyword gdshaderType uint uvec2 uvec3 uvec4 +syn keyword gdshaderType int ivec2 ivec3 ivec4 +syn keyword gdshaderType void bool +syn keyword gdshaderType bvec2 bvec3 bvec4 +syn keyword gdshaderType mat2 mat3 mat4 +syn keyword gdshaderType sampler2D isampler2D usampler2D samplerCube + +syn match gdshaderMember "\v<(\.)@<=[a-z_]+\w*>" +syn match gdshaderBuiltin "\v<[A-Z_]+[A-Z0-9_]*>" +syn match gdshaderFunction "\v<\w*>(\()@=" + +syn match gdshaderNumber "\v<\d+(\.)@!>" +syn match gdshaderFloat "\v<\d*\.\d+(\.)@!>" +syn match gdshaderFloat "\v<\d*\.=\d+(e-=\d+)@=" +syn match gdshaderExponent "\v(\d*\.=\d+)@<=e-=\d+>" + +syn match gdshaderComment "\v//.*$" contains=@Spell +syn region gdshaderComment start="/\*" end="\*/" contains=@Spell +syn keyword gdshaderTodo TODO FIXME XXX NOTE BUG HACK OPTIMIZE containedin=gdshaderComment + +hi def link gdshaderConditional Conditional +hi def link gdshaderRepeat Repeat +hi def link gdshaderStatement Statement +hi def link gdshaderBoolean Boolean +hi def link gdshaderKeyword Keyword +hi def link gdshaderMember Identifier +hi def link gdshaderBuiltin Identifier +hi def link gdshaderFunction Function +hi def link gdshaderType Type +hi def link gdshaderNumber Number +hi def link gdshaderFloat Float +hi def link gdshaderExponent Special +hi def link gdshaderComment Comment +hi def link gdshaderTodo Todo + +let b:current_syntax = "gdshader" diff --git a/runtime/syntax/gitattributes.vim b/runtime/syntax/gitattributes.vim new file mode 100644 index 0000000000..b6d997f45d --- /dev/null +++ b/runtime/syntax/gitattributes.vim @@ -0,0 +1,63 @@ +" Vim syntax file +" Language: git attributes +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: .gitattributes, *.git/info/attributes +" Last Change: 2022 Sep 09 + +if exists('b:current_syntax') + finish +endif + +let s:cpo_save = &cpoptions +set cpoptions&vim + +" Comment +syn keyword gitattributesTodo contained TODO FIXME XXX +syn match gitattributesComment /^\s*#.*/ contains=gitattributesTodo + +" Pattern +syn match gitattributesPattern /^\s*#\@!\(".\+"\|\S\+\)/ skipwhite + \ nextgroup=gitattributesAttrPrefixed,gitattributesAttrAssigned skipwhite + \ contains=gitattributesGlob,gitattributesRange,gitattributesSeparator +syn match gitattributesGlob /\\\@1<![?*]/ contained +syn match gitattributesRange /\\\@1<!\[.\{-}\]/ contained +syn match gitattributesSeparator '/' contained + +" Attribute +syn match gitattributesAttrPrefixed /[!-]\?[A-Za-z0-9_.][-A-Za-z0-9_.]*/ + \ transparent contained skipwhite + \ nextgroup=gitattributesAttrPrefixed,gitattributesAttrAssigned + \ contains=gitattributesPrefix,gitattributesName +syn match gitattributesAttrAssigned /[A-Za-z0-9_.][-A-Za-z0-9_.]*=\S\+/ + \ transparent contained skipwhite + \ nextgroup=gitattributesAttrPrefixed,gitattributesAttrAssigned + \ contains=gitattributesName,gitattributesAssign,gitattributesBoolean,gitattributesString +syn match gitattributesName /[A-Za-z0-9_.][-A-Za-z0-9_.]*/ + \ contained nextgroup=gitattributesAssign +syn match gitattributesPrefix /[!-]/ contained + \ nextgroup=gitAttributesName +syn match gitattributesAssign '=' contained + \ nextgroup=gitattributesBoolean,gitattributesString +syn match gitattributesString /=\@1<=\S\+/ contained +syn keyword gitattributesBoolean true false contained + +" Macro +syn match gitattributesMacro /^\s*\[attr\]\s*\S\+/ + \ nextgroup=gitattributesAttribute skipwhite + +hi def link gitattributesAssign Operator +hi def link gitattributesBoolean Boolean +hi def link gitattributesComment Comment +hi def link gitattributesGlob Special +hi def link gitattributesMacro Define +hi def link gitattributesName Identifier +hi def link gitattributesPrefix SpecialChar +hi def link gitattributesRange Special +hi def link gitattributesSeparator Delimiter +hi def link gitattributesString String +hi def link gitattributesTodo Todo + +let b:current_syntax = 'gitattributes' + +let &cpoptions = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/gitignore.vim b/runtime/syntax/gitignore.vim new file mode 100644 index 0000000000..8e6d098acd --- /dev/null +++ b/runtime/syntax/gitignore.vim @@ -0,0 +1,29 @@ +" Vim syntax file +" Language: git ignore +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: .gitignore, *.git/info/exclude +" Last Change: 2022 Sep 10 + +if exists('b:current_syntax') + finish +endif + +" Comment +syn keyword gitignoreTodo contained TODO FIXME XXX +syn match gitignoreComment /^#.*/ contains=gitignoreTodo + +" Pattern +syn match gitignorePattern /^#\@!.*$/ contains=gitignoreNegation,gitignoreGlob,gitignoreRange,gitignoreSeparator +syn match gitignoreNegation /^!/ contained +syn match gitignoreGlob /\\\@1<![?*]/ contained +syn match gitignoreRange /\\\@1<!\[.\{-}\]/ contained +syn match gitignoreSeparator '/' contained + +hi def link gitignoreComment Comment +hi def link gitignoreGlob Special +hi def link gitignoreNegation SpecialChar +hi def link gitignoreRange Special +hi def link gitignoreSeparator Delimiter +hi def link gitignoreTodo Todo + +let b:current_syntax = 'gitignore' diff --git a/runtime/syntax/gyp.vim b/runtime/syntax/gyp.vim new file mode 100644 index 0000000000..14c07b8726 --- /dev/null +++ b/runtime/syntax/gyp.vim @@ -0,0 +1,49 @@ +" Vim syntax file +" Language: GYP +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: *.gyp,*.gypi +" Last Change: 2022 Sep 27 + +if !exists('g:main_syntax') + if exists('b:current_syntax') && b:current_syntax ==# 'gyp' + finish + endif + let g:main_syntax = 'gyp' +endif + +" Based on JSON syntax +runtime! syntax/json.vim + +" Single quotes are allowed +syn clear jsonStringSQError + +syn match jsonKeywordMatch /'\([^']\|\\\'\)\+'[[:blank:]\r\n]*\:/ contains=jsonKeyword +if has('conceal') && (!exists('g:vim_json_conceal') || g:vim_json_conceal==1) + syn region jsonKeyword matchgroup=jsonQuote start=/'/ end=/'\ze[[:blank:]\r\n]*\:/ concealends contained +else + syn region jsonKeyword matchgroup=jsonQuote start=/'/ end=/'\ze[[:blank:]\r\n]*\:/ contained +endif + +syn match jsonStringMatch /'\([^']\|\\\'\)\+'\ze[[:blank:]\r\n]*[,}\]]/ contains=jsonString +if has('conceal') && (!exists('g:vim_json_conceal') || g:vim_json_conceal==1) + syn region jsonString oneline matchgroup=jsonQuote start=/'/ skip=/\\\\\|\\'/ end=/'/ concealends contains=jsonEscape contained +else + syn region jsonString oneline matchgroup=jsonQuote start=/'/ skip=/\\\\\|\\'/ end=/'/ contains=jsonEscape contained +endif + +" Trailing commas are allowed +if !exists('g:vim_json_warnings') || g:vim_json_warnings==1 + syn clear jsonTrailingCommaError +endif + +" Python-style comments are allowed +syn match jsonComment /#.*$/ contains=jsonTodo,@Spell +syn keyword jsonTodo FIXME NOTE TODO XXX TBD contained + +hi def link jsonComment Comment +hi def link jsonTodo Todo + +let b:current_syntax = 'gyp' +if g:main_syntax ==# 'gyp' + unlet g:main_syntax +endif diff --git a/runtime/syntax/hare.vim b/runtime/syntax/hare.vim new file mode 100644 index 0000000000..07cf33fb11 --- /dev/null +++ b/runtime/syntax/hare.vim @@ -0,0 +1,133 @@ +" PRELUDE {{{1 +" Vim syntax file +" Language: Hare +" Maintainer: Amelia Clarke <me@rsaihe.dev> +" Last Change: 2022-09-21 + +if exists("b:current_syntax") + finish +endif +let b:current_syntax = "hare" + +" SYNTAX {{{1 +syn case match + +" KEYWORDS {{{2 +syn keyword hareConditional if else match switch +syn keyword hareKeyword break continue return yield +syn keyword hareKeyword defer +syn keyword hareKeyword fn +syn keyword hareKeyword let +syn keyword hareLabel case +syn keyword hareOperator as is +syn keyword hareRepeat for +syn keyword hareStorageClass const def export nullable static +syn keyword hareStructure enum struct union +syn keyword hareTypedef type + +" C ABI. +syn keyword hareKeyword vastart vaarg vaend + +" BUILTINS {{{2 +syn keyword hareBuiltin abort +syn keyword hareBuiltin alloc free +syn keyword hareBuiltin append delete insert +syn keyword hareBuiltin assert +syn keyword hareBuiltin len offset + +" TYPES {{{2 +syn keyword hareType bool +syn keyword hareType char str +syn keyword hareType f32 f64 +syn keyword hareType u8 u16 u32 u64 i8 i16 i32 i64 +syn keyword hareType uint int +syn keyword hareType rune +syn keyword hareType uintptr +syn keyword hareType void + +" C ABI. +syn keyword hareType valist + +" LITERALS {{{2 +syn keyword hareBoolean true false +syn keyword hareNull null + +" Number literals. +syn match hareNumber "\v(\.@1<!|\.\.)\zs<\d+([Ee][+-]?\d+)?(z|[iu](8|16|32|64)?)?>" display +syn match hareNumber "\v(\.@1<!|\.\.)\zs<0b[01]+(z|[iu](8|16|32|64)?)?>" display +syn match hareNumber "\v(\.@1<!|\.\.)\zs<0o\o+(z|[iu](8|16|32|64)?)?>" display +syn match hareNumber "\v(\.@1<!|\.\.)\zs<0x\x+(z|[iu](8|16|32|64)?)?>" display + +" Floating-point number literals. +syn match hareFloat "\v<\d+\.\d+([Ee][+-]?\d+)?(f32|f64)?>" display +syn match hareFloat "\v<\d+([Ee][+-]?\d+)?(f32|f64)>" display + +" String and rune literals. +syn match hareEscape "\\[\\'"0abfnrtv]" contained display +syn match hareEscape "\v\\(x\x{2}|u\x{4}|U\x{8})" contained display +syn match hareFormat "\v\{\d*(\%\d*|(:[ 0+-]?\d*(\.\d+)?[Xbox]?))?}" contained display +syn match hareFormat "\({{\|}}\)" contained display +syn region hareRune start="'" end="'\|$" skip="\\'" contains=hareEscape display extend +syn region hareString start=+"+ end=+"\|$+ skip=+\\"+ contains=hareEscape,hareFormat display extend +syn region hareString start="`" end="`\|$" contains=hareFormat display + +" MISCELLANEOUS {{{2 +syn keyword hareTodo FIXME TODO XXX contained + +" Attributes. +syn match hareAttribute "@[a-z]*" + +" Blocks. +syn region hareBlock start="{" end="}" fold transparent + +" Comments. +syn region hareComment start="//" end="$" contains=hareCommentDoc,hareTodo,@Spell display keepend +syn region hareCommentDoc start="\[\[" end="]]\|\ze\_s" contained display + +" The size keyword can be either a builtin or a type. +syn match hareBuiltin "\v<size>\ze(\_s*//.*\_$)*\_s*\(" contains=hareComment +syn match hareType "\v<size>((\_s*//.*\_$)*\_s*\()@!" contains=hareComment + +" Trailing whitespace. +syn match hareSpaceError "\v\s+$" display excludenl +syn match hareSpaceError "\v\zs +\ze\t" display + +" Use statement. +syn region hareUse start="\v^\s*\zsuse>" end=";" contains=hareComment display + +syn match hareErrorAssertion "\v(^([^/]|//@!)*\)\_s*)@<=!\=@!" +syn match hareQuestionMark "?" + +" DEFAULT HIGHLIGHTING {{{1 +hi def link hareAttribute Keyword +hi def link hareBoolean Boolean +hi def link hareBuiltin Function +hi def link hareComment Comment +hi def link hareCommentDoc SpecialComment +hi def link hareConditional Conditional +hi def link hareEscape SpecialChar +hi def link hareFloat Float +hi def link hareFormat SpecialChar +hi def link hareKeyword Keyword +hi def link hareLabel Label +hi def link hareNull Constant +hi def link hareNumber Number +hi def link hareOperator Operator +hi def link hareQuestionMark Special +hi def link hareRepeat Repeat +hi def link hareRune Character +hi def link hareStorageClass StorageClass +hi def link hareString String +hi def link hareStructure Structure +hi def link hareTodo Todo +hi def link hareType Type +hi def link hareTypedef Typedef +hi def link hareUse PreProc + +hi def link hareSpaceError Error +autocmd InsertEnter * hi link hareSpaceError NONE +autocmd InsertLeave * hi link hareSpaceError Error + +hi def hareErrorAssertion ctermfg=red cterm=bold guifg=red gui=bold + +" vim: tabstop=8 shiftwidth=2 expandtab diff --git a/runtime/syntax/help.vim b/runtime/syntax/help.vim index 01915d23d7..5773e94c3e 100644 --- a/runtime/syntax/help.vim +++ b/runtime/syntax/help.vim @@ -1,7 +1,7 @@ " Vim syntax file " Language: Vim help file " Maintainer: Bram Moolenaar (Bram@vim.org) -" Last Change: 2021 Jun 13 +" Last Change: 2022 Sep 26 " Quit when a (custom) syntax file was already loaded if exists("b:current_syntax") @@ -39,6 +39,7 @@ syn match helpVim "VIM REFERENCE.*" syn match helpVim "NVIM REFERENCE.*" syn match helpOption "'[a-z]\{2,\}'" syn match helpOption "'t_..'" +syn match helpNormal "'ab'" syn match helpCommand "`[^` \t]\+`"hs=s+1,he=e-1 contains=helpBacktick syn match helpCommand "\(^\|[^a-z"[]\)\zs`[^`]\+`\ze\([^a-z\t."']\|$\)"hs=s+1,he=e-1 contains=helpBacktick syn match helpHeader "\s*\zs.\{-}\ze\s\=\~$" nextgroup=helpIgnore diff --git a/runtime/syntax/hlsplaylist.vim b/runtime/syntax/hlsplaylist.vim new file mode 100644 index 0000000000..245eee213b --- /dev/null +++ b/runtime/syntax/hlsplaylist.vim @@ -0,0 +1,120 @@ +" Vim syntax file +" Language: HLS Playlist +" Maintainer: Benoît Ryder <benoit@ryder.fr> +" Latest Revision: 2022-09-23 + +if exists("b:current_syntax") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +" Comment line +syn match hlsplaylistComment "^#\(EXT\)\@!.*$" +" Segment URL +syn match hlsplaylistUrl "^[^#].*$" + +" Unknown tags, assume an attribute list or nothing +syn match hlsplaylistTagUnknown "^#EXT[^:]*$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagUnknown start="^#EXT[^:]*\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Basic Tags +syn match hlsplaylistTagHeader "^#EXTM3U$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-VERSION\ze:" end="$" keepend contains=hlsplaylistValueInt + +" Media or Multivariant Playlist Tags +syn match hlsplaylistTagHeader "^#EXT-X-INDEPENDENT-SEGMENTS$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagDelimiter start="^#EXT-X-START\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-DEFINE\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Media Playlist Tags +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-TARGETDURATION\ze:" end="$" keepend contains=hlsplaylistValueFloat +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-MEDIA-SEQUENCE\ze:" end="$" keepend contains=hlsplaylistValueInt +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-DISCONTINUITY-SEQUENCE\ze:" end="$" keepend contains=hlsplaylistValueInt +syn match hlsplaylistTagDelimiter "^#EXT-X-ENDLIST$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-PLAYLIST-TYPE\ze:" end="$" keepend contains=hlsplaylistAttributeEnum +syn match hlsplaylistTagStandard "^#EXT-X-I-FRAME-ONLY$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-PART-INF\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-SERVER-CONTROL\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Media Segment Tags +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXTINF\ze:" end="$" keepend contains=hlsplaylistValueFloat,hlsplaylistExtInfDesc +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-BYTERANGE\ze:" end="$" keepend contains=hlsplaylistValueInt +syn match hlsplaylistTagDelimiter "^#EXT-X-DISCONTINUITY$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-KEY\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-MAP\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-PROGRAM-DATE-TIME\ze:" end="$" keepend contains=hlsplaylistValueDateTime +syn match hlsplaylistTagDelimiter "^#EXT-X-GAP$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-BITRATE\ze:" end="$" keepend contains=hlsplaylistValueFloat +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-PART\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Media Metadata Tags +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-DATERANGE\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-SKIP\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-PRELOAD-HINT\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-RENDITION-REPORT\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Multivariant Playlist Tags +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-MEDIA\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-STREAM-INF\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-I-FRAME-STREAM-INF\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-SESSION-DATA\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-SESSION-KEY\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-CONTENT-STEERING\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Attributes +syn region hlsplaylistAttributeList start=":" end="$" keepend contained + \ contains=hlsplaylistAttributeName,hlsplaylistAttributeInt,hlsplaylistAttributeHex,hlsplaylistAttributeFloat,hlsplaylistAttributeString,hlsplaylistAttributeEnum,hlsplaylistAttributeResolution,hlsplaylistAttributeUri +" Common attributes +syn match hlsplaylistAttributeName "[A-Za-z-]\+\ze=" contained +syn match hlsplaylistAttributeEnum "=\zs[A-Za-z][A-Za-z0-9-_]*" contained +syn match hlsplaylistAttributeString +=\zs"[^"]*"+ contained +syn match hlsplaylistAttributeInt "=\zs\d\+" contained +syn match hlsplaylistAttributeFloat "=\zs-\?\d*\.\d*" contained +syn match hlsplaylistAttributeHex "=\zs0[xX]\d*" contained +syn match hlsplaylistAttributeResolution "=\zs\d\+x\d\+" contained +" Allow different highligting for URI attributes +syn region hlsplaylistAttributeUri matchgroup=hlsplaylistAttributeName start="\zsURI\ze" end="\(,\|$\)" contained contains=hlsplaylistUriQuotes +syn region hlsplaylistUriQuotes matchgroup=hlsplaylistAttributeString start=+"+ end=+"+ keepend contained contains=hlsplaylistUriValue +syn match hlsplaylistUriValue /[^" ]\+/ contained +" Individual values +syn match hlsplaylistValueInt "[0-9]\+" contained +syn match hlsplaylistValueFloat "\(\d\+\|\d*\.\d*\)" contained +syn match hlsplaylistExtInfDesc ",\zs.*$" contained +syn match hlsplaylistValueDateTime "\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d\(\.\d*\)\?\(Z\|\d\d:\?\d\d\)$" contained + + +" Define default highlighting + +hi def link hlsplaylistComment Comment +hi def link hlsplaylistUrl NONE + +hi def link hlsplaylistTagHeader Special +hi def link hlsplaylistTagStandard Define +hi def link hlsplaylistTagDelimiter Delimiter +hi def link hlsplaylistTagStatement Statement +hi def link hlsplaylistTagUnknown Special + +hi def link hlsplaylistUriQuotes String +hi def link hlsplaylistUriValue Underlined +hi def link hlsplaylistAttributeQuotes String +hi def link hlsplaylistAttributeName Identifier +hi def link hlsplaylistAttributeInt Number +hi def link hlsplaylistAttributeHex Number +hi def link hlsplaylistAttributeFloat Float +hi def link hlsplaylistAttributeString String +hi def link hlsplaylistAttributeEnum Constant +hi def link hlsplaylistAttributeResolution Constant +hi def link hlsplaylistValueInt Number +hi def link hlsplaylistValueFloat Float +hi def link hlsplaylistExtInfDesc String +hi def link hlsplaylistValueDateTime Constant + + +let b:current_syntax = "hlsplaylist" + +let &cpo = s:cpo_save +unlet s:cpo_save + +" vim: sts=2 sw=2 et diff --git a/runtime/syntax/lua.vim b/runtime/syntax/lua.vim index b398e2e5c6..9c5a490582 100644 --- a/runtime/syntax/lua.vim +++ b/runtime/syntax/lua.vim @@ -1,11 +1,12 @@ " Vim syntax file -" Language: Lua 4.0, Lua 5.0, Lua 5.1 and Lua 5.2 -" Maintainer: Marcus Aurelius Farias <masserahguard-lua 'at' yahoo com> -" First Author: Carlos Augusto Teixeira Mendes <cmendes 'at' inf puc-rio br> -" Last Change: 2022 Mar 31 -" Options: lua_version = 4 or 5 -" lua_subversion = 0 (4.0, 5.0) or 1 (5.1) or 2 (5.2) -" default 5.2 +" Language: Lua 4.0, Lua 5.0, Lua 5.1, Lua 5.2 and Lua 5.3 +" Maintainer: Marcus Aurelius Farias <masserahguard-lua 'at' yahoo com> +" First Author: Carlos Augusto Teixeira Mendes <cmendes 'at' inf puc-rio br> +" Last Change: 2022 Sep 07 +" Options: lua_version = 4 or 5 +" lua_subversion = 0 (for 4.0 or 5.0) +" or 1, 2, 3 (for 5.1, 5.2 or 5.3) +" the default is 5.3 " quit when a syntax file was already loaded if exists("b:current_syntax") @@ -16,70 +17,78 @@ let s:cpo_save = &cpo set cpo&vim if !exists("lua_version") - " Default is lua 5.2 + " Default is lua 5.3 let lua_version = 5 - let lua_subversion = 2 + let lua_subversion = 3 elseif !exists("lua_subversion") - " lua_version exists, but lua_subversion doesn't. So, set it to 0 + " lua_version exists, but lua_subversion doesn't. In this case set it to 0 let lua_subversion = 0 endif syn case match " syncing method -syn sync minlines=100 +syn sync minlines=1000 -" Comments -syn keyword luaTodo contained TODO FIXME XXX -syn match luaComment "--.*$" contains=luaTodo,@Spell -if lua_version == 5 && lua_subversion == 0 - syn region luaComment matchgroup=luaComment start="--\[\[" end="\]\]" contains=luaTodo,luaInnerComment,@Spell - syn region luaInnerComment contained transparent start="\[\[" end="\]\]" -elseif lua_version > 5 || (lua_version == 5 && lua_subversion >= 1) - " Comments in Lua 5.1: --[[ ... ]], [=[ ... ]=], [===[ ... ]===], etc. - syn region luaComment matchgroup=luaComment start="--\[\z(=*\)\[" end="\]\z1\]" contains=luaTodo,@Spell +if lua_version >= 5 + syn keyword luaMetaMethod __add __sub __mul __div __pow __unm __concat + syn keyword luaMetaMethod __eq __lt __le + syn keyword luaMetaMethod __index __newindex __call + syn keyword luaMetaMethod __metatable __mode __gc __tostring endif -" First line may start with #! -syn match luaComment "\%^#!.*" +if lua_version > 5 || (lua_version == 5 && lua_subversion >= 1) + syn keyword luaMetaMethod __mod __len +endif + +if lua_version > 5 || (lua_version == 5 && lua_subversion >= 2) + syn keyword luaMetaMethod __pairs +endif + +if lua_version > 5 || (lua_version == 5 && lua_subversion >= 3) + syn keyword luaMetaMethod __idiv __name + syn keyword luaMetaMethod __band __bor __bxor __bnot __shl __shr +endif + +if lua_version > 5 || (lua_version == 5 && lua_subversion >= 4) + syn keyword luaMetaMethod __close +endif " catch errors caused by wrong parenthesis and wrong curly brackets or " keywords placed outside their respective blocks -syn region luaParen transparent start='(' end=')' contains=ALLBUT,luaParenError,luaTodo,luaSpecial,luaIfThen,luaElseifThen,luaElse,luaThenEnd,luaBlock,luaLoopBlock,luaIn,luaStatement -syn region luaTableBlock transparent matchgroup=luaTable start="{" end="}" contains=ALLBUT,luaBraceError,luaTodo,luaSpecial,luaIfThen,luaElseifThen,luaElse,luaThenEnd,luaBlock,luaLoopBlock,luaIn,luaStatement +syn region luaParen transparent start='(' end=')' contains=TOP,luaParenError syn match luaParenError ")" -syn match luaBraceError "}" +syn match luaError "}" syn match luaError "\<\%(end\|else\|elseif\|then\|until\|in\)\>" -" function ... end -syn region luaFunctionBlock transparent matchgroup=luaFunction start="\<function\>" end="\<end\>" contains=ALLBUT,luaTodo,luaSpecial,luaElseifThen,luaElse,luaThenEnd,luaIn +" Function declaration +syn region luaFunctionBlock transparent matchgroup=luaFunction start="\<function\>" end="\<end\>" contains=TOP -" if ... then -syn region luaIfThen transparent matchgroup=luaCond start="\<if\>" end="\<then\>"me=e-4 contains=ALLBUT,luaTodo,luaSpecial,luaElseifThen,luaElse,luaIn nextgroup=luaThenEnd skipwhite skipempty +" else +syn keyword luaCondElse matchgroup=luaCond contained containedin=luaCondEnd else " then ... end -syn region luaThenEnd contained transparent matchgroup=luaCond start="\<then\>" end="\<end\>" contains=ALLBUT,luaTodo,luaSpecial,luaThenEnd,luaIn +syn region luaCondEnd contained transparent matchgroup=luaCond start="\<then\>" end="\<end\>" contains=TOP " elseif ... then -syn region luaElseifThen contained transparent matchgroup=luaCond start="\<elseif\>" end="\<then\>" contains=ALLBUT,luaTodo,luaSpecial,luaElseifThen,luaElse,luaThenEnd,luaIn +syn region luaCondElseif contained containedin=luaCondEnd transparent matchgroup=luaCond start="\<elseif\>" end="\<then\>" contains=TOP -" else -syn keyword luaElse contained else +" if ... then +syn region luaCondStart transparent matchgroup=luaCond start="\<if\>" end="\<then\>"me=e-4 contains=TOP nextgroup=luaCondEnd skipwhite skipempty " do ... end -syn region luaBlock transparent matchgroup=luaStatement start="\<do\>" end="\<end\>" contains=ALLBUT,luaTodo,luaSpecial,luaElseifThen,luaElse,luaThenEnd,luaIn - +syn region luaBlock transparent matchgroup=luaStatement start="\<do\>" end="\<end\>" contains=TOP " repeat ... until -syn region luaLoopBlock transparent matchgroup=luaRepeat start="\<repeat\>" end="\<until\>" contains=ALLBUT,luaTodo,luaSpecial,luaElseifThen,luaElse,luaThenEnd,luaIn +syn region luaRepeatBlock transparent matchgroup=luaRepeat start="\<repeat\>" end="\<until\>" contains=TOP " while ... do -syn region luaLoopBlock transparent matchgroup=luaRepeat start="\<while\>" end="\<do\>"me=e-2 contains=ALLBUT,luaTodo,luaSpecial,luaIfThen,luaElseifThen,luaElse,luaThenEnd,luaIn nextgroup=luaBlock skipwhite skipempty +syn region luaWhile transparent matchgroup=luaRepeat start="\<while\>" end="\<do\>"me=e-2 contains=TOP nextgroup=luaBlock skipwhite skipempty " for ... do and for ... in ... do -syn region luaLoopBlock transparent matchgroup=luaRepeat start="\<for\>" end="\<do\>"me=e-2 contains=ALLBUT,luaTodo,luaSpecial,luaIfThen,luaElseifThen,luaElse,luaThenEnd nextgroup=luaBlock skipwhite skipempty +syn region luaFor transparent matchgroup=luaRepeat start="\<for\>" end="\<do\>"me=e-2 contains=TOP nextgroup=luaBlock skipwhite skipempty -syn keyword luaIn contained in +syn keyword luaFor contained containedin=luaFor in " other keywords syn keyword luaStatement return local break @@ -87,35 +96,59 @@ if lua_version > 5 || (lua_version == 5 && lua_subversion >= 2) syn keyword luaStatement goto syn match luaLabel "::\I\i*::" endif + +" operators syn keyword luaOperator and or not + +if (lua_version == 5 && lua_subversion >= 3) || lua_version > 5 + syn match luaSymbolOperator "[#<>=~^&|*/%+-]\|\.\{2,3}" +elseif lua_version == 5 && (lua_subversion == 1 || lua_subversion == 2) + syn match luaSymbolOperator "[#<>=~^*/%+-]\|\.\{2,3}" +else + syn match luaSymbolOperator "[<>=~^*/+-]\|\.\{2,3}" +endif + +" comments +syn keyword luaTodo contained TODO FIXME XXX +syn match luaComment "--.*$" contains=luaTodo,@Spell +if lua_version == 5 && lua_subversion == 0 + syn region luaComment matchgroup=luaCommentDelimiter start="--\[\[" end="\]\]" contains=luaTodo,luaInnerComment,@Spell + syn region luaInnerComment contained transparent start="\[\[" end="\]\]" +elseif lua_version > 5 || (lua_version == 5 && lua_subversion >= 1) + " Comments in Lua 5.1: --[[ ... ]], [=[ ... ]=], [===[ ... ]===], etc. + syn region luaComment matchgroup=luaCommentDelimiter start="--\[\z(=*\)\[" end="\]\z1\]" contains=luaTodo,@Spell +endif + +" first line may start with #! +syn match luaComment "\%^#!.*" + syn keyword luaConstant nil if lua_version > 4 syn keyword luaConstant true false endif -" Strings -if lua_version < 5 - syn match luaSpecial contained "\\[\\abfnrtv\'\"]\|\\[[:digit:]]\{,3}" -elseif lua_version == 5 +" strings +syn match luaSpecial contained #\\[\\abfnrtv'"[\]]\|\\[[:digit:]]\{,3}# +if lua_version == 5 if lua_subversion == 0 - syn match luaSpecial contained #\\[\\abfnrtv'"[\]]\|\\[[:digit:]]\{,3}# - syn region luaString2 matchgroup=luaString start=+\[\[+ end=+\]\]+ contains=luaString2,@Spell + syn region luaString2 matchgroup=luaStringDelimiter start=+\[\[+ end=+\]\]+ contains=luaString2,@Spell else - if lua_subversion == 1 - syn match luaSpecial contained #\\[\\abfnrtv'"]\|\\[[:digit:]]\{,3}# - else " Lua 5.2 - syn match luaSpecial contained #\\[\\abfnrtvz'"]\|\\x[[:xdigit:]]\{2}\|\\[[:digit:]]\{,3}# + if lua_subversion >= 2 + syn match luaSpecial contained #\\z\|\\x[[:xdigit:]]\{2}# + endif + if lua_subversion >= 3 + syn match luaSpecial contained #\\u{[[:xdigit:]]\+}# endif - syn region luaString2 matchgroup=luaString start="\[\z(=*\)\[" end="\]\z1\]" contains=@Spell + syn region luaString2 matchgroup=luaStringDelimiter start="\[\z(=*\)\[" end="\]\z1\]" contains=@Spell endif endif -syn region luaString start=+'+ end=+'+ skip=+\\\\\|\\'+ contains=luaSpecial,@Spell -syn region luaString start=+"+ end=+"+ skip=+\\\\\|\\"+ contains=luaSpecial,@Spell +syn region luaString matchgroup=luaStringDelimiter start=+'+ end=+'+ skip=+\\\\\|\\'+ contains=luaSpecial,@Spell +syn region luaString matchgroup=luaStringDelimiter start=+"+ end=+"+ skip=+\\\\\|\\"+ contains=luaSpecial,@Spell " integer number syn match luaNumber "\<\d\+\>" " floating point number, with dot, optional exponent -syn match luaNumber "\<\d\+\.\d*\%([eE][-+]\=\d\+\)\=\>" +syn match luaNumber "\<\d\+\.\d*\%([eE][-+]\=\d\+\)\=" " floating point number, starting with a dot, optional exponent syn match luaNumber "\.\d\+\%([eE][-+]\=\d\+\)\=\>" " floating point number, without dot, with exponent @@ -130,8 +163,15 @@ if lua_version >= 5 endif endif +" tables +syn region luaTableBlock transparent matchgroup=luaTable start="{" end="}" contains=TOP,luaStatement + +" methods +syntax match luaFunc ":\@<=\k\+" + +" built-in functions syn keyword luaFunc assert collectgarbage dofile error next -syn keyword luaFunc print rawget rawset tonumber tostring type _VERSION +syn keyword luaFunc print rawget rawset self tonumber tostring type _VERSION if lua_version == 4 syn keyword luaFunc _ALERT _ERRORMESSAGE gcinfo @@ -168,30 +208,26 @@ elseif lua_version == 5 syn match luaFunc /\<package\.loaded\>/ syn match luaFunc /\<package\.loadlib\>/ syn match luaFunc /\<package\.path\>/ + syn match luaFunc /\<package\.preload\>/ if lua_subversion == 1 syn keyword luaFunc getfenv setfenv syn keyword luaFunc loadstring module unpack syn match luaFunc /\<package\.loaders\>/ - syn match luaFunc /\<package\.preload\>/ syn match luaFunc /\<package\.seeall\>/ - elseif lua_subversion == 2 + elseif lua_subversion >= 2 syn keyword luaFunc _ENV rawlen syn match luaFunc /\<package\.config\>/ syn match luaFunc /\<package\.preload\>/ syn match luaFunc /\<package\.searchers\>/ syn match luaFunc /\<package\.searchpath\>/ - syn match luaFunc /\<bit32\.arshift\>/ - syn match luaFunc /\<bit32\.band\>/ - syn match luaFunc /\<bit32\.bnot\>/ - syn match luaFunc /\<bit32\.bor\>/ - syn match luaFunc /\<bit32\.btest\>/ - syn match luaFunc /\<bit32\.bxor\>/ - syn match luaFunc /\<bit32\.extract\>/ - syn match luaFunc /\<bit32\.lrotate\>/ - syn match luaFunc /\<bit32\.lshift\>/ - syn match luaFunc /\<bit32\.replace\>/ - syn match luaFunc /\<bit32\.rrotate\>/ - syn match luaFunc /\<bit32\.rshift\>/ + endif + + if lua_subversion >= 3 + syn match luaFunc /\<coroutine\.isyieldable\>/ + endif + if lua_subversion >= 4 + syn keyword luaFunc warn + syn match luaFunc /\<coroutine\.close\>/ endif syn match luaFunc /\<coroutine\.running\>/ endif @@ -200,6 +236,7 @@ elseif lua_version == 5 syn match luaFunc /\<coroutine\.status\>/ syn match luaFunc /\<coroutine\.wrap\>/ syn match luaFunc /\<coroutine\.yield\>/ + syn match luaFunc /\<string\.byte\>/ syn match luaFunc /\<string\.char\>/ syn match luaFunc /\<string\.dump\>/ @@ -218,6 +255,18 @@ elseif lua_version == 5 syn match luaFunc /\<string\.match\>/ syn match luaFunc /\<string\.reverse\>/ endif + if lua_subversion >= 3 + syn match luaFunc /\<string\.pack\>/ + syn match luaFunc /\<string\.packsize\>/ + syn match luaFunc /\<string\.unpack\>/ + syn match luaFunc /\<utf8\.char\>/ + syn match luaFunc /\<utf8\.charpattern\>/ + syn match luaFunc /\<utf8\.codes\>/ + syn match luaFunc /\<utf8\.codepoint\>/ + syn match luaFunc /\<utf8\.len\>/ + syn match luaFunc /\<utf8\.offset\>/ + endif + if lua_subversion == 0 syn match luaFunc /\<table\.getn\>/ syn match luaFunc /\<table\.setn\>/ @@ -225,19 +274,40 @@ elseif lua_version == 5 syn match luaFunc /\<table\.foreachi\>/ elseif lua_subversion == 1 syn match luaFunc /\<table\.maxn\>/ - elseif lua_subversion == 2 + elseif lua_subversion >= 2 syn match luaFunc /\<table\.pack\>/ syn match luaFunc /\<table\.unpack\>/ + if lua_subversion >= 3 + syn match luaFunc /\<table\.move\>/ + endif endif syn match luaFunc /\<table\.concat\>/ - syn match luaFunc /\<table\.sort\>/ syn match luaFunc /\<table\.insert\>/ + syn match luaFunc /\<table\.sort\>/ syn match luaFunc /\<table\.remove\>/ + + if lua_subversion == 2 + syn match luaFunc /\<bit32\.arshift\>/ + syn match luaFunc /\<bit32\.band\>/ + syn match luaFunc /\<bit32\.bnot\>/ + syn match luaFunc /\<bit32\.bor\>/ + syn match luaFunc /\<bit32\.btest\>/ + syn match luaFunc /\<bit32\.bxor\>/ + syn match luaFunc /\<bit32\.extract\>/ + syn match luaFunc /\<bit32\.lrotate\>/ + syn match luaFunc /\<bit32\.lshift\>/ + syn match luaFunc /\<bit32\.replace\>/ + syn match luaFunc /\<bit32\.rrotate\>/ + syn match luaFunc /\<bit32\.rshift\>/ + endif + syn match luaFunc /\<math\.abs\>/ syn match luaFunc /\<math\.acos\>/ syn match luaFunc /\<math\.asin\>/ syn match luaFunc /\<math\.atan\>/ - syn match luaFunc /\<math\.atan2\>/ + if lua_subversion < 3 + syn match luaFunc /\<math\.atan2\>/ + endif syn match luaFunc /\<math\.ceil\>/ syn match luaFunc /\<math\.sin\>/ syn match luaFunc /\<math\.cos\>/ @@ -251,25 +321,36 @@ elseif lua_version == 5 if lua_subversion == 0 syn match luaFunc /\<math\.mod\>/ syn match luaFunc /\<math\.log10\>/ - else - if lua_subversion == 1 - syn match luaFunc /\<math\.log10\>/ - endif + elseif lua_subversion == 1 + syn match luaFunc /\<math\.log10\>/ + endif + if lua_subversion >= 1 syn match luaFunc /\<math\.huge\>/ syn match luaFunc /\<math\.fmod\>/ syn match luaFunc /\<math\.modf\>/ - syn match luaFunc /\<math\.cosh\>/ - syn match luaFunc /\<math\.sinh\>/ - syn match luaFunc /\<math\.tanh\>/ + if lua_subversion == 1 || lua_subversion == 2 + syn match luaFunc /\<math\.cosh\>/ + syn match luaFunc /\<math\.sinh\>/ + syn match luaFunc /\<math\.tanh\>/ + endif endif - syn match luaFunc /\<math\.pow\>/ syn match luaFunc /\<math\.rad\>/ syn match luaFunc /\<math\.sqrt\>/ - syn match luaFunc /\<math\.frexp\>/ - syn match luaFunc /\<math\.ldexp\>/ + if lua_subversion < 3 + syn match luaFunc /\<math\.pow\>/ + syn match luaFunc /\<math\.frexp\>/ + syn match luaFunc /\<math\.ldexp\>/ + else + syn match luaFunc /\<math\.maxinteger\>/ + syn match luaFunc /\<math\.mininteger\>/ + syn match luaFunc /\<math\.tointeger\>/ + syn match luaFunc /\<math\.type\>/ + syn match luaFunc /\<math\.ult\>/ + endif syn match luaFunc /\<math\.random\>/ syn match luaFunc /\<math\.randomseed\>/ syn match luaFunc /\<math\.pi\>/ + syn match luaFunc /\<io\.close\>/ syn match luaFunc /\<io\.flush\>/ syn match luaFunc /\<io\.input\>/ @@ -284,6 +365,7 @@ elseif lua_version == 5 syn match luaFunc /\<io\.tmpfile\>/ syn match luaFunc /\<io\.type\>/ syn match luaFunc /\<io\.write\>/ + syn match luaFunc /\<os\.clock\>/ syn match luaFunc /\<os\.date\>/ syn match luaFunc /\<os\.difftime\>/ @@ -295,6 +377,7 @@ elseif lua_version == 5 syn match luaFunc /\<os\.setlocale\>/ syn match luaFunc /\<os\.time\>/ syn match luaFunc /\<os\.tmpname\>/ + syn match luaFunc /\<debug\.debug\>/ syn match luaFunc /\<debug\.gethook\>/ syn match luaFunc /\<debug\.getinfo\>/ @@ -307,53 +390,49 @@ elseif lua_version == 5 if lua_subversion == 1 syn match luaFunc /\<debug\.getfenv\>/ syn match luaFunc /\<debug\.setfenv\>/ + endif + if lua_subversion >= 1 syn match luaFunc /\<debug\.getmetatable\>/ syn match luaFunc /\<debug\.setmetatable\>/ syn match luaFunc /\<debug\.getregistry\>/ - elseif lua_subversion == 2 - syn match luaFunc /\<debug\.getmetatable\>/ - syn match luaFunc /\<debug\.setmetatable\>/ - syn match luaFunc /\<debug\.getregistry\>/ - syn match luaFunc /\<debug\.getuservalue\>/ - syn match luaFunc /\<debug\.setuservalue\>/ - syn match luaFunc /\<debug\.upvalueid\>/ - syn match luaFunc /\<debug\.upvaluejoin\>/ - endif - if lua_subversion >= 3 - "https://www.lua.org/manual/5.3/manual.html#6.5 - syn match luaFunc /\<utf8\.char\>/ - syn match luaFunc /\<utf8\.charpattern\>/ - syn match luaFunc /\<utf8\.codes\>/ - syn match luaFunc /\<utf8\.codepoint\>/ - syn match luaFunc /\<utf8\.len\>/ - syn match luaFunc /\<utf8\.offset\>/ + if lua_subversion >= 2 + syn match luaFunc /\<debug\.getuservalue\>/ + syn match luaFunc /\<debug\.setuservalue\>/ + syn match luaFunc /\<debug\.upvalueid\>/ + syn match luaFunc /\<debug\.upvaluejoin\>/ + endif + if lua_subversion >= 4 + syn match luaFunc /\<debug.setcstacklimit\>/ + endif endif endif " Define the default highlighting. " Only when an item doesn't have highlighting yet -hi def link luaStatement Statement -hi def link luaRepeat Repeat -hi def link luaFor Repeat -hi def link luaString String -hi def link luaString2 String -hi def link luaNumber Number -hi def link luaOperator Operator -hi def link luaIn Operator -hi def link luaConstant Constant -hi def link luaCond Conditional -hi def link luaElse Conditional -hi def link luaFunction Function -hi def link luaComment Comment -hi def link luaTodo Todo -hi def link luaTable Structure -hi def link luaError Error -hi def link luaParenError Error -hi def link luaBraceError Error -hi def link luaSpecial SpecialChar -hi def link luaFunc Identifier -hi def link luaLabel Label +hi def link luaStatement Statement +hi def link luaRepeat Repeat +hi def link luaFor Repeat +hi def link luaString String +hi def link luaString2 String +hi def link luaStringDelimiter luaString +hi def link luaNumber Number +hi def link luaOperator Operator +hi def link luaSymbolOperator luaOperator +hi def link luaConstant Constant +hi def link luaCond Conditional +hi def link luaCondElse Conditional +hi def link luaFunction Function +hi def link luaMetaMethod Function +hi def link luaComment Comment +hi def link luaCommentDelimiter luaComment +hi def link luaTodo Todo +hi def link luaTable Structure +hi def link luaError Error +hi def link luaParenError Error +hi def link luaSpecial SpecialChar +hi def link luaFunc Identifier +hi def link luaLabel Label let b:current_syntax = "lua" diff --git a/runtime/syntax/lyrics.vim b/runtime/syntax/lyrics.vim new file mode 100644 index 0000000000..42a288b51b --- /dev/null +++ b/runtime/syntax/lyrics.vim @@ -0,0 +1,43 @@ +" Vim syntax file +" Language: LyRiCs +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: *.lrc +" Last Change: 2022 Sep 18 + +if exists('b:current_syntax') + finish +endif + +let s:cpo_save = &cpoptions +set cpoptions&vim + +syn case ignore + +" Errors +syn match lrcError /^.\+$/ + +" ID tags +syn match lrcTag /^\s*\[\a\+:.\+\]\s*$/ contains=lrcTagName,lrcTagValue +syn match lrcTagName contained nextgroup=lrcTagValue + \ /\[\zs\(al\|ar\|au\|by\|encoding\|la\|id\|length\|offset\|re\|ti\|ve\)\ze:/ +syn match lrcTagValue /:\zs.\+\ze\]/ contained + +" Lyrics +syn match lrcLyricTime /^\s*\[\d\d:\d\d\.\d\d\]/ + \ contains=lrcNumber nextgroup=lrcLyricLine +syn match lrcLyricLine /.*$/ contained contains=lrcWordTime,@Spell +syn match lrcWordTime /<\d\d:\d\d\.\d\d>/ contained contains=lrcNumber,@NoSpell +syn match lrcNumber /[+-]\=\d\+/ contained + +hi def link lrcLyricTime Label +hi def link lrcNumber Number +hi def link lrcTag PreProc +hi def link lrcTagName Identifier +hi def link lrcTagValue String +hi def link lrcWordTime Special +hi def link lrcError Error + +let b:current_syntax = 'lyrics' + +let &cpoptions = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/plsql.vim b/runtime/syntax/plsql.vim index 7b36c0a180..9b4df09ac7 100644 --- a/runtime/syntax/plsql.vim +++ b/runtime/syntax/plsql.vim @@ -4,12 +4,16 @@ " Previous Maintainer: Jeff Lanzarotta (jefflanzarotta at yahoo dot com) " Previous Maintainer: C. Laurence Gonsalves (clgonsal@kami.com) " URL: https://github.com/lee-lindley/vim_plsql_syntax -" Last Change: April 28, 2022 -" History Lee Lindley (lee dot lindley at gmail dot com) +" Last Change: Sep 19, 2022 +" History Carsten Czarski (carsten dot czarski at oracle com) +" add handling for typical SQL*Plus commands (rem, start, host, set, etc) +" add error highlight for non-breaking space +" Lee Lindley (lee dot lindley at gmail dot com) +" use get with default 0 instead of exists per Bram suggestion +" make procedure folding optional " updated to 19c keywords. refined quoting. " separated reserved, non-reserved keywords and functions -" revised folding, giving up on procedure folding due to issue -" with multiple ways to enter <begin>. +" revised folding " Eugene Lysyonok (lysyonok at inbox ru) " Added folding. " Geoff Evans & Bill Pribyl (bill at plnet dot org) @@ -23,12 +27,19 @@ " To enable folding (It does setlocal foldmethod=syntax) " let plsql_fold = 1 " +" To disable folding procedure/functions (recommended if you habitually +" do not put the method name on the END statement) +" let plsql_disable_procedure_fold = 1 +" " From my vimrc file -- turn syntax and syntax folding on, " associate file suffixes as plsql, open all the folds on file open +" syntax enable " let plsql_fold = 1 " au BufNewFile,BufRead *.sql,*.pls,*.tps,*.tpb,*.pks,*.pkb,*.pkg,*.trg set filetype=plsql " au BufNewFile,BufRead *.sql,*.pls,*.tps,*.tpb,*.pks,*.pkb,*.pkg,*.trg syntax on " au Syntax plsql normal zR +" au Syntax plsql set foldcolumn=2 "optional if you want to see choosable folds on the left + if exists("b:current_syntax") finish @@ -46,15 +57,20 @@ syn case ignore syn match plsqlGarbage "[^ \t()]" syn match plsqlIdentifier "[a-z][a-z0-9$_#]*" +syn match plsqlSqlPlusDefine "&&\?[a-z][a-z0-9$_#]*\.\?" syn match plsqlHostIdentifier ":[a-z][a-z0-9$_#]*" +" The Non-Breaking is often accidentally typed (Mac User: Opt+Space, after typing the "|", Opt+7); +" error highlight for these avoids running into annoying compiler errors. +syn match plsqlIllegalSpace "[\xa0]" + " When wanted, highlight the trailing whitespace. -if exists("plsql_space_errors") - if !exists("plsql_no_trail_space_error") +if get(g:,"plsql_space_errors",0) == 1 + if get(g:,"plsql_no_trail_space_error",0) == 0 syn match plsqlSpaceError "\s\+$" endif - if !exists("plsql_no_tab_space_error") + if get(g:,"plsql_no_tab_space_error",0) == 0 syn match plsqlSpaceError " \+\t"me=e-1 endif endif @@ -71,7 +87,6 @@ syn match plsqlOperator "\<IS\\_s\+\(NOT\_s\+\)\?NULL\>" " " conditional compilation Preprocessor directives and sqlplus define sigil syn match plsqlPseudo "$[$a-z][a-z0-9$_#]*" -syn match plsqlPseudo "&" syn match plsqlReserved "\<\(CREATE\|THEN\|UPDATE\|INSERT\|SET\)\>" syn match plsqlKeyword "\<\(REPLACE\|PACKAGE\|FUNCTION\|PROCEDURE\|TYPE|BODY\|WHEN\|MATCHED\)\>" @@ -134,14 +149,15 @@ syn keyword plsqlKeyword CPU_TIME CRASH CREATE_FILE_DEST CREATE_STORED_OUTLINES syn keyword plsqlKeyword CREDENTIALS CRITICAL CROSS CROSSEDITION CSCONVERT CUBE CUBE_AJ CUBE_GB CUBE_SJ syn keyword plsqlKeyword CUME_DIST CUME_DISTM CURRENT CURRENTV CURRENT_DATE CURRENT_INSTANCE CURRENT_PARTSET_KEY syn keyword plsqlKeyword CURRENT_SCHEMA CURRENT_SHARD_KEY CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER -syn keyword plsqlKeyword CURSOR CURSOR_SHARING_EXACT CURSOR_SPECIFIC_SEGMENT CV CYCLE DAGG_OPTIM_GSETS +syn match plsqlKeyword "\<CURSOR\>" +syn keyword plsqlKeyword CURSOR_SHARING_EXACT CURSOR_SPECIFIC_SEGMENT CV CYCLE DAGG_OPTIM_GSETS syn keyword plsqlKeyword DANGLING DATA DATABASE DATABASES DATAFILE DATAFILES DATAMOVEMENT DATAOBJNO syn keyword plsqlKeyword DATAOBJ_TO_MAT_PARTITION DATAOBJ_TO_PARTITION DATAPUMP DATASTORE DATA_LINK_DML syn keyword plsqlKeyword DATA_SECURITY_REWRITE_LIMIT DATA_VALIDATE DATE_MODE DAYS DBA DBA_RECYCLEBIN syn keyword plsqlKeyword DBMS_STATS DBSTR2UTF8 DBTIMEZONE DB_ROLE_CHANGE DB_UNIQUE_NAME DB_VERSION syn keyword plsqlKeyword DDL DEALLOCATE DEBUG DEBUGGER DECLARE DECODE DECOMPOSE DECOMPRESS DECORRELATE syn keyword plsqlKeyword DECR DECREMENT DECRYPT DEDUPLICATE DEFAULTS DEFAULT_COLLATION DEFAULT_PDB_HINT -syn keyword plsqlKeyword DEFERRABLE DEFERRED DEFINE DEFINED DEFINER DEFINITION DEGREE DELAY DELEGATE +syn keyword plsqlKeyword DEFERRABLE DEFERRED DEFINED DEFINER DEFINITION DEGREE DELAY DELEGATE syn keyword plsqlKeyword DELETEXML DELETE_ALL DEMAND DENORM_AV DENSE_RANK DENSE_RANKM DEPENDENT DEPTH syn keyword plsqlKeyword DEQUEUE DEREF DEREF_NO_REWRITE DESCENDANT DESCRIPTION DESTROY DETACHED DETERMINED syn keyword plsqlKeyword DETERMINES DETERMINISTIC DG_GATHER_STATS DIAGNOSTICS DICTIONARY DIGEST DIMENSION @@ -180,7 +196,7 @@ syn keyword plsqlKeyword HELP HEXTORAW HEXTOREF HIDDEN HIDE HIERARCHICAL HIERARC syn keyword plsqlKeyword HIER_CAPTION HIER_CHILDREN HIER_CHILD_COUNT HIER_COLUMN HIER_CONDITION HIER_DEPTH syn keyword plsqlKeyword HIER_DESCRIPTION HIER_HAS_CHILDREN HIER_LAG HIER_LEAD HIER_LEVEL HIER_MEMBER_NAME syn keyword plsqlKeyword HIER_MEMBER_UNIQUE_NAME HIER_ORDER HIER_PARENT HIER_WINDOW HIGH HINTSET_BEGIN -syn keyword plsqlKeyword HINTSET_END HOST HOT HOUR HOURS HTTP HWM_BROKERED HYBRID ID IDENTIFIER IDENTITY +syn keyword plsqlKeyword HINTSET_END HOT HOUR HOURS HTTP HWM_BROKERED HYBRID ID IDENTIFIER IDENTITY syn keyword plsqlKeyword IDGENERATORS IDLE IDLE_TIME IGNORE IGNORE_OPTIM_EMBEDDED_HINTS IGNORE_ROW_ON_DUPKEY_INDEX syn keyword plsqlKeyword IGNORE_WHERE_CLAUSE ILM IMMEDIATE IMMUTABLE IMPACT IMPORT INACTIVE INACTIVE_ACCOUNT_TIME syn keyword plsqlKeyword INCLUDE INCLUDES INCLUDE_VERSION INCLUDING INCOMING INCR INCREMENT INCREMENTAL @@ -333,7 +349,7 @@ syn keyword plsqlKeyword SELF SEMIJOIN SEMIJOIN_DRIVER SEMI_TO_INNER SENSITIVE S syn keyword plsqlKeyword SERIAL SERIALIZABLE SERVERERROR SERVICE SERVICES SERVICE_NAME_CONVERT SESSION syn keyword plsqlKeyword SESSIONS_PER_USER SESSIONTIMEZONE SESSIONTZNAME SESSION_CACHED_CURSORS SETS syn keyword plsqlKeyword SETTINGS SET_GBY_PUSHDOWN SET_TO_JOIN SEVERE SHARD SHARDED SHARDS SHARDSPACE -syn keyword plsqlKeyword SHARD_CHUNK_ID SHARED SHARED_POOL SHARE_OF SHARING SHD$COL$MAP SHELFLIFE SHOW +syn keyword plsqlKeyword SHARD_CHUNK_ID SHARED SHARED_POOL SHARE_OF SHARING SHD$COL$MAP SHELFLIFE syn keyword plsqlKeyword SHRINK SHUTDOWN SIBLING SIBLINGS SID SIGN SIGNAL_COMPONENT SIGNAL_FUNCTION syn keyword plsqlKeyword SIGNATURE SIMPLE SIN SINGLE SINGLETASK SINH SITE SKEWNESS_POP SKEWNESS_SAMP syn keyword plsqlKeyword SKIP SKIP_EXT_OPTIMIZER SKIP_PROXY SKIP_UNQ_UNUSABLE_IDX SKIP_UNUSABLE_INDEXES @@ -436,7 +452,7 @@ syn keyword plsqlKeyword VECTOR_READ_TRACE VECTOR_TRANSFORM VECTOR_TRANSFORM_DIM syn keyword plsqlKeyword VERIFIER VERIFY VERSION VERSIONING VERSIONS VERSIONS_ENDSCN VERSIONS_ENDTIME syn keyword plsqlKeyword VERSIONS_OPERATION VERSIONS_STARTSCN VERSIONS_STARTTIME VERSIONS_XID VIEWS syn keyword plsqlKeyword VIOLATION VIRTUAL VISIBILITY VISIBLE VOLUME VSIZE WAIT WALLET WEEK WEEKS WELLFORMED -syn keyword plsqlKeyword WHENEVER WHITESPACE WIDTH_BUCKET WINDOW WITHIN WITHOUT WITH_EXPRESSION +syn keyword plsqlKeyword WHITESPACE WIDTH_BUCKET WINDOW WITHIN WITHOUT WITH_EXPRESSION syn keyword plsqlKeyword WITH_PLSQL WORK WRAPPED WRAPPER WRITE XDB_FASTPATH_INSERT XID XML XML2OBJECT syn keyword plsqlKeyword XMLATTRIBUTES XMLCAST XMLCDATA XMLCOLATTVAL XMLCOMMENT XMLCONCAT XMLDIFF XMLELEMENT syn keyword plsqlKeyword XMLEXISTS XMLEXISTS2 XMLFOREST XMLINDEX_REWRITE XMLINDEX_REWRITE_IN_SELECT @@ -459,13 +475,13 @@ syn keyword plsqlReserved MINUS MODE NOCOMPRESS NOWAIT NUMBER_BASE OCICOLL OCIDA syn keyword plsqlReserved OCIDURATION OCIINTERVAL OCILOBLOCATOR OCINUMBER OCIRAW OCIREF OCIREFCURSOR syn keyword plsqlReserved OCIROWID OCISTRING OCITYPE OF ON OPTION ORACLE ORADATA ORDER ORLANY ORLVARY syn keyword plsqlReserved OUT OVERRIDING PARALLEL_ENABLE PARAMETER PASCAL PCTFREE PIPE PIPELINED POLYMORPHIC -syn keyword plsqlReserved PRAGMA PRIOR PUBLIC RAISE RECORD RELIES_ON REM RENAME RESOURCE RESULT REVOKE ROWID +syn keyword plsqlReserved PRAGMA PRIOR PUBLIC RAISE RECORD RELIES_ON RENAME RESOURCE RESULT REVOKE ROWID syn keyword plsqlReserved SB1 SB2 syn match plsqlReserved "\<SELECT\>" syn keyword plsqlReserved SEPARATE SHARE SHORT SIZE SIZE_T SPARSE SQLCODE SQLDATA syn keyword plsqlReserved SQLNAME SQLSTATE STANDARD START STORED STRUCT STYLE SYNONYM TABLE TDO syn keyword plsqlReserved TRANSACTIONAL TRIGGER UB1 UB4 UNION UNIQUE UNSIGNED UNTRUSTED VALIST -syn keyword plsqlReserved VALUES VARIABLE VIEW VOID WHERE WITH +syn keyword plsqlReserved VALUES VIEW VOID WHERE WITH " PL/SQL and SQL functions. syn keyword plsqlFunction ABS ACOS ADD_MONTHS APPROX_COUNT APPROX_COUNT_DISTINCT APPROX_COUNT_DISTINCT_AGG @@ -515,7 +531,7 @@ syn match plsqlFunction "\.DELETE\>"hs=s+1 syn match plsqlFunction "\.PREV\>"hs=s+1 syn match plsqlFunction "\.NEXT\>"hs=s+1 -if exists("plsql_legacy_sql_keywords") +if get(g:,"plsql_legacy_sql_keywords",0) == 1 " Some of Oracle's SQL keywords. syn keyword plsqlSQLKeyword ABORT ACCESS ACCESSED ADD AFTER ALL ALTER AND ANY syn keyword plsqlSQLKeyword ASC ATTRIBUTE AUDIT AUTHORIZATION AVG BASE_TABLE @@ -565,7 +581,7 @@ syn keyword plsqlException SUBSCRIPT_OUTSIDE_LIMIT SYS_INVALID_ROWID syn keyword plsqlException TIMEOUT_ON_RESOURCE TOO_MANY_ROWS VALUE_ERROR syn keyword plsqlException ZERO_DIVIDE -if exists("plsql_highlight_triggers") +if get(g:,"plsql_highlight_triggers",0) == 1 syn keyword plsqlTrigger INSERTING UPDATING DELETING endif @@ -575,18 +591,18 @@ syn match plsqlEND "\<END\>" syn match plsqlISAS "\<\(IS\|AS\)\>" " Various types of comments. -syntax region plsqlCommentL start="--" skip="\\$" end="$" keepend extend contains=@plsqlCommentGroup,plsqlSpaceError -if exists("plsql_fold") +syntax region plsqlCommentL start="--" skip="\\$" end="$" keepend extend contains=@plsqlCommentGroup,plsqlSpaceError,plsqlIllegalSpace,plsqlSqlplusDefine +if get(g:,"plsql_fold",0) == 1 syntax region plsqlComment \ start="/\*" end="\*/" \ extend - \ contains=@plsqlCommentGroup,plsqlSpaceError + \ contains=@plsqlCommentGroup,plsqlSpaceError,plsqlIllegalSpace,plsqlSqlplusDefine \ fold else syntax region plsqlComment \ start="/\*" end="\*/" \ extend - \ contains=@plsqlCommentGroup,plsqlSpaceError + \ contains=@plsqlCommentGroup,plsqlSpaceError,plsqlIllegalSpace,plsqlSqlplusDefine endif syn cluster plsqlCommentAll contains=plsqlCommentL,plsqlComment @@ -609,23 +625,23 @@ syn match plsqlFloatLiteral contained "\.\(\d\+\([eE][+-]\?\d\+\)\?\)[fd]\?" " double quoted strings in SQL are database object names. Should be a subgroup of Normal. " We will use Character group as a proxy for that so color can be chosen close to Normal syn region plsqlQuotedIdentifier matchgroup=plsqlOperator start=+n\?"+ end=+"+ keepend extend -syn cluster plsqlIdentifiers contains=plsqlIdentifier,plsqlQuotedIdentifier +syn cluster plsqlIdentifiers contains=plsqlIdentifier,plsqlQuotedIdentifier,plsqlSqlPlusDefine " quoted string literals -if exists("plsql_fold") - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?'+ skip=+''+ end=+'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\z([^[(<{]\)+ end=+\z1'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'<+ end=+>'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'{+ end=+}'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'(+ end=+)'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\[+ end=+]'+ fold keepend extend +if get(g:,"plsql_fold",0) == 1 + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?'+ skip=+''+ end=+'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\z([^[(<{]\)+ end=+\z1'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'<+ end=+>'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'{+ end=+}'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'(+ end=+)'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\[+ end=+]'+ contains=plsqlSqlplusDefine fold keepend extend else - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?'+ skip=+''+ end=+'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\z([^[(<{]\)+ end=+\z1'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'<+ end=+>'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'{+ end=+}'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'(+ end=+)'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\[+ end=+]'+ + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?'+ skip=+''+ end=+'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\z([^[(<{]\)+ end=+\z1'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'<+ end=+>'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'{+ end=+}'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'(+ end=+)'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\[+ end=+]'+ contains=plsqlSqlplusDefine endif syn keyword plsqlBooleanLiteral TRUE FALSE @@ -639,10 +655,10 @@ syn match plsqlAttribute "%\(BULK_EXCEPTIONS\|BULK_ROWCOUNT\|ISOPEN\|FOUND\|NOTF " This'll catch mis-matched close-parens. syn cluster plsqlParenGroup contains=plsqlParenError,@plsqlCommentGroup,plsqlCommentSkip,plsqlIntLiteral,plsqlFloatLiteral,plsqlNumbersCom -if exists("plsql_bracket_error") +if get(g:,"plsql_bracket_error",0) == 1 " I suspect this code was copied from c.vim and never properly considered. Do " we even use braces or brackets in sql or pl/sql? - if exists("plsql_fold") + if get(g:,"plsql_fold",0) == 1 syn region plsqlParen start='(' end=')' contains=ALLBUT,@plsqlParenGroup,plsqlErrInBracket fold keepend extend transparent else syn region plsqlParen transparent start='(' end=')' contains=ALLBUT,@plsqlParenGroup,plsqlErrInBracket @@ -652,7 +668,7 @@ if exists("plsql_bracket_error") syn region plsqlBracket transparent start='\[' end=']' contains=ALLBUT,@plsqlParenGroup,plsqlErrInParen syn match plsqlErrInBracket contained "[);{}]" else - if exists("plsql_fold") + if get(g:,"plsql_fold",0) == 1 syn region plsqlParen start='(' end=')' contains=ALLBUT,@plsqlParenGroup,plsqlErrInParen fold keepend extend transparent else syn region plsqlParen transparent start='(' end=')' contains=ALLBUT,@plsqlParenGroup,plsqlErrInParen @@ -673,12 +689,16 @@ syn match plsqlConditional "\<END\>\_s\+\<IF\>" syn match plsqlCase "\<END\>\_s\+\<CASE\>" syn match plsqlCase "\<CASE\>" -if exists("plsql_fold") +syn region plsqlSqlPlusCommentL start="^\(REM\)\( \|$\)" skip="\\$" end="$" keepend extend contains=@plsqlCommentGroup,plsqlSpaceError,plsqlIllegalSpace +syn region plsqlSqlPlusCommand start="^\(SET\|DEFINE\|PROMPT\|ACCEPT\|EXEC\|HOST\|SHOW\|VAR\|VARIABLE\|COL\|WHENEVER\|TIMING\)\( \|$\)" skip="\\$" end="$" keepend extend +syn region plsqlSqlPlusRunFile start="^\(@\|@@\)" skip="\\$" end="$" keepend extend + +if get(g:,"plsql_fold",0) == 1 setlocal foldmethod=syntax syn sync fromstart syn cluster plsqlProcedureGroup contains=plsqlProcedure - syn cluster plsqlOnlyGroup contains=@plsqlProcedure,plsqlConditionalBlock,plsqlLoopBlock,plsqlBlock + syn cluster plsqlOnlyGroup contains=@plsqlProcedure,plsqlConditionalBlock,plsqlLoopBlock,plsqlBlock,plsqlCursor syntax region plsqlUpdateSet \ start="\(\<update\>\_s\+\(\<set\>\)\@![a-z][a-z0-9$_#]*\_s\+\(\(\<set\>\)\@![a-z][a-z0-9$_#]*\_s\+\)\?\)\|\(\<when\>\_s\+\<matched\>\_s\+\<then\>\_s\+\<update\>\_s\+\)\<set\>" @@ -698,24 +718,40 @@ if exists("plsql_fold") \ transparent \ contains=ALLBUT,@plsqlOnlyGroup,plsqlUpdateSet - " this is brute force and requires you have the procedure/function name in the END - " statement. ALthough Oracle makes it optional, we cannot. If you do not - " have it, then you can fold the BEGIN/END block of the procedure but not - " the specification of it (other than a paren group). You also cannot fold - " BEGIN/END blocks in the procedure body. Local procedures will fold as - " long as the END statement includes the procedure/function name. - " As for why we cannot make it work any other way, I don't know. It is - " something to do with both plsqlBlock and plsqlProcedure both consuming BEGIN and END, - " even if we use a lookahead for one of them. - syntax region plsqlProcedure - "\ start="\(create\(\_s\+or\_s\+replace\)\?\_s\+\)\?\<\(procedure\|function\)\>\_s\+\z([a-z][a-z0-9$_#]*\)" - \ start="\<\(procedure\|function\)\>\_s\+\(\z([a-z][a-z0-9$_#]*\)\)\([^;]\|\n\)\{-}\<\(is\|as\)\>\_.\{-}\(\<end\>\_s\+\2\_s*;\)\@=" - \ end="\<end\>\_s\+\z1\_s*;" + if get(g:,"plsql_disable_procedure_fold",0) == 0 + " this is brute force and requires you have the procedure/function name in the END + " statement. ALthough Oracle makes it optional, we cannot. If you do not + " have it, then you can fold the BEGIN/END block of the procedure but not + " the specification of it (other than a paren group). You also cannot fold + " BEGIN/END blocks in the procedure body. Local procedures will fold as + " long as the END statement includes the procedure/function name. + " As for why we cannot make it work any other way, I don't know. It is + " something to do with both plsqlBlock and plsqlProcedure both consuming BEGIN and END, + " even if we use a lookahead for one of them. + " + " If you habitualy do not put the method name in the END statement, + " this can be expensive because it searches to end of file on every + " procedure/function declaration + " + "\ start="\(create\(\_s\+or\_s\+replace\)\?\_s\+\)\?\<\(procedure\|function\)\>\_s\+\z([a-z][a-z0-9$_#]*\)" + syntax region plsqlProcedure + \ start="\<\(procedure\|function\)\>\_s\+\(\z([a-z][a-z0-9$_#]*\)\)\([^;]\|\n\)\{-}\<\(is\|as\)\>\_.\{-}\(\<end\>\_s\+\2\_s*;\)\@=" + \ end="\<end\>\_s\+\z1\_s*;" + \ fold + \ keepend + \ extend + \ transparent + \ contains=ALLBUT,plsqlBlock + endif + + syntax region plsqlCursor + \ start="\<cursor\>\_s\+[a-z][a-z0-9$_#]*\(\_s*([^)]\+)\)\?\(\_s\+return\_s\+\S\+\)\?\_s\+is" + \ end=";" \ fold \ keepend \ extend \ transparent - \ contains=ALLBUT,plsqlBlock + \ contains=ALLBUT,@plsqlOnlyGroup syntax region plsqlBlock \ start="\<begin\>" @@ -801,8 +837,15 @@ hi def link plsqlComment2String String hi def link plsqlTrigger Function hi def link plsqlTypeAttribute StorageClass hi def link plsqlTodo Todo + +hi def link plsqlIllegalSpace Error +hi def link plsqlSqlPlusDefine PreProc +hi def link plsqlSqlPlusCommand PreProc +hi def link plsqlSqlPlusRunFile Include +hi def link plsqlSqlPlusCommentL Comment + " to be able to change them after loading, need override whether defined or not -if exists("plsql_legacy_sql_keywords") +if get(g:,"plsql_legacy_sql_keywords",0) == 1 hi link plsqlSQLKeyword Function hi link plsqlSymbol Normal hi link plsqlParen Normal diff --git a/runtime/syntax/racket.vim b/runtime/syntax/racket.vim new file mode 100644 index 0000000000..b1ed2b454c --- /dev/null +++ b/runtime/syntax/racket.vim @@ -0,0 +1,656 @@ +" Vim syntax file +" Language: Racket +" Maintainer: D. Ben Knoble <ben.knoble+github@gmail.com> +" Previous Maintainer: Will Langstroth <will@langstroth.com> +" URL: https://github.com/benknoble/vim-racket +" Description: Contains all of the keywords in #lang racket +" Last Change: 2022 Aug 12 + +" Initializing: +if exists("b:current_syntax") + finish +endif + +" Highlight unmatched parens +syntax match racketError ,[]})], + +if version < 800 + set iskeyword=33,35-39,42-58,60-90,94,95,97-122,126,_ +else + " syntax iskeyword 33,35-39,42-58,60-90,94,95,97-122,126,_ + " converted from decimal to char + " :s/\d\+/\=submatch(0)->str2nr()->nr2char()/g + " but corrected to remove duplicate _, move ^ to end + syntax iskeyword @,!,#-',*-:,<-Z,a-z,~,_,^ + " expanded + " syntax iskeyword !,#,$,%,&,',*,+,,,-,.,/,0-9,:,<,=,>,?,@,A-Z,_,a-z,~,^ +endif + +" Forms in order of appearance at +" http://docs.racket-lang.org/reference/index.html +" +syntax keyword racketSyntax module module* module+ require provide quote +syntax keyword racketSyntax #%datum #%expression #%top #%variable-reference #%app +syntax keyword racketSyntax lambda case-lambda let let* letrec +syntax keyword racketSyntax let-values let*-values let-syntax letrec-syntax +syntax keyword racketSyntax let-syntaxes letrec-syntaxes letrec-syntaxes+values +syntax keyword racketSyntax local shared +syntax keyword racketSyntax if cond and or case define else => +syntax keyword racketSyntax define define-values define-syntax define-syntaxes +syntax keyword racketSyntax define-for-syntax define-require-syntax define-provide-syntax +syntax keyword racketSyntax define-syntax-rule +syntax keyword racketSyntax define-record-type +syntax keyword racketSyntax begin begin0 +syntax keyword racketSyntax begin-for-syntax +syntax keyword racketSyntax when unless +syntax keyword racketSyntax set! set!-values +syntax keyword racketSyntax for for/list for/vector for/hash for/hasheq for/hasheqv +syntax keyword racketSyntax for/and for/or for/lists for/first +syntax keyword racketSyntax for/last for/fold +syntax keyword racketSyntax for* for*/list for*/vector for*/hash for*/hasheq for*/hasheqv +syntax keyword racketSyntax for*/and for*/or for*/lists for*/first +syntax keyword racketSyntax for*/last for*/fold +syntax keyword racketSyntax for/fold/derived for*/fold/derived +syntax keyword racketSyntax define-sequence-syntax :do-in do +syntax keyword racketSyntax with-continuation-mark +syntax keyword racketSyntax quasiquote unquote unquote-splicing quote-syntax +syntax keyword racketSyntax #%top-interaction +syntax keyword racketSyntax define-package open-package package-begin +syntax keyword racketSyntax define* define*-values define*-syntax define*-syntaxes open*-package +syntax keyword racketSyntax package? package-exported-identifiers package-original-identifiers +syntax keyword racketSyntax block #%stratified-body + +" 8 Contracts +" 8.2 Function contracts +syntax keyword racketSyntax -> ->* ->i ->d case-> dynamic->* unconstrained-domain-> + +" 8.6.1 Nested Contract Boundaries +syntax keyword racketSyntax with-contract define/contract define-struct/contract +syntax keyword racketSyntax invariant-assertion current-contract-region + +" 9 Pattern Matching +syntax keyword racketSyntax match match* match/values define/match +syntax keyword racketSyntax match-lambda match-lambda* match-lambda** +syntax keyword racketSyntax match-let match-let* match-let-values match-let*-values +syntax keyword racketSyntax match-letrec match-define match-define-values + +" 10.2.3 Handling Exceptions +syntax keyword racketSyntax with-handlers with-handlers* + +" 10.4 Continuations +syntax keyword racketSyntax let/cc let/ec + +" 10.4.1 Additional Control Operators +syntax keyword racketSyntax % prompt control prompt-at control-at reset shift +syntax keyword racketSyntax reset-at shift-at prompt0 reset0 control0 shift0 +syntax keyword racketSyntax prompt0-at reset0-at control0-at shift0-at +syntax keyword racketSyntax set cupto + +" 11.3.2 Parameters +syntax keyword racketSyntax parameterize parameterize* + +" 12.5 Writing +syntax keyword racketSyntax write display displayln print +syntax keyword racketSyntax fprintf printf eprintf format +syntax keyword racketSyntax print-pair-curly-braces print-mpair-curly-braces print-unreadable +syntax keyword racketSyntax print-graph print-struct print-box print-vector-length print-hash-table +syntax keyword racketSyntax print-boolean-long-form print-reader-abbreviations print-as-expression print-syntax-width +syntax keyword racketSyntax current-write-relative-directory port-write-handler port-display-handler +syntax keyword racketSyntax port-print-handler global-port-print-handler + +" 13.7 Custodians +syntax keyword racketSyntax custodian? custodian-memory-accounting-available? custodian-box? +syntax keyword racketSyntax make-custodian custodian-shutdown-all current-custodian custodian-managed-list +syntax keyword racketSyntax custodian-require-memory custodian-limit-memory +syntax keyword racketSyntax make-custodian-box custodian-box-value + +" lambda sign +syntax match racketSyntax /\<[\u03bb]\>/ + + +" Functions ================================================================== + +syntax keyword racketFunc boolean? not equal? eqv? eq? equal?/recur immutable? +syntax keyword racketFunc true false symbol=? boolean=? false? +syntax keyword racketFunc number? complex? real? rational? integer? +syntax keyword racketFunc exact-integer? exact-nonnegative-integer? +syntax keyword racketFunc exact-positive-integer? inexact-real? +syntax keyword racketFunc fixnum? flonum? zero? positive? negative? +syntax keyword racketFunc even? odd? exact? inexact? +syntax keyword racketFunc inexact->exact exact->inexact + +" 3.2.2 General Arithmetic + +" 3.2.2.1 Arithmetic +syntax keyword racketFunc + - * / quotient remainder quotient/remainder modulo +syntax keyword racketFunc add1 sub1 abs max min gcd lcm round exact-round floor +syntax keyword racketFunc ceiling truncate numerator denominator rationalize + +" 3.2.2.2 Number Comparison +syntax keyword racketFunc = < <= > >= + +" 3.2.2.3 Powers and Roots +syntax keyword racketFunc sqrt integer-sqrt integer-sqrt/remainder +syntax keyword racketFunc expt exp log + +" 3.2.2.3 Trigonometric Functions +syntax keyword racketFunc sin cos tan asin acos atan + +" 3.2.2.4 Complex Numbers +syntax keyword racketFunc make-rectangular make-polar +syntax keyword racketFunc real-part imag-part magnitude angle +syntax keyword racketFunc bitwise-ior bitwise-and bitwise-xor bitwise-not +syntax keyword racketFunc bitwise-bit-set? bitwise-bit-field arithmetic-shift +syntax keyword racketFunc integer-length + +" 3.2.2.5 Random Numbers +syntax keyword racketFunc random random-seed +syntax keyword racketFunc make-pseudo-random-generator pseudo-random-generator? +syntax keyword racketFunc current-pseudo-random-generator pseudo-random-generator->vector +syntax keyword racketFunc vector->pseudo-random-generator vector->pseudo-random-generator! + +" 3.2.2.8 Number-String Conversions +syntax keyword racketFunc number->string string->number real->decimal-string +syntax keyword racketFunc integer->integer-bytes +syntax keyword racketFunc floating-point-bytes->real real->floating-point-bytes +syntax keyword racketFunc system-big-endian? + +" 3.2.2.9 Extra Constants and Functions +syntax keyword racketFunc pi sqr sgn conjugate sinh cosh tanh order-of-magnitude + +" 3.2.3 Flonums + +" 3.2.3.1 Flonum Arithmetic +syntax keyword racketFunc fl+ fl- fl* fl/ flabs +syntax keyword racketFunc fl= fl< fl> fl<= fl>= flmin flmax +syntax keyword racketFunc flround flfloor flceiling fltruncate +syntax keyword racketFunc flsin flcos fltan flasin flacos flatan +syntax keyword racketFunc fllog flexp flsqrt +syntax keyword racketFunc ->fl fl->exact-integer make-flrectangular +syntax keyword racketFunc flreal-part flimag-part + +" 3.2.3.2 Flonum Vectors +syntax keyword racketFunc flvector? flvector make-flvector flvector-length +syntax keyword racketFunc flvector-ref flvector-set! flvector-copy in-flvector +syntax keyword racketFunc shared-flvector make-shared-flvector +syntax keyword racketSyntax for/flvector for*/flvector + +" 3.2.4 Fixnums +syntax keyword racketFunc fx+ fx- fx* fxquotient fxremainder fxmodulo fxabs +syntax keyword racketFunc fxand fxior fxxor fxnot fxlshift fxrshift +syntax keyword racketFunc fx= fx< fx> fx<= fx>= fxmin fxmax fx->fl fl->fx + +" 3.2.4.2 Fixnum Vectors +syntax keyword racketFunc fxvector? fxvector make-fxvector fxvector-length +syntax keyword racketFunc fxvector-ref fxvector-set! fxvector-copy in-fxvector +syntax keyword racketFunc for/fxvector for*/fxvector +syntax keyword racketFunc shared-fxvector make-shared-fxvector + +" 3.3 Strings +syntax keyword racketFunc string? make-string string string->immutable-string string-length +syntax keyword racketFunc string-ref string-set! substring string-copy string-copy! +syntax keyword racketFunc string-fill! string-append string->list list->string +syntax keyword racketFunc build-string string=? string<? string<=? string>? string>=? +syntax keyword racketFunc string-ci=? string-ci<? string-ci<=? string-ci>? string-ci>=? +syntax keyword racketFunc string-upcase string-downcase string-titlecase string-foldcase +syntax keyword racketFunc string-normalize-nfd string-normalize-nfc string-normalize-nfkc +syntax keyword racketFunc string-normalize-spaces string-trim +syntax keyword racketFunc string-locale=? string-locale>? string-locale<? +syntax keyword racketFunc string-locale-ci=? string-locale<=? +syntax keyword racketFunc string-locale-upcase string-locale-downcase +syntax keyword racketFunc string-append* string-join + +" 3.4 Bytestrings +syntax keyword racketFunc bytes? make-bytes bytes bytes->immutable-bytes byte? +syntax keyword racketFunc bytes-length bytes-ref bytes-set! subbytes bytes-copy +syntax keyword racketFunc bytes-copy! bytes-fill! bytes-append bytes->list list->bytes +syntax keyword racketFunc make-shared-bytes shared-bytes +syntax keyword racketFunc bytes=? bytes<? bytes>? +syntax keyword racketFunc bytes->string/utf-8 bytes->string/latin-1 +syntax keyword racketFunc string->bytes/locale string->bytes/latin-1 string->bytes/utf-8 +syntax keyword racketFunc string-utf-8-length bytes-utf8-ref bytes-utf-8-index +syntax keyword racketFunc bytes-open-converter bytes-close-converter +syntax keyword racketFunc bytes-convert bytes-convert-end bytes-converter? +syntax keyword racketFunc locale-string-encoding + +" 3.5 Characters +syntax keyword racketFunc char? char->integer integer->char +syntax keyword racketFunc char=? char<? char<=? char>? char>=? +syntax keyword racketFunc char-ci=? char-ci<? char-ci<=? char-ci>? char-ci>=? +syntax keyword racketFunc char-alphabetic? char-lower-case? char-upper-case? char-title-case? +syntax keyword racketFunc char-numeric? char-symbolic? char-punctuation? char-graphic? +syntax keyword racketFunc char-whitespace? char-blank? +syntax keyword racketFunc char-iso-control? char-general-category +syntax keyword racketFunc make-known-char-range-list +syntax keyword racketFunc char-upcase char-downcase char-titlecase char-foldcase + +" 3.6 Symbols +syntax keyword racketFunc symbol? symbol-interned? symbol-unreadable? +syntax keyword racketFunc symbol->string string->symbol +syntax keyword racketFunc string->uninterned-symbol string->unreadable-symbol +syntax keyword racketFunc gensym + +" 3.7 Regular Expressions +syntax keyword racketFunc regexp? pregexp? byte-regexp? byte-pregexp? +syntax keyword racketFunc regexp pregexp byte-regexp byte-pregexp +syntax keyword racketFunc regexp-quote regexp-match regexp-match* +syntax keyword racketFunc regexp-try-match regexp-match-positions +syntax keyword racketFunc regexp-match-positions* regexp-match? +syntax keyword racketFunc regexp-match-peek-positions regexp-match-peek-immediate +syntax keyword racketFunc regexp-match-peek regexp-match-peek-positions* +syntax keyword racketFunc regexp-match/end regexp-match-positions/end +syntax keyword racketFunc regexp-match-peek-positions-immediat/end +syntax keyword racketFunc regexp-split regexp-replace regexp-replace* +syntax keyword racketFunc regexp-replace-quote + +" 3.8 Keywords +syntax keyword racketFunc keyword? keyword->string string->keyword keyword<? + +" 3.9 Pairs and Lists +syntax keyword racketFunc pair? null? cons car cdr null +syntax keyword racketFunc list? list list* build-list length +syntax keyword racketFunc list-ref list-tail append reverse map andmap ormap +syntax keyword racketFunc for-each foldl foldr filter remove remq remv remove* +syntax keyword racketFunc remq* remv* sort member memv memq memf +syntax keyword racketFunc findf assoc assv assq assf +syntax keyword racketFunc caar cadr cdar cddr caaar caadr cadar caddr cdaar +syntax keyword racketFunc cddar cdddr caaaar caaadr caadar caaddr cadadr caddar +syntax keyword racketFunc cadddr cdaaar cdaadr cdadar cddaar cdddar cddddr + +" 3.9.7 Additional List Functions and Synonyms +" (require racket/list) +syntax keyword racketFunc empty cons? empty? first rest +syntax keyword racketFunc second third fourth fifth sixth seventh eighth ninth tenth +syntax keyword racketFunc last last-pair make-list take drop split-at +syntax keyword racketFunc take-right drop-right split-at-right add-between +syntax keyword racketFunc append* flatten remove-duplicates filter-map +syntax keyword racketFunc count partition append-map filter-not shuffle +syntax keyword racketFunc argmin argmax make-reader-graph placeholder? make-placeholder +syntax keyword racketFunc placeholder-set! placeholder-get hash-placeholder? +syntax keyword racketFunc make-hash-placeholder make-hasheq-placeholder +syntax keyword racketFunc make-hasheqv-placeholder make-immutable-hasheqv + +" 3.10 Mutable Pairs and Lists +syntax keyword racketFunc mpair? mcons mcar mcdr + +" 3.11 Vectors +syntax keyword racketFunc vector? make-vector vector vector-immutable vector-length +syntax keyword racketFunc vector-ref vector-set! vector->list list->vector +syntax keyword racketFunc vector->immutable-vector vector-fill! vector-copy! +syntax keyword racketFunc vector->values build-vector vector-set*! vector-map +syntax keyword racketFunc vector-map! vector-append vector-take vector-take-right +syntax keyword racketFunc vector-drop vector-drop-right vector-split-at +syntax keyword racketFunc vector-split-at-right vector-copy vector-filter +syntax keyword racketFunc vector-filter-not vector-count vector-argmin vector-argmax +syntax keyword racketFunc vector-member vector-memv vector-memq + +" 3.12 Boxes +syntax keyword racketFunc box? box box-immutable unbox set-box! + +" 3.13 Hash Tables +syntax keyword racketFunc hash? hash-equal? hash-eqv? hash-eq? hash-weak? hash +syntax keyword racketFunc hasheq hasheqv +syntax keyword racketFunc make-hash make-hasheqv make-hasheq make-weak-hash make-weak-hasheqv +syntax keyword racketFunc make-weak-hasheq make-immutable-hash make-immutable-hasheqv +syntax keyword racketFunc make-immutable-hasheq +syntax keyword racketFunc hash-set! hash-set*! hash-set hash-set* hash-ref hash-ref! +syntax keyword racketFunc hash-has-key? hash-update! hash-update hash-remove! +syntax keyword racketFunc hash-remove hash-map hash-keys hash-values +syntax keyword racketFunc hash->list hash-for-each hash-count +syntax keyword racketFunc hash-iterate-first hash-iterate-next hash-iterate-key +syntax keyword racketFunc hash-iterate-value hash-copy eq-hash-code eqv-hash-code +syntax keyword racketFunc equal-hash-code equal-secondary-hash-code + +" 3.15 Dictionaries +syntax keyword racketFunc dict? dict-mutable? dict-can-remove-keys? dict-can-functional-set? +syntax keyword racketFunc dict-set! dict-set*! dict-set dict-set* dict-has-key? dict-ref +syntax keyword racketFunc dict-ref! dict-update! dict-update dict-remove! dict-remove +syntax keyword racketFunc dict-map dict-for-each dict-count dict-iterate-first dict-iterate-next +syntax keyword racketFunc dict-iterate-key dict-iterate-value in-dict in-dict-keys +syntax keyword racketFunc in-dict-values in-dict-pairs dict-keys dict-values +syntax keyword racketFunc dict->list prop: dict prop: dict/contract dict-key-contract +syntax keyword racketFunc dict-value-contract dict-iter-contract make-custom-hash +syntax keyword racketFunc make-immutable-custom-hash make-weak-custom-hash + +" 3.16 Sets +syntax keyword racketFunc set seteqv seteq set-empty? set-count set-member? +syntax keyword racketFunc set-add set-remove set-union set-intersect set-subtract +syntax keyword racketFunc set-symmetric-difference set=? subset? proper-subset? +syntax keyword racketFunc set-map set-for-each set? set-equal? set-eqv? set-eq? +syntax keyword racketFunc set/c in-set for/set for/seteq for/seteqv for*/set +syntax keyword racketFunc for*/seteq for*/seteqv list->set list->seteq +syntax keyword racketFunc list->seteqv set->list + +" 3.17 Procedures +syntax keyword racketFunc procedure? apply compose compose1 procedure-rename procedure->method +syntax keyword racketFunc keyword-apply procedure-arity procedure-arity? +syntax keyword racketFunc procedure-arity-includes? procedure-reduce-arity +syntax keyword racketFunc procedure-keywords make-keyword-procedure +syntax keyword racketFunc procedure-reduce-keyword-arity procedure-struct-type? +syntax keyword racketFunc procedure-extract-target checked-procedure-check-and-extract +syntax keyword racketFunc primitive? primitive-closure? primitive-result-arity +syntax keyword racketFunc identity const thunk thunk* negate curry curryr + +" 3.18 Void +syntax keyword racketFunc void void? + +" 4.1 Defining Structure Types +syntax keyword racketFunc struct struct-field-index define-struct define-struct define-struct/derived + +" 4.2 Creating Structure Types +syntax keyword racketFunc make-struct-type make-struct-field-accessor make-struct-field-mutator + +" 4.3 Structure Type Properties +syntax keyword racketFunc make-struct-type-property struct-type-property? struct-type-property-accessor-procedure? + +" 4.4 Copying and Updating Structures +syntax keyword racketFunc struct-copy + +" 4.5 Structure Utilities +syntax keyword racketFunc struct->vector struct? struct-type? +syntax keyword racketFunc struct-constructor-procedure? struct-predicate-procedure? struct-accessor-procedure? struct-mutator-procedure? +syntax keyword racketFunc prefab-struct-key make-prefab-struct prefab-key->struct-type + +" 4.6 Structure Type Transformer Binding +syntax keyword racketFunc struct-info? check-struct-info? make-struct-info extract-struct-info +syntax keyword racketFunc struct-auto-info? struct-auto-info-lists + +" 5.1 Creating Interfaces +syntax keyword racketFunc interface interface* + +" 5.2 Creating Classes +syntax keyword racketFunc class* class inspect +syntax keyword racketFunc init init-field field inherit field init-rest +syntax keyword racketFunc public public* pubment pubment* public-final public-final* +syntax keyword racketFunc override override* overment overment* override-final override-final* +syntax keyword racketFunc augride augride* augment augment* augment-final augment-final* +syntax keyword racketFunc abstract inherit inherit/super inherit/inner +syntax keyword racketFunc rename-inner rename-super +syntax keyword racketFunc define/public define/pubment define/public-final +syntax keyword racketFunc define/override define/overment define/override-final +syntax keyword racketFunc define/augride define/augment define/augment-final +syntax keyword racketFunc private* define/private + +" 5.2.3 Methods +syntax keyword racketFunc class/derived +syntax keyword racketFunc super inner define-local-member-name define-member-name +syntax keyword racketFunc member-name-key generate-member-key member-name-key? +syntax keyword racketFunc member-name-key=? member-name-key-hash-code + +" 5.3 Creating Objects +syntax keyword racketFunc make-object instantiate new +syntax keyword racketFunc super-make-object super-instantiate super-new + +"5.4 Field and Method Access +syntax keyword racketFunc method-id send send/apply send/keyword-apply dynamic-send send* +syntax keyword racketFunc get-field set-field! field-bound? +syntax keyword racketFunc class-field-accessor class-field-mutator + +"5.4.3 Generics +syntax keyword racketFunc generic send-generic make-generic + +" 8.1 Data-strucure contracts +syntax keyword racketFunc flat-contract-with-explanation flat-named-contract +" TODO where do any/c and none/c `value`s go? +syntax keyword racketFunc or/c first-or/c and/c not/c =/c </c >/c <=/c >=/c +syntax keyword racketFunc between/c real-in integer-in char-in natural-number/c +syntax keyword racketFunc string-len/c printable/c one-of/c symbols vectorof +syntax keyword racketFunc vector-immutableof vector/c box/c box-immutable/c listof +syntax keyword racketFunc non-empty-listof list*of cons/c cons/dc list/c *list/c +syntax keyword racketFunc syntax/c struct/c struct/dc parameter/c +syntax keyword racketFunc procedure-arity-includes/c hash/c hash/dc channel/c +syntax keyword racketFunc prompt-tag/c continuation-mark-key/c evt/c promise/c +syntax keyword racketFunc flat-contract flat-contract-predicate suggest/c + +" 9.1 Multiple Values +syntax keyword racketFunc values call-with-values + +" 10.2.2 Raising Exceptions +syntax keyword racketFunc raise error raise-user-error raise-argument-error +syntax keyword racketFunc raise-result-error raise-argument-error raise-range-error +syntax keyword racketFunc raise-type-error raise-mismatch-error raise-arity-error +syntax keyword racketFunc raise-syntax-error + +" 10.2.3 Handling Exceptions +syntax keyword racketFunc call-with-exception-handler uncaught-exception-handler + +" 10.2.4 Configuring Default Handlers +syntax keyword racketFunc error-escape-handler error-display-handler error-print-width +syntax keyword racketFunc error-print-context-length error-values->string-handler +syntax keyword racketFunc error-print-source-location + +" 10.2.5 Built-in Exception Types +syntax keyword racketFunc exn exn:fail exn:fail:contract exn:fail:contract:arity +syntax keyword racketFunc exn:fail:contract:divide-by-zero exn:fail:contract:non-fixnum-result +syntax keyword racketFunc exn:fail:contract:continuation exn:fail:contract:variable +syntax keyword racketFunc exn:fail:syntax exn:fail:syntax:unbound exn:fail:syntax:missing-module +syntax keyword racketFunc exn:fail:read exn:fail:read:eof exn:fail:read:non-char +syntax keyword racketFunc exn:fail:filesystem exn:fail:filesystem:exists +syntax keyword racketFunc exn:fail:filesystem:version exn:fail:filesystem:errno +syntax keyword racketFunc exn:fail:filesystem:missing-module +syntax keyword racketFunc exn:fail:network exn:fail:network:errno exn:fail:out-of-memory +syntax keyword racketFunc exn:fail:unsupported exn:fail:user +syntax keyword racketFunc exn:break exn:break:hang-up exn:break:terminate + +" 10.3 Delayed Evaluation +syntax keyword racketFunc promise? delay lazy force promise-forced? promise-running? + +" 10.3.1 Additional Promise Kinds +syntax keyword racketFunc delay/name promise/name delay/strict delay/sync delay/thread delay/idle + +" 10.4 Continuations +syntax keyword racketFunc call-with-continuation-prompt abort-current-continuation make-continuation-prompt-tag +syntax keyword racketFunc default-continuation-prompt-tag call-with-current-continuation call/cc +syntax keyword racketFunc call-with-composable-continuation call-with-escape-continuation call/ec +syntax keyword racketFunc call-with-continuation-barrier continuation-prompt-available +syntax keyword racketFunc continuation? continuation-prompt-tag dynamic-wind + +" 10.4.1 Additional Control Operators +syntax keyword racketFunc call/prompt abort/cc call/comp abort fcontrol spawn splitter new-prompt + +" 11.3.2 Parameters +syntax keyword racketFunc make-parameter make-derived-parameter parameter? +syntax keyword racketFunc parameter-procedure=? current-parameterization +syntax keyword racketFunc call-with-parameterization parameterization? + +" 14.1.1 Manipulating Paths +syntax keyword racketFunc path? path-string? path-for-some-system? string->path path->string path->bytes +syntax keyword racketFunc string->path-element bytes->path-element path-element->string path-element->bytes +syntax keyword racketFunc path-convention-type system-path-convention-type build-type +syntax keyword racketFunc build-type/convention-type +syntax keyword racketFunc absolute-path? relative-path? complete-path? +syntax keyword racketFunc path->complete-path path->directory-path +syntax keyword racketFunc resolve-path cleanse-path expand-user-path simplify-path normal-case-path split-path +syntax keyword racketFunc path-replace-suffix path-add-suffix + +" 14.1.2 More Path Utilities +syntax keyword racketFunc explode-path file-name-from-path filename-extension find-relative-path normalize-path +syntax keyword racketFunc path-element? path-only simple-form-path some-simple-path->string string->some-system-path + +" 15.6 Time +syntax keyword racketFunc current-seconds current-inexact-milliseconds +syntax keyword racketFunc seconds->date current-milliseconds + + +syntax match racketDelimiter !\<\.\>! + +syntax cluster racketTop contains=racketSyntax,racketFunc,racketDelimiter + +syntax match racketConstant ,\<\*\k\+\*\>, +syntax match racketConstant ,\<<\k\+>\>, + +" Non-quoted lists, and strings +syntax region racketStruc matchgroup=racketParen start="("rs=s+1 end=")"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="#("rs=s+2 end=")"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="{"rs=s+1 end="}"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="#{"rs=s+2 end="}"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="\["rs=s+1 end="\]"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="#\["rs=s+2 end="\]"re=e-1 contains=@racketTop + +for lit in ['hash', 'hasheq', 'hasheqv'] + execute printf('syntax match racketLit "\<%s\>" nextgroup=@racketParen containedin=ALLBUT,.*String,.*Comment', '#'.lit) +endfor + +for lit in ['rx', 'rx#', 'px', 'px#'] + execute printf('syntax match racketRe "\<%s\>" nextgroup=@racketString containedin=ALLBUT,.*String,.*Comment,', '#'.lit) +endfor + +unlet lit + +" Simple literals + +" Strings + +syntax match racketStringEscapeError "\\." contained display + +syntax match racketStringEscape "\\[abtnvfre'"\\]" contained display +syntax match racketStringEscape "\\$" contained display +syntax match racketStringEscape "\\\o\{1,3}\|\\x\x\{1,2}" contained display + +syntax match racketUStringEscape "\\u\x\{1,4}\|\\U\x\{1,8}" contained display +syntax match racketUStringEscape "\\u\x\{4}\\u\x\{4}" contained display + +syntax region racketString start=/\%(\\\)\@<!"/ skip=/\\[\\"]/ end=/"/ contains=racketStringEscapeError,racketStringEscape,racketUStringEscape +syntax region racketString start=/#"/ skip=/\\[\\"]/ end=/"/ contains=racketStringEscapeError,racketStringEscape + +if exists("racket_no_string_fold") + syn region racketString start=/#<<\z(.*\)$/ end=/^\z1$/ +else + syn region racketString start=/#<<\z(.*\)$/ end=/^\z1$/ fold +endif + + +syntax cluster racketTop add=racketError,racketConstant,racketStruc,racketString + +" Numbers + +" anything which doesn't match the below rules, but starts with a #d, #b, #o, +" #x, #i, or #e, is an error +syntax match racketNumberError "\<#[xdobie]\k*" + +syntax match racketContainedNumberError "\<#o\k*[^-+0-7delfinas#./@]\>" +syntax match racketContainedNumberError "\<#b\k*[^-+01delfinas#./@]\>" +syntax match racketContainedNumberError "\<#[ei]#[ei]" +syntax match racketContainedNumberError "\<#[xdob]#[xdob]" + +" start with the simpler sorts +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\d\+/\d\+\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\d\+/\d\+[-+]\d\+\(/\d\+\)\?i\>" contains=racketContainedNumberError + +" different possible ways of expressing complex values +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?[-+]\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f][-+]\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?[-+]\(inf\|nan\)\.[0f]i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?@[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f]@[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?@[-+]\(inf\|nan\)\.[0f]\>" contains=racketContainedNumberError + +" hex versions of the above (separate because of the different possible exponent markers) +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\x\+/\x\+\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\x\+/\x\+[-+]\x\+\(/\x\+\)\?i\>" + +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?i\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?[-+]\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?i\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\(inf\|nan\)\.[0f][-+]\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?i\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?[-+]\(inf\|nan\)\.[0f]i\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?@[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\(inf\|nan\)\.[0f]@[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?@[-+]\(inf\|nan\)\.[0f]\>" + +" these work for any radix +syntax match racketNumber "\<\(#[xdobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f]i\?\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[xdobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f][-+]\(inf\|nan\)\.[0f]i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[xdobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f]@[-+]\(inf\|nan\)\.[0f]\>" contains=racketContainedNumberError + +syntax keyword racketBoolean #t #f #true #false #T #F + +syntax match racketError "\<#\\\k*\>" + +syntax match racketChar "\<#\\.\w\@!" +syntax match racketChar "\<#\\space\>" +syntax match racketChar "\<#\\newline\>" +syntax match racketChar "\<#\\return\>" +syntax match racketChar "\<#\\null\?\>" +syntax match racketChar "\<#\\backspace\>" +syntax match racketChar "\<#\\tab\>" +syntax match racketChar "\<#\\linefeed\>" +syntax match racketChar "\<#\\vtab\>" +syntax match racketChar "\<#\\page\>" +syntax match racketChar "\<#\\rubout\>" +syntax match racketChar "\<#\\\o\{1,3}\>" +syntax match racketChar "\<#\\x\x\{1,2}\>" +syntax match racketChar "\<#\\u\x\{1,6}\>" + +syntax cluster racketTop add=racketNumber,racketBoolean,racketChar + +" Command-line parsing +syntax keyword racketExtFunc command-line current-command-line-arguments once-any help-labels multi once-each + +syntax match racketSyntax "#lang " +syntax match racketExtSyntax "#:\k\+" + +syntax cluster racketTop add=racketExtFunc,racketExtSyntax + +" syntax quoting, unquoting and quasiquotation +syntax match racketQuote "#\?['`]" + +syntax match racketUnquote "#," +syntax match racketUnquote "#,@" +syntax match racketUnquote "," +syntax match racketUnquote ",@" + +" Comments +syntax match racketSharpBang "\%^#![ /].*" display +syntax match racketComment /;.*$/ contains=racketTodo,racketNote,@Spell +syntax region racketMultilineComment start=/#|/ end=/|#/ contains=racketMultilineComment,racketTodo,racketNote,@Spell +syntax match racketFormComment "#;" nextgroup=@racketTop + +syntax match racketTodo /\C\<\(FIXME\|TODO\|XXX\)\ze:\?\>/ contained +syntax match racketNote /\CNOTE\ze:\?/ contained + +syntax cluster racketTop add=racketQuote,racketUnquote,racketComment,racketMultilineComment,racketFormComment + +" Synchronization and the wrapping up... +syntax sync match matchPlace grouphere NONE "^[^ \t]" +" ... i.e. synchronize on a line that starts at the left margin + +" Define the default highlighting. +highlight default link racketSyntax Statement +highlight default link racketFunc Function + +highlight default link racketString String +highlight default link racketStringEscape Special +highlight default link racketUStringEscape Special +highlight default link racketStringEscapeError Error +highlight default link racketChar Character +highlight default link racketBoolean Boolean + +highlight default link racketNumber Number +highlight default link racketNumberError Error +highlight default link racketContainedNumberError Error + +highlight default link racketQuote SpecialChar +highlight default link racketUnquote SpecialChar + +highlight default link racketDelimiter Delimiter +highlight default link racketParen Delimiter +highlight default link racketConstant Constant + +highlight default link racketLit Type +highlight default link racketRe Type + +highlight default link racketComment Comment +highlight default link racketMultilineComment Comment +highlight default link racketFormComment SpecialChar +highlight default link racketSharpBang Comment +highlight default link racketTodo Todo +highlight default link racketNote SpecialComment +highlight default link racketError Error + +highlight default link racketExtSyntax Type +highlight default link racketExtFunc PreProc + +let b:current_syntax = "racket" diff --git a/runtime/syntax/sh.vim b/runtime/syntax/sh.vim index e44699faa5..822b1a9ed2 100644 --- a/runtime/syntax/sh.vim +++ b/runtime/syntax/sh.vim @@ -2,8 +2,8 @@ " Language: shell (sh) Korn shell (ksh) bash (sh) " Maintainer: Charles E. Campbell <NcampObell@SdrPchip.AorgM-NOSPAM> " Previous Maintainer: Lennart Schultz <Lennart.Schultz@ecmwf.int> -" Last Change: Jun 29, 2022 -" Version: 202 +" Last Change: Jul 08, 2022 +" Version: 203 " URL: http://www.drchip.org/astronaut/vim/index.html#SYNTAX_SH " For options and settings, please use: :help ft-sh-syntax " This file includes many ideas from Eric Brunet (eric.brunet@ens.fr) and heredoc fixes from Felipe Contreras @@ -141,7 +141,7 @@ endif syn cluster shArithParenList contains=shArithmetic,shArithParen,shCaseEsac,shComment,shDeref,shDo,shDerefSimple,shEcho,shEscape,shNumber,shOperator,shPosnParm,shExSingleQuote,shExDoubleQuote,shHereString,shRedir,shSingleQuote,shDoubleQuote,shStatement,shVariable,shAlias,shTest,shCtrlSeq,shSpecial,shParen,bashSpecialVariables,bashStatement,shIf,shFor,shFunctionKey,shFunctionOne,shFunctionTwo syn cluster shArithList contains=@shArithParenList,shParenError syn cluster shCaseEsacList contains=shCaseStart,shCaseLabel,shCase,shCaseBar,shCaseIn,shComment,shDeref,shDerefSimple,shCaseCommandSub,shCaseExSingleQuote,shCaseSingleQuote,shCaseDoubleQuote,shCtrlSeq,@shErrorList,shStringSpecial,shCaseRange -syn cluster shCaseList contains=@shCommandSubList,shCaseEsac,shColon,shCommandSub,shCommandSubBQ,shComment,shDo,shEcho,shExpr,shFor,shHereDoc,shIf,shHereString,shRedir,shSetList,shSource,shStatement,shVariable,shCtrlSeq +syn cluster shCaseList contains=@shCommandSubList,shCaseEsac,shColon,shCommandSub,shCommandSubBQ,shComment,shDblBrace,shDo,shEcho,shExpr,shFor,shHereDoc,shIf,shHereString,shRedir,shSetList,shSource,shStatement,shVariable,shCtrlSeq if exists("b:is_kornshell") || exists("b:is_bash") syn cluster shCaseList add=shForPP endif diff --git a/runtime/syntax/solidity.vim b/runtime/syntax/solidity.vim new file mode 100644 index 0000000000..e552446e10 --- /dev/null +++ b/runtime/syntax/solidity.vim @@ -0,0 +1,173 @@ +" Vim syntax file +" Language: Solidity +" Maintainer: Cothi (jiungdev@gmail.com) +" Original Author: tomlion (https://github.com/tomlion/vim-solidity/blob/master/syntax/solidity.vim) +" Last Changed: 2022 Sep 27 +" +" Additional contributors: +" Modified by thesis (https://github.com/thesis/vim-solidity/blob/main/indent/solidity.vim) + +if exists("b:current_syntax") + finish +endif + +" keyword +syn keyword solKeyword abstract anonymous as break calldata case catch constant constructor continue default switch revert require +syn keyword solKeyword ecrecover addmod mulmod keccak256 +syn keyword solKeyword delete do else emit enum external final for function if immutable import in indexed inline +syn keyword solKeyword interface internal is let match memory modifier new of payable pragma private public pure override virtual +syn keyword solKeyword relocatable return returns static storage struct throw try type typeof using +syn keyword solKeyword var view while + +syn keyword solConstant true false wei szabo finney ether seconds minutes hours days weeks years now +syn keyword solConstant abi block blockhash msg tx this super selfdestruct + +syn keyword solBuiltinType mapping address bool +syn keyword solBuiltinType int int8 int16 int24 int32 int40 int48 int56 int64 int72 int80 int88 int96 int104 int112 int120 int128 int136 int144 int152 int160 int168 int178 int184 int192 int200 int208 int216 int224 int232 int240 int248 int256 +syn keyword solBuiltinType uint uint8 uint16 uint24 uint32 uint40 uint48 uint56 uint64 uint72 uint80 uint88 uint96 uint104 uint112 uint120 uint128 uint136 uint144 uint152 uint160 uint168 uint178 uint184 uint192 uint200 uint208 uint216 uint224 uint232 uint240 uint248 uint256 +syn keyword solBuiltinType fixed +syn keyword solBuiltinType fixed0x8 fixed0x16 fixed0x24 fixed0x32 fixed0x40 fixed0x48 fixed0x56 fixed0x64 fixed0x72 fixed0x80 fixed0x88 fixed0x96 fixed0x104 fixed0x112 fixed0x120 fixed0x128 fixed0x136 fixed0x144 fixed0x152 fixed0x160 fixed0x168 fixed0x178 fixed0x184 fixed0x192 fixed0x200 fixed0x208 fixed0x216 fixed0x224 fixed0x232 fixed0x240 fixed0x248 fixed0x256 +syn keyword solBuiltinType fixed8x8 fixed8x16 fixed8x24 fixed8x32 fixed8x40 fixed8x48 fixed8x56 fixed8x64 fixed8x72 fixed8x80 fixed8x88 fixed8x96 fixed8x104 fixed8x112 fixed8x120 fixed8x128 fixed8x136 fixed8x144 fixed8x152 fixed8x160 fixed8x168 fixed8x178 fixed8x184 fixed8x192 fixed8x200 fixed8x208 fixed8x216 fixed8x224 fixed8x232 fixed8x240 fixed8x248 +syn keyword solBuiltinType fixed16x8 fixed16x16 fixed16x24 fixed16x32 fixed16x40 fixed16x48 fixed16x56 fixed16x64 fixed16x72 fixed16x80 fixed16x88 fixed16x96 fixed16x104 fixed16x112 fixed16x120 fixed16x128 fixed16x136 fixed16x144 fixed16x152 fixed16x160 fixed16x168 fixed16x178 fixed16x184 fixed16x192 fixed16x200 fixed16x208 fixed16x216 fixed16x224 fixed16x232 fixed16x240 +syn keyword solBuiltinType fixed24x8 fixed24x16 fixed24x24 fixed24x32 fixed24x40 fixed24x48 fixed24x56 fixed24x64 fixed24x72 fixed24x80 fixed24x88 fixed24x96 fixed24x104 fixed24x112 fixed24x120 fixed24x128 fixed24x136 fixed24x144 fixed24x152 fixed24x160 fixed24x168 fixed24x178 fixed24x184 fixed24x192 fixed24x200 fixed24x208 fixed24x216 fixed24x224 fixed24x232 +syn keyword solBuiltinType fixed32x8 fixed32x16 fixed32x24 fixed32x32 fixed32x40 fixed32x48 fixed32x56 fixed32x64 fixed32x72 fixed32x80 fixed32x88 fixed32x96 fixed32x104 fixed32x112 fixed32x120 fixed32x128 fixed32x136 fixed32x144 fixed32x152 fixed32x160 fixed32x168 fixed32x178 fixed32x184 fixed32x192 fixed32x200 fixed32x208 fixed32x216 fixed32x224 +syn keyword solBuiltinType fixed40x8 fixed40x16 fixed40x24 fixed40x32 fixed40x40 fixed40x48 fixed40x56 fixed40x64 fixed40x72 fixed40x80 fixed40x88 fixed40x96 fixed40x104 fixed40x112 fixed40x120 fixed40x128 fixed40x136 fixed40x144 fixed40x152 fixed40x160 fixed40x168 fixed40x178 fixed40x184 fixed40x192 fixed40x200 fixed40x208 fixed40x216 +syn keyword solBuiltinType fixed48x8 fixed48x16 fixed48x24 fixed48x32 fixed48x40 fixed48x48 fixed48x56 fixed48x64 fixed48x72 fixed48x80 fixed48x88 fixed48x96 fixed48x104 fixed48x112 fixed48x120 fixed48x128 fixed48x136 fixed48x144 fixed48x152 fixed48x160 fixed48x168 fixed48x178 fixed48x184 fixed48x192 fixed48x200 fixed48x208 +syn keyword solBuiltinType fixed56x8 fixed56x16 fixed56x24 fixed56x32 fixed56x40 fixed56x48 fixed56x56 fixed56x64 fixed56x72 fixed56x80 fixed56x88 fixed56x96 fixed56x104 fixed56x112 fixed56x120 fixed56x128 fixed56x136 fixed56x144 fixed56x152 fixed56x160 fixed56x168 fixed56x178 fixed56x184 fixed56x192 fixed56x200 +syn keyword solBuiltinType fixed64x8 fixed64x16 fixed64x24 fixed64x32 fixed64x40 fixed64x48 fixed64x56 fixed64x64 fixed64x72 fixed64x80 fixed64x88 fixed64x96 fixed64x104 fixed64x112 fixed64x120 fixed64x128 fixed64x136 fixed64x144 fixed64x152 fixed64x160 fixed64x168 fixed64x178 fixed64x184 fixed64x192 +syn keyword solBuiltinType fixed72x8 fixed72x16 fixed72x24 fixed72x32 fixed72x40 fixed72x48 fixed72x56 fixed72x64 fixed72x72 fixed72x80 fixed72x88 fixed72x96 fixed72x104 fixed72x112 fixed72x120 fixed72x128 fixed72x136 fixed72x144 fixed72x152 fixed72x160 fixed72x168 fixed72x178 fixed72x184 +syn keyword solBuiltinType fixed80x8 fixed80x16 fixed80x24 fixed80x32 fixed80x40 fixed80x48 fixed80x56 fixed80x64 fixed80x72 fixed80x80 fixed80x88 fixed80x96 fixed80x104 fixed80x112 fixed80x120 fixed80x128 fixed80x136 fixed80x144 fixed80x152 fixed80x160 fixed80x168 fixed80x178 +syn keyword solBuiltinType fixed88x8 fixed88x16 fixed88x24 fixed88x32 fixed88x40 fixed88x48 fixed88x56 fixed88x64 fixed88x72 fixed88x80 fixed88x88 fixed88x96 fixed88x104 fixed88x112 fixed88x120 fixed88x128 fixed88x136 fixed88x144 fixed88x152 fixed88x160 fixed88x168 +syn keyword solBuiltinType fixed96x8 fixed96x16 fixed96x24 fixed96x32 fixed96x40 fixed96x48 fixed96x56 fixed96x64 fixed96x72 fixed96x80 fixed96x88 fixed96x96 fixed96x104 fixed96x112 fixed96x120 fixed96x128 fixed96x136 fixed96x144 fixed96x152 fixed96x160 +syn keyword solBuiltinType fixed104x8 fixed104x16 fixed104x24 fixed104x32 fixed104x40 fixed104x48 fixed104x56 fixed104x64 fixed104x72 fixed104x80 fixed104x88 fixed104x96 fixed104x104 fixed104x112 fixed104x120 fixed104x128 fixed104x136 fixed104x144 fixed104x152 +syn keyword solBuiltinType fixed112x8 fixed112x16 fixed112x24 fixed112x32 fixed112x40 fixed112x48 fixed112x56 fixed112x64 fixed112x72 fixed112x80 fixed112x88 fixed112x96 fixed112x104 fixed112x112 fixed112x120 fixed112x128 fixed112x136 fixed112x144 +syn keyword solBuiltinType fixed120x8 fixed120x16 fixed120x24 fixed120x32 fixed120x40 fixed120x48 fixed120x56 fixed120x64 fixed120x72 fixed120x80 fixed120x88 fixed120x96 fixed120x104 fixed120x112 fixed120x120 fixed120x128 fixed120x136 +syn keyword solBuiltinType fixed128x8 fixed128x16 fixed128x24 fixed128x32 fixed128x40 fixed128x48 fixed128x56 fixed128x64 fixed128x72 fixed128x80 fixed128x88 fixed128x96 fixed128x104 fixed128x112 fixed128x120 fixed128x128 +syn keyword solBuiltinType fixed136x8 fixed136x16 fixed136x24 fixed136x32 fixed136x40 fixed136x48 fixed136x56 fixed136x64 fixed136x72 fixed136x80 fixed136x88 fixed136x96 fixed136x104 fixed136x112 fixed136x120 +syn keyword solBuiltinType fixed144x8 fixed144x16 fixed144x24 fixed144x32 fixed144x40 fixed144x48 fixed144x56 fixed144x64 fixed144x72 fixed144x80 fixed144x88 fixed144x96 fixed144x104 fixed144x112 +syn keyword solBuiltinType fixed152x8 fixed152x16 fixed152x24 fixed152x32 fixed152x40 fixed152x48 fixed152x56 fixed152x64 fixed152x72 fixed152x80 fixed152x88 fixed152x96 fixed152x104 +syn keyword solBuiltinType fixed160x8 fixed160x16 fixed160x24 fixed160x32 fixed160x40 fixed160x48 fixed160x56 fixed160x64 fixed160x72 fixed160x80 fixed160x88 fixed160x96 +syn keyword solBuiltinType fixed168x8 fixed168x16 fixed168x24 fixed168x32 fixed168x40 fixed168x48 fixed168x56 fixed168x64 fixed168x72 fixed168x80 fixed168x88 +syn keyword solBuiltinType fixed176x8 fixed176x16 fixed176x24 fixed176x32 fixed176x40 fixed176x48 fixed176x56 fixed176x64 fixed176x72 fixed176x80 +syn keyword solBuiltinType fixed184x8 fixed184x16 fixed184x24 fixed184x32 fixed184x40 fixed184x48 fixed184x56 fixed184x64 fixed184x72 +syn keyword solBuiltinType fixed192x8 fixed192x16 fixed192x24 fixed192x32 fixed192x40 fixed192x48 fixed192x56 fixed192x64 +syn keyword solBuiltinType fixed200x8 fixed200x16 fixed200x24 fixed200x32 fixed200x40 fixed200x48 fixed200x56 +syn keyword solBuiltinType fixed208x8 fixed208x16 fixed208x24 fixed208x32 fixed208x40 fixed208x48 +syn keyword solBuiltinType fixed216x8 fixed216x16 fixed216x24 fixed216x32 fixed216x40 +syn keyword solBuiltinType fixed224x8 fixed224x16 fixed224x24 fixed224x32 +syn keyword solBuiltinType fixed232x8 fixed232x16 fixed232x24 +syn keyword solBuiltinType fixed240x8 fixed240x16 +syn keyword solBuiltinType fixed248x8 +syn keyword solBuiltinType ufixed +syn keyword solBuiltinType ufixed0x8 ufixed0x16 ufixed0x24 ufixed0x32 ufixed0x40 ufixed0x48 ufixed0x56 ufixed0x64 ufixed0x72 ufixed0x80 ufixed0x88 ufixed0x96 ufixed0x104 ufixed0x112 ufixed0x120 ufixed0x128 ufixed0x136 ufixed0x144 ufixed0x152 ufixed0x160 ufixed0x168 ufixed0x178 ufixed0x184 ufixed0x192 ufixed0x200 ufixed0x208 ufixed0x216 ufixed0x224 ufixed0x232 ufixed0x240 ufixed0x248 ufixed0x256 +syn keyword solBuiltinType ufixed8x8 ufixed8x16 ufixed8x24 ufixed8x32 ufixed8x40 ufixed8x48 ufixed8x56 ufixed8x64 ufixed8x72 ufixed8x80 ufixed8x88 ufixed8x96 ufixed8x104 ufixed8x112 ufixed8x120 ufixed8x128 ufixed8x136 ufixed8x144 ufixed8x152 ufixed8x160 ufixed8x168 ufixed8x178 ufixed8x184 ufixed8x192 ufixed8x200 ufixed8x208 ufixed8x216 ufixed8x224 ufixed8x232 ufixed8x240 ufixed8x248 +syn keyword solBuiltinType ufixed16x8 ufixed16x16 ufixed16x24 ufixed16x32 ufixed16x40 ufixed16x48 ufixed16x56 ufixed16x64 ufixed16x72 ufixed16x80 ufixed16x88 ufixed16x96 ufixed16x104 ufixed16x112 ufixed16x120 ufixed16x128 ufixed16x136 ufixed16x144 ufixed16x152 ufixed16x160 ufixed16x168 ufixed16x178 ufixed16x184 ufixed16x192 ufixed16x200 ufixed16x208 ufixed16x216 ufixed16x224 ufixed16x232 ufixed16x240 +syn keyword solBuiltinType ufixed24x8 ufixed24x16 ufixed24x24 ufixed24x32 ufixed24x40 ufixed24x48 ufixed24x56 ufixed24x64 ufixed24x72 ufixed24x80 ufixed24x88 ufixed24x96 ufixed24x104 ufixed24x112 ufixed24x120 ufixed24x128 ufixed24x136 ufixed24x144 ufixed24x152 ufixed24x160 ufixed24x168 ufixed24x178 ufixed24x184 ufixed24x192 ufixed24x200 ufixed24x208 ufixed24x216 ufixed24x224 ufixed24x232 +syn keyword solBuiltinType ufixed32x8 ufixed32x16 ufixed32x24 ufixed32x32 ufixed32x40 ufixed32x48 ufixed32x56 ufixed32x64 ufixed32x72 ufixed32x80 ufixed32x88 ufixed32x96 ufixed32x104 ufixed32x112 ufixed32x120 ufixed32x128 ufixed32x136 ufixed32x144 ufixed32x152 ufixed32x160 ufixed32x168 ufixed32x178 ufixed32x184 ufixed32x192 ufixed32x200 ufixed32x208 ufixed32x216 ufixed32x224 +syn keyword solBuiltinType ufixed40x8 ufixed40x16 ufixed40x24 ufixed40x32 ufixed40x40 ufixed40x48 ufixed40x56 ufixed40x64 ufixed40x72 ufixed40x80 ufixed40x88 ufixed40x96 ufixed40x104 ufixed40x112 ufixed40x120 ufixed40x128 ufixed40x136 ufixed40x144 ufixed40x152 ufixed40x160 ufixed40x168 ufixed40x178 ufixed40x184 ufixed40x192 ufixed40x200 ufixed40x208 ufixed40x216 +syn keyword solBuiltinType ufixed48x8 ufixed48x16 ufixed48x24 ufixed48x32 ufixed48x40 ufixed48x48 ufixed48x56 ufixed48x64 ufixed48x72 ufixed48x80 ufixed48x88 ufixed48x96 ufixed48x104 ufixed48x112 ufixed48x120 ufixed48x128 ufixed48x136 ufixed48x144 ufixed48x152 ufixed48x160 ufixed48x168 ufixed48x178 ufixed48x184 ufixed48x192 ufixed48x200 ufixed48x208 +syn keyword solBuiltinType ufixed56x8 ufixed56x16 ufixed56x24 ufixed56x32 ufixed56x40 ufixed56x48 ufixed56x56 ufixed56x64 ufixed56x72 ufixed56x80 ufixed56x88 ufixed56x96 ufixed56x104 ufixed56x112 ufixed56x120 ufixed56x128 ufixed56x136 ufixed56x144 ufixed56x152 ufixed56x160 ufixed56x168 ufixed56x178 ufixed56x184 ufixed56x192 ufixed56x200 +syn keyword solBuiltinType ufixed64x8 ufixed64x16 ufixed64x24 ufixed64x32 ufixed64x40 ufixed64x48 ufixed64x56 ufixed64x64 ufixed64x72 ufixed64x80 ufixed64x88 ufixed64x96 ufixed64x104 ufixed64x112 ufixed64x120 ufixed64x128 ufixed64x136 ufixed64x144 ufixed64x152 ufixed64x160 ufixed64x168 ufixed64x178 ufixed64x184 ufixed64x192 +syn keyword solBuiltinType ufixed72x8 ufixed72x16 ufixed72x24 ufixed72x32 ufixed72x40 ufixed72x48 ufixed72x56 ufixed72x64 ufixed72x72 ufixed72x80 ufixed72x88 ufixed72x96 ufixed72x104 ufixed72x112 ufixed72x120 ufixed72x128 ufixed72x136 ufixed72x144 ufixed72x152 ufixed72x160 ufixed72x168 ufixed72x178 ufixed72x184 +syn keyword solBuiltinType ufixed80x8 ufixed80x16 ufixed80x24 ufixed80x32 ufixed80x40 ufixed80x48 ufixed80x56 ufixed80x64 ufixed80x72 ufixed80x80 ufixed80x88 ufixed80x96 ufixed80x104 ufixed80x112 ufixed80x120 ufixed80x128 ufixed80x136 ufixed80x144 ufixed80x152 ufixed80x160 ufixed80x168 ufixed80x178 +syn keyword solBuiltinType ufixed88x8 ufixed88x16 ufixed88x24 ufixed88x32 ufixed88x40 ufixed88x48 ufixed88x56 ufixed88x64 ufixed88x72 ufixed88x80 ufixed88x88 ufixed88x96 ufixed88x104 ufixed88x112 ufixed88x120 ufixed88x128 ufixed88x136 ufixed88x144 ufixed88x152 ufixed88x160 ufixed88x168 +syn keyword solBuiltinType ufixed96x8 ufixed96x16 ufixed96x24 ufixed96x32 ufixed96x40 ufixed96x48 ufixed96x56 ufixed96x64 ufixed96x72 ufixed96x80 ufixed96x88 ufixed96x96 ufixed96x104 ufixed96x112 ufixed96x120 ufixed96x128 ufixed96x136 ufixed96x144 ufixed96x152 ufixed96x160 +syn keyword solBuiltinType ufixed104x8 ufixed104x16 ufixed104x24 ufixed104x32 ufixed104x40 ufixed104x48 ufixed104x56 ufixed104x64 ufixed104x72 ufixed104x80 ufixed104x88 ufixed104x96 ufixed104x104 ufixed104x112 ufixed104x120 ufixed104x128 ufixed104x136 ufixed104x144 ufixed104x152 +syn keyword solBuiltinType ufixed112x8 ufixed112x16 ufixed112x24 ufixed112x32 ufixed112x40 ufixed112x48 ufixed112x56 ufixed112x64 ufixed112x72 ufixed112x80 ufixed112x88 ufixed112x96 ufixed112x104 ufixed112x112 ufixed112x120 ufixed112x128 ufixed112x136 ufixed112x144 +syn keyword solBuiltinType ufixed120x8 ufixed120x16 ufixed120x24 ufixed120x32 ufixed120x40 ufixed120x48 ufixed120x56 ufixed120x64 ufixed120x72 ufixed120x80 ufixed120x88 ufixed120x96 ufixed120x104 ufixed120x112 ufixed120x120 ufixed120x128 ufixed120x136 +syn keyword solBuiltinType ufixed128x8 ufixed128x16 ufixed128x24 ufixed128x32 ufixed128x40 ufixed128x48 ufixed128x56 ufixed128x64 ufixed128x72 ufixed128x80 ufixed128x88 ufixed128x96 ufixed128x104 ufixed128x112 ufixed128x120 ufixed128x128 +syn keyword solBuiltinType ufixed136x8 ufixed136x16 ufixed136x24 ufixed136x32 ufixed136x40 ufixed136x48 ufixed136x56 ufixed136x64 ufixed136x72 ufixed136x80 ufixed136x88 ufixed136x96 ufixed136x104 ufixed136x112 ufixed136x120 +syn keyword solBuiltinType ufixed144x8 ufixed144x16 ufixed144x24 ufixed144x32 ufixed144x40 ufixed144x48 ufixed144x56 ufixed144x64 ufixed144x72 ufixed144x80 ufixed144x88 ufixed144x96 ufixed144x104 ufixed144x112 +syn keyword solBuiltinType ufixed152x8 ufixed152x16 ufixed152x24 ufixed152x32 ufixed152x40 ufixed152x48 ufixed152x56 ufixed152x64 ufixed152x72 ufixed152x80 ufixed152x88 ufixed152x96 ufixed152x104 +syn keyword solBuiltinType ufixed160x8 ufixed160x16 ufixed160x24 ufixed160x32 ufixed160x40 ufixed160x48 ufixed160x56 ufixed160x64 ufixed160x72 ufixed160x80 ufixed160x88 ufixed160x96 +syn keyword solBuiltinType ufixed168x8 ufixed168x16 ufixed168x24 ufixed168x32 ufixed168x40 ufixed168x48 ufixed168x56 ufixed168x64 ufixed168x72 ufixed168x80 ufixed168x88 +syn keyword solBuiltinType ufixed176x8 ufixed176x16 ufixed176x24 ufixed176x32 ufixed176x40 ufixed176x48 ufixed176x56 ufixed176x64 ufixed176x72 ufixed176x80 +syn keyword solBuiltinType ufixed184x8 ufixed184x16 ufixed184x24 ufixed184x32 ufixed184x40 ufixed184x48 ufixed184x56 ufixed184x64 ufixed184x72 +syn keyword solBuiltinType ufixed192x8 ufixed192x16 ufixed192x24 ufixed192x32 ufixed192x40 ufixed192x48 ufixed192x56 ufixed192x64 +syn keyword solBuiltinType ufixed200x8 ufixed200x16 ufixed200x24 ufixed200x32 ufixed200x40 ufixed200x48 ufixed200x56 +syn keyword solBuiltinType ufixed208x8 ufixed208x16 ufixed208x24 ufixed208x32 ufixed208x40 ufixed208x48 +syn keyword solBuiltinType ufixed216x8 ufixed216x16 ufixed216x24 ufixed216x32 ufixed216x40 +syn keyword solBuiltinType ufixed224x8 ufixed224x16 ufixed224x24 ufixed224x32 +syn keyword solBuiltinType ufixed232x8 ufixed232x16 ufixed232x24 +syn keyword solBuiltinType ufixed240x8 ufixed240x16 +syn keyword solBuiltinType ufixed248x8 +syn keyword solBuiltinType string string1 string2 string3 string4 string5 string6 string7 string8 string9 string10 string11 string12 string13 string14 string15 string16 string17 string18 string19 string20 string21 string22 string23 string24 string25 string26 string27 string28 string29 string30 string31 string32 +syn keyword solBuiltinType byte bytes bytes1 bytes2 bytes3 bytes4 bytes5 bytes6 bytes7 bytes8 bytes9 bytes10 bytes11 bytes12 bytes13 bytes14 bytes15 bytes16 bytes17 bytes18 bytes19 bytes20 bytes21 bytes22 bytes23 bytes24 bytes25 bytes26 bytes27 bytes28 bytes29 bytes30 bytes31 bytes32 + +hi def link solKeyword Keyword +hi def link solConstant Constant +hi def link solBuiltinType Type +hi def link solBuiltinFunction Keyword + +syn match solOperator /\(!\||\|&\|+\|-\|<\|>\|=\|%\|\/\|*\|\~\|\^\)/ +syn match solNumber /\<-\=\d\+L\=\>\|\<0[xX]\x\+\>/ +syn match solFloat /\<-\=\%(\d\+\.\d\+\|\d\+\.\|\.\d\+\)\%([eE][+-]\=\d\+\)\=\>/ + +syn region solString start=+"+ skip=+\\\\\|\\$"\|\\"+ end=+"+ +syn region solString start=+'+ skip=+\\\\\|\\$'\|\\'+ end=+'+ + +hi def link solOperator Operator +hi def link solNumber Number +hi def link solFloat Float +hi def link solString String + +" Function +syn match solFunction /\<function\>/ nextgroup=solFuncName,solFuncArgs skipwhite +syn match solFuncName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*/ nextgroup=solFuncArgs skipwhite + +syn region solFuncArgs contained matchgroup=solFuncParens start='(' end=')' contains=solFuncArgCommas,solBuiltinType nextgroup=solModifierName,solFuncReturns,solFuncBody keepend skipwhite skipempty +syn match solModifierName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*/ nextgroup=solModifierArgs,solModifierName skipwhite +syn region solModifierArgs contained matchgroup=solFuncParens start='(' end=')' contains=solFuncArgCommas nextgroup=solModifierName,solFuncReturns,solFuncBody skipwhite +syn region solFuncReturns contained matchgroup=solFuncParens nextgroup=solFuncBody start='(' end=')' contains=solFuncArgCommas,solBuiltinType skipwhite + +syn match solFuncArgCommas contained ',' +syn region solFuncBody start="{" end="}" fold transparent + +hi def link solFunction Type +hi def link solFuncName Function +hi def link solModifierName Function + +" Yul blocks +syn match yul /\<assembly\>/ skipwhite skipempty nextgroup=yulBody +syn region yulBody contained start='{' end='}' fold contains=yulAssemblyOp,solNumber,yulVarDeclaration,solLineComment,solComment skipwhite skipempty +syn keyword yulAssemblyOp contained stop add sub mul div sdiv mod smod exp not lt gt slt sgt eq iszero and or xor byte shl shr sar addmod mulmod signextend keccak256 pc pop mload mstore mstore8 sload sstore msize gas address balance selfbalance caller callvalue calldataload calldatasize calldatacopy codesize codecopy extcodesize extcodecopy returndatasize returndatacopy extcodehash create create2 call callcode delegatecall staticcall return revert selfdestruct invalid log0 log1 log2 log3 log4 chainid basefee origin gasprice blockhash coinbase timestamp number difficulty gaslimit +syn keyword yulVarDeclaration contained let + +hi def link yul Keyword +hi def link yulVarDeclaration Keyword +hi def link yulAssemblyOp Keyword + +" Contract +syn match solContract /\<\%(contract\|library\|interface\)\>/ nextgroup=solContractName skipwhite +syn match solContractName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*/ nextgroup=solContractParent skipwhite +syn region solContractParent contained start='is' end='{' contains=solContractName,solContractNoise,solContractCommas skipwhite skipempty +syn match solContractNoise contained 'is' containedin=solContractParent +syn match solContractCommas contained ',' + +hi def link solContract Type +hi def link solContractName Function + +" Event +syn match solEvent /\<event\>/ nextgroup=solEventName,solEventArgs skipwhite +syn match solEventName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*/ nextgroup=solEventArgs skipwhite +syn region solEventArgs contained matchgroup=solFuncParens start='(' end=')' contains=solEventArgCommas,solBuiltinType,solEventArgSpecial skipwhite skipempty +syn match solEventArgCommas contained ',' +syn match solEventArgSpecial contained 'indexed' + +hi def link solEvent Type +hi def link solEventName Function +hi def link solEventArgSpecial Label + +" Comment +syn keyword solCommentTodo TODO FIXME XXX TBD contained +syn match solNatSpec contained /@title\|@author\|@notice\|@dev\|@param\|@inheritdoc\|@return/ +syn region solLineComment start=+\/\/+ end=+$+ contains=solCommentTodo,solNatSpec,@Spell +syn region solLineComment start=+^\s*\/\/+ skip=+\n\s*\/\/+ end=+$+ contains=solCommentTodo,solNatSpec,@Spell fold +syn region solComment start="/\*" end="\*/" contains=solCommentTodo,solNatSpec,@Spell fold + +hi def link solCommentTodo Todo +hi def link solNatSpec Label +hi def link solLineComment Comment +hi def link solComment Comment + +let b:current_syntax = "solidity" diff --git a/runtime/syntax/srt.vim b/runtime/syntax/srt.vim new file mode 100644 index 0000000000..12fb264d8e --- /dev/null +++ b/runtime/syntax/srt.vim @@ -0,0 +1,62 @@ +" Vim syntax file +" Language: SubRip +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: *.srt +" Last Change: 2022 Sep 12 + +if exists('b:current_syntax') + finish +endif + +syn spell toplevel + +syn cluster srtSpecial contains=srtBold,srtItalics,srtStrikethrough,srtUnderline,srtFont,srtTag,srtEscape + +" Number +syn match srtNumber /^\d\+$/ contains=@NoSpell + +" Range +syn match srtRange /\d\d:\d\d:\d\d[,.]\d\d\d --> \d\d:\d\d:\d\d[,.]\d\d\d/ skipwhite contains=srtArrow,srtTime nextgroup=srtCoordinates +syn match srtArrow /-->/ contained contains=@NoSpell +syn match srtTime /\d\d:\d\d:\d\d[,.]\d\d\d/ contained contains=@NoSpell +syn match srtCoordinates /X1:\d\+ X2:\d\+ Y1:\d\+ Y2:\d\+/ contained contains=@NoSpell + +" Bold +syn region srtBold matchgroup=srtFormat start=+<b>+ end=+</b>+ contains=@srtSpecial +syn region srtBold matchgroup=srtFormat start=+{b}+ end=+{/b}+ contains=@srtSpecial + +" Italics +syn region srtItalics matchgroup=srtFormat start=+<i>+ end=+</i>+ contains=@srtSpecial +syn region srtItalics matchgroup=srtFormat start=+{i}+ end=+{/i}+ contains=@srtSpecial + +" Strikethrough +syn region srtStrikethrough matchgroup=srtFormat start=+<s>+ end=+</s>+ contains=@srtSpecial +syn region srtStrikethrough matchgroup=srtFormat start=+{s}+ end=+{/s}+ contains=@srtSpecial + +" Underline +syn region srtUnderline matchgroup=srtFormat start=+<u>+ end=+</u>+ contains=@srtSpecial +syn region srtUnderline matchgroup=srtFormat start=+{u}+ end=+{/u}+ contains=@srtSpecial + +" Font +syn region srtFont matchgroup=srtFormat start=+<font[^>]\{-}>+ end=+</font>+ contains=@srtSpecial + +" ASS tags +syn match srtTag /{\\[^}]\{1,}}/ contains=@NoSpell + +" Special characters +syn match srtEscape /\\[nNh]/ contains=@NoSpell + +hi def link srtArrow Delimiter +hi def link srtCoordinates Label +hi def link srtEscape SpecialChar +hi def link srtFormat Special +hi def link srtNumber Number +hi def link srtTag PreProc +hi def link srtTime String + +hi srtBold cterm=bold gui=bold +hi srtItalics cterm=italic gui=italic +hi srtStrikethrough cterm=strikethrough gui=strikethrough +hi srtUnderline cterm=underline gui=underline + +let b:current_syntax = 'srt' diff --git a/runtime/syntax/synload.vim b/runtime/syntax/synload.vim index b88cd95103..056e38bf79 100644 --- a/runtime/syntax/synload.vim +++ b/runtime/syntax/synload.vim @@ -30,7 +30,7 @@ fun! s:SynSet() unlet b:current_syntax endif - let s = expand("<amatch>") + 0verbose let s = expand("<amatch>") if s == "ON" " :set syntax=ON if &filetype == "" diff --git a/runtime/syntax/syntax.vim b/runtime/syntax/syntax.vim index ac7dc314b9..5ec99c7e05 100644 --- a/runtime/syntax/syntax.vim +++ b/runtime/syntax/syntax.vim @@ -27,12 +27,13 @@ else endif " Set up the connection between FileType and Syntax autocommands. -" This makes the syntax automatically set when the file type is detected. +" This makes the syntax automatically set when the file type is detected +" unless treesitter highlighting is enabled. +" Avoid an error when 'verbose' is set and <amatch> expansion fails. augroup syntaxset - au! FileType * exe "set syntax=" . expand("<amatch>") + au! FileType * if !exists('b:ts_highlight') | 0verbose exe "set syntax=" . expand("<amatch>") | endif augroup END - " Execute the syntax autocommands for the each buffer. " If the filetype wasn't detected yet, do that now. " Always do the syntaxset autocommands, for buffers where the 'filetype' diff --git a/runtime/syntax/vdf.vim b/runtime/syntax/vdf.vim new file mode 100644 index 0000000000..c690b706ea --- /dev/null +++ b/runtime/syntax/vdf.vim @@ -0,0 +1,54 @@ +" Vim syntax file +" Language: Valve Data Format +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: *.vdf +" Last Change: 2022 Sep 15 + +if exists('b:current_syntax') + finish +endif + +let s:cpo_save = &cpoptions +set cpoptions&vim + +" Comment +syn keyword vdfTodo contained TODO FIXME XXX +syn match vdfComment +//.*+ contains=vdfTodo + +" Macro +syn match vdfMacro /^\s*#.*/ + +" Tag +syn region vdfTag start=/"/ skip=/\\"/ end=/"/ + \ nextgroup=vdfValue skipwhite oneline + +" Section +syn region vdfSection matchgroup=vdfBrace + \ start=/{/ end=/}/ transparent fold + \ contains=vdfTag,vdfSection,vdfComment,vdfConditional + +" Conditional +syn match vdfConditional /\[\$\w\{1,1021}\]/ nextgroup=vdfTag + +" Value +syn region vdfValue start=/"/ skip=/\\"/ end=/"/ + \ oneline contained contains=vdfVariable,vdfNumber,vdfEscape +syn region vdfVariable start=/%/ skip=/\\%/ end=/%/ oneline contained +syn match vdfEscape /\\[nt\\"]/ contained +syn match vdfNumber /"-\?\d\+"/ contained + +hi def link vdfBrace Delimiter +hi def link vdfComment Comment +hi def link vdfConditional Constant +hi def link vdfEscape SpecialChar +hi def link vdfMacro Macro +hi def link vdfNumber Number +hi def link vdfTag Keyword +hi def link vdfTodo Todo +hi def link vdfValue String +hi def link vdfVariable Identifier + +let b:current_syntax = 'vdf' + +let &cpoptions = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/vim.vim b/runtime/syntax/vim.vim index 2b1c58c449..6ace5ffef3 100644 --- a/runtime/syntax/vim.vim +++ b/runtime/syntax/vim.vim @@ -53,7 +53,7 @@ syn case ignore syn keyword vimGroup contained Comment Constant String Character Number Boolean Float Identifier Function Statement Conditional Repeat Label Operator Keyword Exception PreProc Include Define Macro PreCondit Type StorageClass Structure Typedef Special SpecialChar Tag Delimiter SpecialComment Debug Underlined Ignore Error Todo " Default highlighting groups {{{2 -syn keyword vimHLGroup contained ColorColumn Cursor CursorColumn CursorIM CursorLine CursorLineFold CursorLineNr CursorLineSign DiffAdd DiffChange DiffDelete DiffText Directory EndOfBuffer ErrorMsg FoldColumn Folded IncSearch LineNr MatchParen Menu ModeMsg MoreMsg NonText Normal Pmenu PmenuSbar PmenuSel PmenuThumb Question QuickFixLine Scrollbar Search SignColumn SpecialKey SpellBad SpellCap SpellLocal SpellRare StatusLine StatusLineNC TabLine TabLineFill TabLineSel Title Tooltip VertSplit Visual WarningMsg WildMenu +syn keyword vimHLGroup contained ColorColumn Cursor CursorColumn CursorIM CursorLine CursorLineFold CursorLineNr CursorLineSign DiffAdd DiffChange DiffDelete DiffText Directory EndOfBuffer ErrorMsg FoldColumn Folded IncSearch LineNr MatchParen Menu MessageWindow ModeMsg MoreMsg NonText Normal Pmenu PmenuSbar PmenuSel PmenuThumb Question QuickFixLine Scrollbar Search SignColumn SpecialKey SpellBad SpellCap SpellLocal SpellRare StatusLine StatusLineNC TabLine TabLineFill TabLineSel Title Tooltip VertSplit Visual WarningMsg WildMenu syn match vimHLGroup contained "Conceal" syn keyword vimOnlyHLGroup contained LineNrAbove LineNrBelow StatusLineTerm Terminal VisualNOS syn keyword nvimHLGroup contained Substitute TermCursor TermCursorNC @@ -368,7 +368,7 @@ syn match vimSetMod contained "&vim\=\|[!&?<]\|all&" " Let: {{{2 " === syn keyword vimLet let unl[et] skipwhite nextgroup=vimVar,vimFuncVar,vimLetHereDoc -VimFoldh syn region vimLetHereDoc matchgroup=vimLetHereDocStart start='=<<\s\+\%(trim\|eval\>\)\=\s*\z(\L\S*\)' matchgroup=vimLetHereDocStop end='^\s*\z1\s*$' +VimFoldh syn region vimLetHereDoc matchgroup=vimLetHereDocStart start='=<<\s\+\%(trim\s\+\)\=\%(eval\s\+\)\=\s*\z(\L\S*\)' matchgroup=vimLetHereDocStop end='^\s*\z1\s*$' " Abbreviations: {{{2 " ============= @@ -619,7 +619,7 @@ syn match vimCtrlChar "[--]" " Beginners - Patterns that involve ^ {{{2 " ========= -syn match vimLineComment +^[ \t:]*".*$+ contains=@vimCommentGroup,vimCommentString,vimCommentTitle +syn match vimLineComment +^[ \t:]*"\("[^"]*"\|[^"]\)*$+ contains=@vimCommentGroup,vimCommentString,vimCommentTitle syn match vim9LineComment +^[ \t:]\+#.*$+ contains=@vimCommentGroup,vimCommentString,vimCommentTitle syn match vimCommentTitle '"\s*\%([sS]:\|\h\w*#\)\=\u\w*\(\s\+\u\w*\)*:'hs=s+1 contained contains=vimCommentTitleLeader,vimTodo,@vimCommentGroup syn match vimContinue "^\s*\\" diff --git a/runtime/syntax/zsh.vim b/runtime/syntax/zsh.vim index bab89b916e..69671c59ca 100644 --- a/runtime/syntax/zsh.vim +++ b/runtime/syntax/zsh.vim @@ -2,7 +2,7 @@ " Language: Zsh shell script " Maintainer: Christian Brabandt <cb@256bit.org> " Previous Maintainer: Nikolai Weibull <now@bitwi.se> -" Latest Revision: 2020-11-21 +" Latest Revision: 2022-07-26 " License: Vim (see :h license) " Repository: https://github.com/chrisbra/vim-zsh @@ -19,9 +19,9 @@ function! s:ContainedGroup() " vim-pandoc syntax defines the @langname cluster for embedded syntax languages " However, if no syntax is defined yet, `syn list @zsh` will return " "No syntax items defined", so make sure the result is actually a valid syn cluster - for cluster in ['markdownHighlightzsh', 'zsh'] + for cluster in ['markdownHighlight_zsh', 'zsh'] try - " markdown syntax defines embedded clusters as @markdownhighlight<lang>, + " markdown syntax defines embedded clusters as @markdownhighlight_<lang>, " pandoc just uses @<lang>, so check both for both clusters let a=split(execute('syn list @'. cluster), "\n") if len(a) == 2 && a[0] =~# '^---' && a[1] =~? cluster @@ -48,17 +48,28 @@ syn match zshPOSIXQuoted '\\u[0-9a-fA-F]\{1,4}' syn match zshPOSIXQuoted '\\U[1-9a-fA-F]\{1,8}' syn region zshString matchgroup=zshStringDelimiter start=+"+ end=+"+ - \ contains=zshQuoted,@zshDerefs,@zshSubst fold + \ contains=zshQuoted,@zshDerefs,@zshSubstQuoted fold syn region zshString matchgroup=zshStringDelimiter start=+'+ end=+'+ fold syn region zshPOSIXString matchgroup=zshStringDelimiter start=+\$'+ \ skip=+\\[\\']+ end=+'+ contains=zshPOSIXQuoted,zshQuoted syn match zshJobSpec '%\(\d\+\|?\=\w\+\|[%+-]\)' +syn match zshNumber '[+-]\=\<\d\+\>' +syn match zshNumber '[+-]\=\<0x\x\+\>' +syn match zshNumber '[+-]\=\<0\o\+\>' +syn match zshNumber '[+-]\=\d\+#[-+]\=\w\+\>' +syn match zshNumber '[+-]\=\d\+\.\d\+\>' + syn keyword zshPrecommand noglob nocorrect exec command builtin - time syn keyword zshDelimiter do done end -syn keyword zshConditional if then elif else fi case in esac select +syn keyword zshConditional if then elif else fi esac select + +syn keyword zshCase case nextgroup=zshCaseWord skipwhite +syn match zshCaseWord /\S\+/ nextgroup=zshCaseIn skipwhite contained transparent +syn keyword zshCaseIn in nextgroup=zshCasePattern skipwhite skipnl contained +syn match zshCasePattern /\S[^)]*)/ contained syn keyword zshRepeat while until repeat @@ -73,9 +84,13 @@ syn match zshFunction '^\s*\k\+\ze\s*()' syn match zshOperator '||\|&&\|;\|&!\=' -syn match zshRedir '\d\=\(<\|<>\|<<<\|<&\s*[0-9p-]\=\)' -syn match zshRedir '\d\=\(>\|>>\|>&\s*[0-9p-]\=\|&>\|>>&\|&>>\)[|!]\=' -syn match zshRedir '|&\=' + " <<<, <, <>, and variants. +syn match zshRedir '\d\=\(<<<\|<&\s*[0-9p-]\=\|<>\?\)' + " >, >>, and variants. +syn match zshRedir '\d\=\(>&\s*[0-9p-]\=\|&>>\?\|>>\?&\?\)[|!]\=' + " | and |&, but only if it's not preceeded or + " followed by a | to avoid matching ||. +syn match zshRedir '|\@1<!|&\=|\@!' syn region zshHereDoc matchgroup=zshRedir \ start='<\@<!<<\s*\z([^<]\S*\)' @@ -125,7 +140,7 @@ syn keyword zshCommands alias autoload bg bindkey break bye cap cd \ enable eval exec exit export false fc fg \ functions getcap getln getopts hash history \ jobs kill let limit log logout popd print - \ printf pushd pushln pwd r read + \ printf prompt pushd pushln pwd r read \ rehash return sched set setcap shift \ source stat suspend test times trap true \ ttyctl type ulimit umask unalias unfunction @@ -139,10 +154,120 @@ syn case ignore syn match zshOptStart \ /\v^\s*%(%(un)?setopt|set\s+[-+]o)/ \ nextgroup=zshOption skipwhite -syn match zshOption nextgroup=zshOption,zshComment skipwhite contained /\v - \ <%(no_?)?%( - \ auto_?cd|auto_?pushd|cdable_?vars|cd_?silent|chase_?dots|chase_?links|posix_?cd|pushd_?ignore_?dups|pushd_?minus|pushd_?silent|pushd_?to_?home|always_?last_?prompt|always_?to_?end|auto_?list|auto_?menu|auto_?name_?dirs|auto_?param_?keys|auto_?param_?slash|auto_?remove_?slash|bash_?auto_?list|complete_?aliases|complete_?in_?word|glob_?complete|hash_?list_?all|list_?ambiguous|list_?beep|list_?packed|list_?rows_?first|list_?types|menu_?complete|rec_?exact|bad_?pattern|bare_?glob_?qual|brace_?ccl|case_?glob|case_?match|case_?paths|csh_?null_?glob|equals|extended_?glob|force_?float|glob|glob_?assign|glob_?dots|glob_?star_?short|glob_?subst|hist_?subst_?pattern|ignore_?braces|ignore_?close_?braces|ksh_?glob|magic_?equal_?subst|mark_?dirs|multibyte|nomatch|null_?glob|numeric_?glob_?sort|rc_?expand_?param|rematch_?pcre|sh_?glob|unset|warn_?create_?global|warn_?nested_?var|warnnestedvar|append_?history|bang_?hist|extended_?history|hist_?allow_?clobber|hist_?beep|hist_?expire_?dups_?first|hist_?fcntl_?lock|hist_?find_?no_?dups|hist_?ignore_?all_?dups|hist_?ignore_?dups|hist_?ignore_?space|hist_?lex_?words|hist_?no_?functions|hist_?no_?store|hist_?reduce_?blanks|hist_?save_?by_?copy|hist_?save_?no_?dups|hist_?verify|inc_?append_?history|inc_?append_?history_?time|share_?history|all_?export|global_?export|global_?rcs|rcs|aliases|clobber|clobber_?empty|correct|correct_?all|dvorak|flow_?control|ignore_?eof|interactive_?comments|hash_?cmds|hash_?dirs|hash_?executables_?only|mail_?warning|path_?dirs|path_?script|print_?eight_?bit|print_?exit_?value|rc_?quotes|rm_?star_?silent|rm_?star_?wait|short_?loops|short_?repeat|sun_?keyboard_?hack|auto_?continue|auto_?resume|bg_?nice|check_?jobs|check_?running_?jobs|hup|long_?list_?jobs|monitor|notify|posix_?jobs|prompt_?bang|prompt_?cr|prompt_?sp|prompt_?percent|prompt_?subst|transient_?rprompt|alias_?func_?def|c_?bases|c_?precedences|debug_?before_?cmd|err_?exit|err_?return|eval_?lineno|exec|function_?argzero|local_?loops|local_?options|local_?patterns|local_?traps|multi_?func_?def|multios|octal_?zeroes|pipe_?fail|source_?trace|typeset_?silent|typeset_?to_?unset|verbose|xtrace|append_?create|bash_?rematch|bsd_?echo|continue_?on_?error|csh_?junkie_?history|csh_?junkie_?loops|csh_?junkie_?quotes|csh_?nullcmd|ksh_?arrays|ksh_?autoload|ksh_?option_?print|ksh_?typeset|ksh_?zero_?subscript|posix_?aliases|posix_?argzero|posix_?builtins|posix_?identifiers|posix_?strings|posix_?traps|sh_?file_?expansion|sh_?nullcmd|sh_?option_?letters|sh_?word_?split|traps_?async|interactive|login|privileged|restricted|shin_?stdin|single_?command|beep|combining_?chars|emacs|overstrike|single_?line_?zle|vi|zle|brace_?expand|dot_?glob|hash_?all|hist_?append|hist_?expand|log|mail_?warn|one_?cmd|physical|prompt_?vars|stdin|track_?all|no_?match - \)>/ +syn keyword zshOption nextgroup=zshOption,zshComment skipwhite contained + \ auto_cd no_auto_cd autocd noautocd auto_pushd no_auto_pushd autopushd noautopushd cdable_vars + \ no_cdable_vars cdablevars nocdablevars cd_silent no_cd_silent cdsilent nocdsilent chase_dots + \ no_chase_dots chasedots nochasedots chase_links no_chase_links chaselinks nochaselinks posix_cd + \ posixcd no_posix_cd noposixcd pushd_ignore_dups no_pushd_ignore_dups pushdignoredups + \ nopushdignoredups pushd_minus no_pushd_minus pushdminus nopushdminus pushd_silent no_pushd_silent + \ pushdsilent nopushdsilent pushd_to_home no_pushd_to_home pushdtohome nopushdtohome + \ always_last_prompt no_always_last_prompt alwayslastprompt noalwayslastprompt always_to_end + \ no_always_to_end alwaystoend noalwaystoend auto_list no_auto_list autolist noautolist auto_menu + \ no_auto_menu automenu noautomenu auto_name_dirs no_auto_name_dirs autonamedirs noautonamedirs + \ auto_param_keys no_auto_param_keys autoparamkeys noautoparamkeys auto_param_slash + \ no_auto_param_slash autoparamslash noautoparamslash auto_remove_slash no_auto_remove_slash + \ autoremoveslash noautoremoveslash bash_auto_list no_bash_auto_list bashautolist nobashautolist + \ complete_aliases no_complete_aliases completealiases nocompletealiases complete_in_word + \ no_complete_in_word completeinword nocompleteinword glob_complete no_glob_complete globcomplete + \ noglobcomplete hash_list_all no_hash_list_all hashlistall nohashlistall list_ambiguous + \ no_list_ambiguous listambiguous nolistambiguous list_beep no_list_beep listbeep nolistbeep + \ list_packed no_list_packed listpacked nolistpacked list_rows_first no_list_rows_first listrowsfirst + \ nolistrowsfirst list_types no_list_types listtypes nolisttypes menu_complete no_menu_complete + \ menucomplete nomenucomplete rec_exact no_rec_exact recexact norecexact bad_pattern no_bad_pattern + \ badpattern nobadpattern bare_glob_qual no_bare_glob_qual bareglobqual nobareglobqual brace_ccl + \ no_brace_ccl braceccl nobraceccl case_glob no_case_glob caseglob nocaseglob case_match + \ no_case_match casematch nocasematch case_paths no_case_paths casepaths nocasepaths csh_null_glob + \ no_csh_null_glob cshnullglob nocshnullglob equals no_equals noequals extended_glob no_extended_glob + \ extendedglob noextendedglob force_float no_force_float forcefloat noforcefloat glob no_glob noglob + \ glob_assign no_glob_assign globassign noglobassign glob_dots no_glob_dots globdots noglobdots + \ glob_star_short no_glob_star_short globstarshort noglobstarshort glob_subst no_glob_subst globsubst + \ noglobsubst hist_subst_pattern no_hist_subst_pattern histsubstpattern nohistsubstpattern + \ ignore_braces no_ignore_braces ignorebraces noignorebraces ignore_close_braces + \ no_ignore_close_braces ignoreclosebraces noignoreclosebraces ksh_glob no_ksh_glob kshglob nokshglob + \ magic_equal_subst no_magic_equal_subst magicequalsubst nomagicequalsubst mark_dirs no_mark_dirs + \ markdirs nomarkdirs multibyte no_multibyte nomultibyte nomatch no_nomatch nonomatch null_glob + \ no_null_glob nullglob nonullglob numeric_glob_sort no_numeric_glob_sort numericglobsort + \ nonumericglobsort rc_expand_param no_rc_expand_param rcexpandparam norcexpandparam rematch_pcre + \ no_rematch_pcre rematchpcre norematchpcre sh_glob no_sh_glob shglob noshglob unset no_unset nounset + \ warn_create_global no_warn_create_global warncreateglobal nowarncreateglobal warn_nested_var + \ no_warn_nested_var warnnestedvar no_warnnestedvar append_history no_append_history appendhistory + \ noappendhistory bang_hist no_bang_hist banghist nobanghist extended_history no_extended_history + \ extendedhistory noextendedhistory hist_allow_clobber no_hist_allow_clobber histallowclobber + \ nohistallowclobber hist_beep no_hist_beep histbeep nohistbeep hist_expire_dups_first + \ no_hist_expire_dups_first histexpiredupsfirst nohistexpiredupsfirst hist_fcntl_lock + \ no_hist_fcntl_lock histfcntllock nohistfcntllock hist_find_no_dups no_hist_find_no_dups + \ histfindnodups nohistfindnodups hist_ignore_all_dups no_hist_ignore_all_dups histignorealldups + \ nohistignorealldups hist_ignore_dups no_hist_ignore_dups histignoredups nohistignoredups + \ hist_ignore_space no_hist_ignore_space histignorespace nohistignorespace hist_lex_words + \ no_hist_lex_words histlexwords nohistlexwords hist_no_functions no_hist_no_functions + \ histnofunctions nohistnofunctions hist_no_store no_hist_no_store histnostore nohistnostore + \ hist_reduce_blanks no_hist_reduce_blanks histreduceblanks nohistreduceblanks hist_save_by_copy + \ no_hist_save_by_copy histsavebycopy nohistsavebycopy hist_save_no_dups no_hist_save_no_dups + \ histsavenodups nohistsavenodups hist_verify no_hist_verify histverify nohistverify + \ inc_append_history no_inc_append_history incappendhistory noincappendhistory + \ inc_append_history_time no_inc_append_history_time incappendhistorytime noincappendhistorytime + \ share_history no_share_history sharehistory nosharehistory all_export no_all_export allexport + \ noallexport global_export no_global_export globalexport noglobalexport global_rcs no_global_rcs + \ globalrcs noglobalrcs rcs no_rcs norcs aliases no_aliases noaliases clobber no_clobber noclobber + \ clobber_empty no_clobber_empty clobberempty noclobberempty correct no_correct nocorrect correct_all + \ no_correct_all correctall nocorrectall dvorak no_dvorak nodvorak flow_control no_flow_control + \ flowcontrol noflowcontrol ignore_eof no_ignore_eof ignoreeof noignoreeof interactive_comments + \ no_interactive_comments interactivecomments nointeractivecomments hash_cmds no_hash_cmds hashcmds + \ nohashcmds hash_dirs no_hash_dirs hashdirs nohashdirs hash_executables_only + \ no_hash_executables_only hashexecutablesonly nohashexecutablesonly mail_warning no_mail_warning + \ mailwarning nomailwarning path_dirs no_path_dirs pathdirs nopathdirs path_script no_path_script + \ pathscript nopathscript print_eight_bit no_print_eight_bit printeightbit noprinteightbit + \ print_exit_value no_print_exit_value printexitvalue noprintexitvalue rc_quotes no_rc_quotes + \ rcquotes norcquotes rm_star_silent no_rm_star_silent rmstarsilent normstarsilent rm_star_wait + \ no_rm_star_wait rmstarwait normstarwait short_loops no_short_loops shortloops noshortloops + \ short_repeat no_short_repeat shortrepeat noshortrepeat sun_keyboard_hack no_sun_keyboard_hack + \ sunkeyboardhack nosunkeyboardhack auto_continue no_auto_continue autocontinue noautocontinue + \ auto_resume no_auto_resume autoresume noautoresume bg_nice no_bg_nice bgnice nobgnice check_jobs + \ no_check_jobs checkjobs nocheckjobs check_running_jobs no_check_running_jobs checkrunningjobs + \ nocheckrunningjobs hup no_hup nohup long_list_jobs no_long_list_jobs longlistjobs nolonglistjobs + \ monitor no_monitor nomonitor notify no_notify nonotify posix_jobs posixjobs no_posix_jobs + \ noposixjobs prompt_bang no_prompt_bang promptbang nopromptbang prompt_cr no_prompt_cr promptcr + \ nopromptcr prompt_sp no_prompt_sp promptsp nopromptsp prompt_percent no_prompt_percent + \ promptpercent nopromptpercent prompt_subst no_prompt_subst promptsubst nopromptsubst + \ transient_rprompt no_transient_rprompt transientrprompt notransientrprompt alias_func_def + \ no_alias_func_def aliasfuncdef noaliasfuncdef c_bases no_c_bases cbases nocbases c_precedences + \ no_c_precedences cprecedences nocprecedences debug_before_cmd no_debug_before_cmd debugbeforecmd + \ nodebugbeforecmd err_exit no_err_exit errexit noerrexit err_return no_err_return errreturn + \ noerrreturn eval_lineno no_eval_lineno evallineno noevallineno exec no_exec noexec function_argzero + \ no_function_argzero functionargzero nofunctionargzero local_loops no_local_loops localloops + \ nolocalloops local_options no_local_options localoptions nolocaloptions local_patterns + \ no_local_patterns localpatterns nolocalpatterns local_traps no_local_traps localtraps nolocaltraps + \ multi_func_def no_multi_func_def multifuncdef nomultifuncdef multios no_multios nomultios + \ octal_zeroes no_octal_zeroes octalzeroes nooctalzeroes pipe_fail no_pipe_fail pipefail nopipefail + \ source_trace no_source_trace sourcetrace nosourcetrace typeset_silent no_typeset_silent + \ typesetsilent notypesetsilent typeset_to_unset no_typeset_to_unset typesettounset notypesettounset + \ verbose no_verbose noverbose xtrace no_xtrace noxtrace append_create no_append_create appendcreate + \ noappendcreate bash_rematch no_bash_rematch bashrematch nobashrematch bsd_echo no_bsd_echo bsdecho + \ nobsdecho continue_on_error no_continue_on_error continueonerror nocontinueonerror + \ csh_junkie_history no_csh_junkie_history cshjunkiehistory nocshjunkiehistory csh_junkie_loops + \ no_csh_junkie_loops cshjunkieloops nocshjunkieloops csh_junkie_quotes no_csh_junkie_quotes + \ cshjunkiequotes nocshjunkiequotes csh_nullcmd no_csh_nullcmd cshnullcmd nocshnullcmd ksh_arrays + \ no_ksh_arrays ksharrays noksharrays ksh_autoload no_ksh_autoload kshautoload nokshautoload + \ ksh_option_print no_ksh_option_print kshoptionprint nokshoptionprint ksh_typeset no_ksh_typeset + \ kshtypeset nokshtypeset ksh_zero_subscript no_ksh_zero_subscript kshzerosubscript + \ nokshzerosubscript posix_aliases no_posix_aliases posixaliases noposixaliases posix_argzero + \ no_posix_argzero posixargzero noposixargzero posix_builtins no_posix_builtins posixbuiltins + \ noposixbuiltins posix_identifiers no_posix_identifiers posixidentifiers noposixidentifiers + \ posix_strings no_posix_strings posixstrings noposixstrings posix_traps no_posix_traps posixtraps + \ noposixtraps sh_file_expansion no_sh_file_expansion shfileexpansion noshfileexpansion sh_nullcmd + \ no_sh_nullcmd shnullcmd noshnullcmd sh_option_letters no_sh_option_letters shoptionletters + \ noshoptionletters sh_word_split no_sh_word_split shwordsplit noshwordsplit traps_async + \ no_traps_async trapsasync notrapsasync interactive no_interactive nointeractive login no_login + \ nologin privileged no_privileged noprivileged restricted no_restricted norestricted shin_stdin + \ no_shin_stdin shinstdin noshinstdin single_command no_single_command singlecommand nosinglecommand + \ beep no_beep nobeep combining_chars no_combining_chars combiningchars nocombiningchars emacs + \ no_emacs noemacs overstrike no_overstrike nooverstrike single_line_zle no_single_line_zle + \ singlelinezle nosinglelinezle vi no_vi novi zle no_zle nozle brace_expand no_brace_expand + \ braceexpand nobraceexpand dot_glob no_dot_glob dotglob nodotglob hash_all no_hash_all hashall + \ nohashall hist_append no_hist_append histappend nohistappend hist_expand no_hist_expand histexpand + \ nohistexpand log no_log nolog mail_warn no_mail_warn mailwarn nomailwarn one_cmd no_one_cmd onecmd + \ noonecmd physical no_physical nophysical prompt_vars no_prompt_vars promptvars nopromptvars stdin + \ no_stdin nostdin track_all no_track_all trackall notrackall syn case match syn keyword zshTypes float integer local typeset declare private readonly @@ -150,15 +275,12 @@ syn keyword zshTypes float integer local typeset declare private read " XXX: this may be too much " syn match zshSwitches '\s\zs--\=[a-zA-Z0-9-]\+' -syn match zshNumber '[+-]\=\<\d\+\>' -syn match zshNumber '[+-]\=\<0x\x\+\>' -syn match zshNumber '[+-]\=\<0\o\+\>' -syn match zshNumber '[+-]\=\d\+#[-+]\=\w\+\>' -syn match zshNumber '[+-]\=\d\+\.\d\+\>' - " TODO: $[...] is the same as $((...)), so add that as well. syn cluster zshSubst contains=zshSubst,zshOldSubst,zshMathSubst +syn cluster zshSubstQuoted contains=zshSubstQuoted,zshOldSubst,zshMathSubst exe 'syn region zshSubst matchgroup=zshSubstDelim transparent start=/\$(/ skip=/\\)/ end=/)/ contains='.s:contained. ' fold' +exe 'syn region zshSubstQuoted matchgroup=zshSubstDelim transparent start=/\$(/ skip=/\\)/ end=/)/ contains='.s:contained. ' fold' +syn region zshSubstQuoted matchgroup=zshSubstDelim start='\${' skip='\\}' end='}' contains=@zshSubst,zshBrackets,zshQuoted fold syn region zshParentheses transparent start='(' skip='\\)' end=')' fold syn region zshGlob start='(#' end=')' syn region zshMathSubst matchgroup=zshSubstDelim transparent @@ -201,6 +323,8 @@ hi def link zshJobSpec Special hi def link zshPrecommand Special hi def link zshDelimiter Keyword hi def link zshConditional Conditional +hi def link zshCase zshConditional +hi def link zshCaseIn zshCase hi def link zshException Exception hi def link zshRepeat Repeat hi def link zshKeyword Keyword @@ -223,6 +347,7 @@ hi def link zshTypes Type hi def link zshSwitches Special hi def link zshNumber Number hi def link zshSubst PreProc +hi def link zshSubstQuoted zshSubst hi def link zshMathSubst zshSubst hi def link zshOldSubst zshSubst hi def link zshSubstDelim zshSubst |