diff options
Diffstat (limited to 'runtime')
356 files changed, 27091 insertions, 18055 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e0a0b34d28..581a4545db 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -63,7 +63,7 @@ foreach(DF ${DOCFILES}) endforeach() add_custom_command(OUTPUT ${GENERATED_HELP_TAGS} - COMMAND ${CMAKE_COMMAND} -E remove doc/* + COMMAND ${CMAKE_COMMAND} -E remove_directory doc COMMAND ${CMAKE_COMMAND} -E copy_directory ${PROJECT_SOURCE_DIR}/runtime/doc doc COMMAND "${PROJECT_BINARY_DIR}/bin/nvim" @@ -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" @@ -108,12 +110,16 @@ if(NOT APPLE) install_helper( FILES ${CMAKE_CURRENT_SOURCE_DIR}/nvim.desktop DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/applications) - - install_helper( - FILES ${CMAKE_CURRENT_SOURCE_DIR}/nvim.png - DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/128x128/apps) endif() +install_helper( + FILES ${CMAKE_CURRENT_SOURCE_DIR}/nvim.png + DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/128x128/apps) + +install_helper( + FILES ${CMAKE_CURRENT_SOURCE_DIR}/neovim.ico + DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/nvim/runtime) + globrecurse_wrapper(RUNTIME_PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR} *.awk *.sh *.bat) foreach(PROG ${RUNTIME_PROGRAMS}) @@ -123,7 +129,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/ccomplete.lua b/runtime/autoload/ccomplete.lua new file mode 100644 index 0000000000..f4a3eabd9a --- /dev/null +++ b/runtime/autoload/ccomplete.lua @@ -0,0 +1,857 @@ +---------------------------------------- +-- This file is generated via github.com/tjdevries/vim9jit +-- For any bugs, please first consider reporting there. +---------------------------------------- + +-- Ignore "value assigned to a local variable is unused" because +-- we can't guarantee that local variables will be used by plugins +-- luacheck: ignore 311 + +local vim9 = require('_vim9script') +local M = {} +local prepended = nil +local grepCache = nil +local Complete = nil +local GetAddition = nil +local Tag2item = nil +local Dict2info = nil +local ParseTagline = nil +local Tagline2item = nil +local Tagcmd2extra = nil +local Nextitem = nil +local StructMembers = nil +local SearchMembers = nil +-- vim9script + +-- # Vim completion script +-- # Language: C +-- # Maintainer: Bram Moolenaar <Bram@vim.org> +-- # Rewritten in Vim9 script by github user lacygoill +-- # Last Change: 2022 Jan 31 + +prepended = '' +grepCache = vim.empty_dict() + +-- # This function is used for the 'omnifunc' option. + +Complete = function(findstart, abase) + findstart = vim9.bool(findstart) + if vim9.bool(findstart) then + -- # Locate the start of the item, including ".", "->" and "[...]". + local line = vim9.fn.getline('.') + local start = vim9.fn.charcol('.') - 1 + local lastword = -1 + while start > 0 do + if vim9.ops.RegexpMatches(vim9.index(line, vim9.ops.Minus(start, 1)), '\\w') then + start = start - 1 + elseif + vim9.bool(vim9.ops.RegexpMatches(vim9.index(line, vim9.ops.Minus(start, 1)), '\\.')) + then + if lastword == -1 then + lastword = start + end + start = start - 1 + elseif + vim9.bool( + start > 1 + and vim9.index(line, vim9.ops.Minus(start, 2)) == '-' + and vim9.index(line, vim9.ops.Minus(start, 1)) == '>' + ) + then + if lastword == -1 then + lastword = start + end + start = vim9.ops.Minus(start, 2) + elseif vim9.bool(vim9.index(line, vim9.ops.Minus(start, 1)) == ']') then + -- # Skip over [...]. + local n = 0 + start = start - 1 + while start > 0 do + start = start - 1 + if vim9.index(line, start) == '[' then + if n == 0 then + break + end + n = n - 1 + elseif vim9.bool(vim9.index(line, start) == ']') then + n = n + 1 + end + end + else + break + end + end + + -- # Return the column of the last word, which is going to be changed. + -- # Remember the text that comes before it in prepended. + if lastword == -1 then + prepended = '' + return vim9.fn.byteidx(line, start) + end + prepended = vim9.slice(line, start, vim9.ops.Minus(lastword, 1)) + return vim9.fn.byteidx(line, lastword) + end + + -- # Return list of matches. + + local base = prepended .. abase + + -- # Don't do anything for an empty base, would result in all the tags in the + -- # tags file. + if base == '' then + return {} + end + + -- # init cache for vimgrep to empty + grepCache = {} + + -- # Split item in words, keep empty word after "." or "->". + -- # "aa" -> ['aa'], "aa." -> ['aa', ''], "aa.bb" -> ['aa', 'bb'], etc. + -- # We can't use split, because we need to skip nested [...]. + -- # "aa[...]" -> ['aa', '[...]'], "aa.bb[...]" -> ['aa', 'bb', '[...]'], etc. + local items = {} + local s = 0 + local arrays = 0 + while 1 do + local e = vim9.fn.charidx(base, vim9.fn.match(base, '\\.\\|->\\|\\[', s)) + if e < 0 then + if s == 0 or vim9.index(base, vim9.ops.Minus(s, 1)) ~= ']' then + vim9.fn.add(items, vim9.slice(base, s, nil)) + end + break + end + if s == 0 or vim9.index(base, vim9.ops.Minus(s, 1)) ~= ']' then + vim9.fn.add(items, vim9.slice(base, s, vim9.ops.Minus(e, 1))) + end + if vim9.index(base, e) == '.' then + -- # skip over '.' + s = vim9.ops.Plus(e, 1) + elseif vim9.bool(vim9.index(base, e) == '-') then + -- # skip over '->' + s = vim9.ops.Plus(e, 2) + else + -- # Skip over [...]. + local n = 0 + s = e + e = e + 1 + while e < vim9.fn.strcharlen(base) do + if vim9.index(base, e) == ']' then + if n == 0 then + break + end + n = n - 1 + elseif vim9.bool(vim9.index(base, e) == '[') then + n = n + 1 + end + e = e + 1 + end + e = e + 1 + vim9.fn.add(items, vim9.slice(base, s, vim9.ops.Minus(e, 1))) + arrays = arrays + 1 + s = e + end + end + + -- # Find the variable items[0]. + -- # 1. in current function (like with "gd") + -- # 2. in tags file(s) (like with ":tag") + -- # 3. in current file (like with "gD") + local res = {} + if vim9.fn.searchdecl(vim9.index(items, 0), false, true) == 0 then + -- # Found, now figure out the type. + -- # TODO: join previous line if it makes sense + local line = vim9.fn.getline('.') + local col = vim9.fn.charcol('.') + if vim9.fn.stridx(vim9.slice(line, nil, vim9.ops.Minus(col, 1)), ';') >= 0 then + -- # Handle multiple declarations on the same line. + local col2 = vim9.ops.Minus(col, 1) + while vim9.index(line, col2) ~= ';' do + col2 = col2 - 1 + end + line = vim9.slice(line, vim9.ops.Plus(col2, 1), nil) + col = vim9.ops.Minus(col, col2) + end + if vim9.fn.stridx(vim9.slice(line, nil, vim9.ops.Minus(col, 1)), ',') >= 0 then + -- # Handle multiple declarations on the same line in a function + -- # declaration. + local col2 = vim9.ops.Minus(col, 1) + while vim9.index(line, col2) ~= ',' do + col2 = col2 - 1 + end + if + vim9.ops.RegexpMatches( + vim9.slice(line, vim9.ops.Plus(col2, 1), vim9.ops.Minus(col, 1)), + ' *[^ ][^ ]* *[^ ]' + ) + then + line = vim9.slice(line, vim9.ops.Plus(col2, 1), nil) + col = vim9.ops.Minus(col, col2) + end + end + if vim9.fn.len(items) == 1 then + -- # Completing one word and it's a local variable: May add '[', '.' or + -- # '->'. + local match = vim9.index(items, 0) + local kind = 'v' + if vim9.fn.match(line, '\\<' .. match .. '\\s*\\[') > 0 then + match = match .. '[' + else + res = Nextitem(vim9.slice(line, nil, vim9.ops.Minus(col, 1)), { '' }, 0, true) + if vim9.fn.len(res) > 0 then + -- # There are members, thus add "." or "->". + if vim9.fn.match(line, '\\*[ \\t(]*' .. match .. '\\>') > 0 then + match = match .. '->' + else + match = match .. '.' + end + end + end + res = { { ['match'] = match, ['tagline'] = '', ['kind'] = kind, ['info'] = line } } + elseif vim9.bool(vim9.fn.len(items) == vim9.ops.Plus(arrays, 1)) then + -- # Completing one word and it's a local array variable: build tagline + -- # from declaration line + local match = vim9.index(items, 0) + local kind = 'v' + local tagline = '\t/^' .. line .. '$/' + res = { { ['match'] = match, ['tagline'] = tagline, ['kind'] = kind, ['info'] = line } } + else + -- # Completing "var.", "var.something", etc. + res = + Nextitem(vim9.slice(line, nil, vim9.ops.Minus(col, 1)), vim9.slice(items, 1, nil), 0, true) + end + end + + if vim9.fn.len(items) == 1 or vim9.fn.len(items) == vim9.ops.Plus(arrays, 1) then + -- # Only one part, no "." or "->": complete from tags file. + local tags = {} + if vim9.fn.len(items) == 1 then + tags = vim9.fn.taglist('^' .. base) + else + tags = vim9.fn.taglist('^' .. vim9.index(items, 0) .. '$') + end + + vim9.fn_mut('filter', { + vim9.fn_mut('filter', { + tags, + function(_, v) + return vim9.ternary(vim9.fn.has_key(v, 'kind'), function() + return v.kind ~= 'm' + end, true) + end, + }, { replace = 0 }), + function(_, v) + return vim9.ops.Or( + vim9.ops.Or( + vim9.prefix['Bang'](vim9.fn.has_key(v, 'static')), + vim9.prefix['Bang'](vim9.index(v, 'static')) + ), + vim9.fn.bufnr('%') == vim9.fn.bufnr(vim9.index(v, 'filename')) + ) + end, + }, { replace = 0 }) + + res = vim9.fn.extend( + res, + vim9.fn.map(tags, function(_, v) + return Tag2item(v) + end) + ) + end + + if vim9.fn.len(res) == 0 then + -- # Find the variable in the tags file(s) + local diclist = vim9.fn.filter( + vim9.fn.taglist('^' .. vim9.index(items, 0) .. '$'), + function(_, v) + return vim9.ternary(vim9.fn.has_key(v, 'kind'), function() + return v.kind ~= 'm' + end, true) + end + ) + + res = {} + + for _, i in vim9.iter(vim9.fn.range(vim9.fn.len(diclist))) do + -- # New ctags has the "typeref" field. Patched version has "typename". + if vim9.bool(vim9.fn.has_key(vim9.index(diclist, i), 'typename')) then + res = vim9.fn.extend( + res, + StructMembers( + vim9.index(vim9.index(diclist, i), 'typename'), + vim9.slice(items, 1, nil), + true + ) + ) + elseif vim9.bool(vim9.fn.has_key(vim9.index(diclist, i), 'typeref')) then + res = vim9.fn.extend( + res, + StructMembers( + vim9.index(vim9.index(diclist, i), 'typeref'), + vim9.slice(items, 1, nil), + true + ) + ) + end + + -- # For a variable use the command, which must be a search pattern that + -- # shows the declaration of the variable. + if vim9.index(vim9.index(diclist, i), 'kind') == 'v' then + local line = vim9.index(vim9.index(diclist, i), 'cmd') + if vim9.slice(line, nil, 1) == '/^' then + local col = + vim9.fn.charidx(line, vim9.fn.match(line, '\\<' .. vim9.index(items, 0) .. '\\>')) + res = vim9.fn.extend( + res, + Nextitem( + vim9.slice(line, 2, vim9.ops.Minus(col, 1)), + vim9.slice(items, 1, nil), + 0, + true + ) + ) + end + end + end + end + + if vim9.fn.len(res) == 0 and vim9.fn.searchdecl(vim9.index(items, 0), true) == 0 then + -- # Found, now figure out the type. + -- # TODO: join previous line if it makes sense + local line = vim9.fn.getline('.') + local col = vim9.fn.charcol('.') + res = + Nextitem(vim9.slice(line, nil, vim9.ops.Minus(col, 1)), vim9.slice(items, 1, nil), 0, true) + end + + -- # If the last item(s) are [...] they need to be added to the matches. + local last = vim9.fn.len(items) - 1 + local brackets = '' + while last >= 0 do + if vim9.index(vim9.index(items, last), 0) ~= '[' then + break + end + brackets = vim9.index(items, last) .. brackets + last = last - 1 + end + + return vim9.fn.map(res, function(_, v) + return Tagline2item(v, brackets) + end) +end +M['Complete'] = Complete + +GetAddition = function(line, match, memarg, bracket) + bracket = vim9.bool(bracket) + -- # Guess if the item is an array. + if vim9.bool(vim9.ops.And(bracket, vim9.fn.match(line, match .. '\\s*\\[') > 0)) then + return '[' + end + + -- # Check if the item has members. + if vim9.fn.len(SearchMembers(memarg, { '' }, false)) > 0 then + -- # If there is a '*' before the name use "->". + if vim9.fn.match(line, '\\*[ \\t(]*' .. match .. '\\>') > 0 then + return '->' + else + return '.' + end + end + return '' +end + +Tag2item = function(val) + -- # Turn the tag info "val" into an item for completion. + -- # "val" is is an item in the list returned by taglist(). + -- # If it is a variable we may add "." or "->". Don't do it for other types, + -- # such as a typedef, by not including the info that GetAddition() uses. + local res = vim9.convert.decl_dict({ ['match'] = vim9.index(val, 'name') }) + + res[vim9.index_expr('extra')] = + Tagcmd2extra(vim9.index(val, 'cmd'), vim9.index(val, 'name'), vim9.index(val, 'filename')) + + local s = Dict2info(val) + if s ~= '' then + res[vim9.index_expr('info')] = s + end + + res[vim9.index_expr('tagline')] = '' + if vim9.bool(vim9.fn.has_key(val, 'kind')) then + local kind = vim9.index(val, 'kind') + res[vim9.index_expr('kind')] = kind + if kind == 'v' then + res[vim9.index_expr('tagline')] = '\t' .. vim9.index(val, 'cmd') + res[vim9.index_expr('dict')] = val + elseif vim9.bool(kind == 'f') then + res[vim9.index_expr('match')] = vim9.index(val, 'name') .. '(' + end + end + + return res +end + +Dict2info = function(dict) + -- # Use all the items in dictionary for the "info" entry. + local info = '' + + for _, k in vim9.iter(vim9.fn_mut('sort', { vim9.fn.keys(dict) }, { replace = 0 })) do + info = info .. k .. vim9.fn['repeat'](' ', 10 - vim9.fn.strlen(k)) + if k == 'cmd' then + info = info + .. vim9.fn.substitute( + vim9.fn.matchstr(vim9.index(dict, 'cmd'), '/^\\s*\\zs.*\\ze$/'), + '\\\\\\(.\\)', + '\\1', + 'g' + ) + else + local dictk = vim9.index(dict, k) + if vim9.fn.typename(dictk) ~= 'string' then + info = info .. vim9.fn.string(dictk) + else + info = info .. dictk + end + end + info = info .. '\n' + end + + return info +end + +ParseTagline = function(line) + -- # Parse a tag line and return a dictionary with items like taglist() + local l = vim9.fn.split(line, '\t') + local d = vim.empty_dict() + if vim9.fn.len(l) >= 3 then + d[vim9.index_expr('name')] = vim9.index(l, 0) + d[vim9.index_expr('filename')] = vim9.index(l, 1) + d[vim9.index_expr('cmd')] = vim9.index(l, 2) + local n = 2 + if vim9.ops.RegexpMatches(vim9.index(l, 2), '^/') then + -- # Find end of cmd, it may contain Tabs. + while n < vim9.fn.len(l) and vim9.ops.NotRegexpMatches(vim9.index(l, n), '/;"$') do + n = n + 1 + d[vim9.index_expr('cmd')] = vim9.index(d, 'cmd') .. ' ' .. vim9.index(l, n) + end + end + + for _, i in vim9.iter(vim9.fn.range(vim9.ops.Plus(n, 1), vim9.fn.len(l) - 1)) do + if vim9.index(l, i) == 'file:' then + d[vim9.index_expr('static')] = 1 + elseif vim9.bool(vim9.ops.NotRegexpMatches(vim9.index(l, i), ':')) then + d[vim9.index_expr('kind')] = vim9.index(l, i) + else + d[vim9.index_expr(vim9.fn.matchstr(vim9.index(l, i), '[^:]*'))] = + vim9.fn.matchstr(vim9.index(l, i), ':\\zs.*') + end + end + end + + return d +end + +Tagline2item = function(val, brackets) + -- # Turn a match item "val" into an item for completion. + -- # "val['match']" is the matching item. + -- # "val['tagline']" is the tagline in which the last part was found. + local line = vim9.index(val, 'tagline') + local add = GetAddition(line, vim9.index(val, 'match'), { val }, brackets == '') + local res = vim9.convert.decl_dict({ ['word'] = vim9.index(val, 'match') .. brackets .. add }) + + if vim9.bool(vim9.fn.has_key(val, 'info')) then + -- # Use info from Tag2item(). + res[vim9.index_expr('info')] = vim9.index(val, 'info') + else + -- # Parse the tag line and add each part to the "info" entry. + local s = Dict2info(ParseTagline(line)) + if s ~= '' then + res[vim9.index_expr('info')] = s + end + end + + if vim9.bool(vim9.fn.has_key(val, 'kind')) then + res[vim9.index_expr('kind')] = vim9.index(val, 'kind') + elseif vim9.bool(add == '(') then + res[vim9.index_expr('kind')] = 'f' + else + local s = vim9.fn.matchstr(line, '\\t\\(kind:\\)\\=\\zs\\S\\ze\\(\\t\\|$\\)') + if s ~= '' then + res[vim9.index_expr('kind')] = s + end + end + + if vim9.bool(vim9.fn.has_key(val, 'extra')) then + res[vim9.index_expr('menu')] = vim9.index(val, 'extra') + return res + end + + -- # Isolate the command after the tag and filename. + local s = vim9.fn.matchstr( + line, + '[^\\t]*\\t[^\\t]*\\t\\zs\\(/^.*$/\\|[^\\t]*\\)\\ze\\(;"\\t\\|\\t\\|$\\)' + ) + if s ~= '' then + res[vim9.index_expr('menu')] = Tagcmd2extra( + s, + vim9.index(val, 'match'), + vim9.fn.matchstr(line, '[^\\t]*\\t\\zs[^\\t]*\\ze\\t') + ) + end + return res +end + +Tagcmd2extra = function(cmd, name, fname) + -- # Turn a command from a tag line to something that is useful in the menu + local x = '' + if vim9.ops.RegexpMatches(cmd, '^/^') then + -- # The command is a search command, useful to see what it is. + x = vim9.fn.substitute( + vim9.fn.substitute( + vim9.fn.matchstr(cmd, '^/^\\s*\\zs.*\\ze$/'), + '\\<' .. name .. '\\>', + '@@', + '' + ), + '\\\\\\(.\\)', + '\\1', + 'g' + ) .. ' - ' .. fname + elseif vim9.bool(vim9.ops.RegexpMatches(cmd, '^\\d*$')) then + -- # The command is a line number, the file name is more useful. + x = fname .. ' - ' .. cmd + else + -- # Not recognized, use command and file name. + x = cmd .. ' - ' .. fname + end + return x +end + +Nextitem = function(lead, items, depth, all) + all = vim9.bool(all) + -- # Find composing type in "lead" and match items[0] with it. + -- # Repeat this recursively for items[1], if it's there. + -- # When resolving typedefs "depth" is used to avoid infinite recursion. + -- # Return the list of matches. + + -- # Use the text up to the variable name and split it in tokens. + local tokens = vim9.fn.split(lead, '\\s\\+\\|\\<') + + -- # Try to recognize the type of the variable. This is rough guessing... + local res = {} + + local body = function(_, tidx) + -- # Skip tokens starting with a non-ID character. + if vim9.ops.NotRegexpMatches(vim9.index(tokens, tidx), '^\\h') then + return vim9.ITER_CONTINUE + end + + -- # Recognize "struct foobar" and "union foobar". + -- # Also do "class foobar" when it's C++ after all (doesn't work very well + -- # though). + if + ( + vim9.index(tokens, tidx) == 'struct' + or vim9.index(tokens, tidx) == 'union' + or vim9.index(tokens, tidx) == 'class' + ) and vim9.ops.Plus(tidx, 1) < vim9.fn.len(tokens) + then + res = StructMembers( + vim9.index(tokens, tidx) .. ':' .. vim9.index(tokens, vim9.ops.Plus(tidx, 1)), + items, + all + ) + return vim9.ITER_BREAK + end + + -- # TODO: add more reserved words + if + vim9.fn.index( + { 'int', 'short', 'char', 'float', 'double', 'static', 'unsigned', 'extern' }, + vim9.index(tokens, tidx) + ) >= 0 + then + return vim9.ITER_CONTINUE + end + + -- # Use the tags file to find out if this is a typedef. + local diclist = vim9.fn.taglist('^' .. vim9.index(tokens, tidx) .. '$') + + local body = function(_, tagidx) + local item = vim9.convert.decl_dict(vim9.index(diclist, tagidx)) + + -- # New ctags has the "typeref" field. Patched version has "typename". + if vim9.bool(vim9.fn.has_key(item, 'typeref')) then + res = vim9.fn.extend(res, StructMembers(vim9.index(item, 'typeref'), items, all)) + return vim9.ITER_CONTINUE + end + if vim9.bool(vim9.fn.has_key(item, 'typename')) then + res = vim9.fn.extend(res, StructMembers(vim9.index(item, 'typename'), items, all)) + return vim9.ITER_CONTINUE + end + + -- # Only handle typedefs here. + if vim9.index(item, 'kind') ~= 't' then + return vim9.ITER_CONTINUE + end + + -- # Skip matches local to another file. + if + vim9.bool( + vim9.ops.And( + vim9.ops.And(vim9.fn.has_key(item, 'static'), vim9.index(item, 'static')), + vim9.fn.bufnr('%') ~= vim9.fn.bufnr(vim9.index(item, 'filename')) + ) + ) + then + return vim9.ITER_CONTINUE + end + + -- # For old ctags we recognize "typedef struct aaa" and + -- # "typedef union bbb" in the tags file command. + local cmd = vim9.index(item, 'cmd') + local ei = vim9.fn.charidx(cmd, vim9.fn.matchend(cmd, 'typedef\\s\\+')) + if ei > 1 then + local cmdtokens = vim9.fn.split(vim9.slice(cmd, ei, nil), '\\s\\+\\|\\<') + if vim9.fn.len(cmdtokens) > 1 then + if + vim9.index(cmdtokens, 0) == 'struct' + or vim9.index(cmdtokens, 0) == 'union' + or vim9.index(cmdtokens, 0) == 'class' + then + local name = '' + -- # Use the first identifier after the "struct" or "union" + + for _, ti in vim9.iter(vim9.fn.range((vim9.fn.len(cmdtokens) - 1))) do + if vim9.ops.RegexpMatches(vim9.index(cmdtokens, ti), '^\\w') then + name = vim9.index(cmdtokens, ti) + break + end + end + + if name ~= '' then + res = vim9.fn.extend( + res, + StructMembers(vim9.index(cmdtokens, 0) .. ':' .. name, items, all) + ) + end + elseif vim9.bool(depth < 10) then + -- # Could be "typedef other_T some_T". + res = vim9.fn.extend( + res, + Nextitem(vim9.index(cmdtokens, 0), items, vim9.ops.Plus(depth, 1), all) + ) + end + end + end + + return vim9.ITER_DEFAULT + end + + for _, tagidx in vim9.iter(vim9.fn.range(vim9.fn.len(diclist))) do + local nvim9_status, nvim9_ret = body(_, tagidx) + if nvim9_status == vim9.ITER_BREAK then + break + elseif nvim9_status == vim9.ITER_RETURN then + return nvim9_ret + end + end + + if vim9.fn.len(res) > 0 then + return vim9.ITER_BREAK + end + + return vim9.ITER_DEFAULT + end + + for _, tidx in vim9.iter(vim9.fn.range(vim9.fn.len(tokens))) do + local nvim9_status, nvim9_ret = body(_, tidx) + if nvim9_status == vim9.ITER_BREAK then + break + elseif nvim9_status == vim9.ITER_RETURN then + return nvim9_ret + end + end + + return res +end + +StructMembers = function(atypename, items, all) + all = vim9.bool(all) + + -- # Search for members of structure "typename" in tags files. + -- # Return a list with resulting matches. + -- # Each match is a dictionary with "match" and "tagline" entries. + -- # When "all" is true find all, otherwise just return 1 if there is any member. + + -- # Todo: What about local structures? + local fnames = vim9.fn.join(vim9.fn.map(vim9.fn.tagfiles(), function(_, v) + return vim9.fn.escape(v, ' \\#%') + end)) + if fnames == '' then + return {} + end + + local typename = atypename + local qflist = {} + local cached = 0 + local n = '' + if vim9.bool(vim9.prefix['Bang'](all)) then + n = '1' + if vim9.bool(vim9.fn.has_key(grepCache, typename)) then + qflist = vim9.index(grepCache, typename) + cached = 1 + end + else + n = '' + end + if vim9.bool(vim9.prefix['Bang'](cached)) then + while 1 do + vim.api.nvim_command( + 'silent! keepjumps noautocmd ' + .. n + .. 'vimgrep ' + .. '/\\t' + .. typename + .. '\\(\\t\\|$\\)/j ' + .. fnames + ) + + qflist = vim9.fn.getqflist() + if vim9.fn.len(qflist) > 0 or vim9.fn.match(typename, '::') < 0 then + break + end + -- # No match for "struct:context::name", remove "context::" and try again. + typename = vim9.fn.substitute(typename, ':[^:]*::', ':', '') + end + + if vim9.bool(vim9.prefix['Bang'](all)) then + -- # Store the result to be able to use it again later. + grepCache[vim9.index_expr(typename)] = qflist + end + end + + -- # Skip over [...] items + local idx = 0 + local target = '' + while 1 do + if idx >= vim9.fn.len(items) then + target = '' + break + end + if vim9.index(vim9.index(items, idx), 0) ~= '[' then + target = vim9.index(items, idx) + break + end + idx = idx + 1 + end + -- # Put matching members in matches[]. + local matches = {} + + for _, l in vim9.iter(qflist) do + local memb = vim9.fn.matchstr(vim9.index(l, 'text'), '[^\\t]*') + if vim9.ops.RegexpMatches(memb, '^' .. target) then + -- # Skip matches local to another file. + if + vim9.fn.match(vim9.index(l, 'text'), '\tfile:') < 0 + or vim9.fn.bufnr('%') + == vim9.fn.bufnr(vim9.fn.matchstr(vim9.index(l, 'text'), '\\t\\zs[^\\t]*')) + then + local item = + vim9.convert.decl_dict({ ['match'] = memb, ['tagline'] = vim9.index(l, 'text') }) + + -- # Add the kind of item. + local s = + vim9.fn.matchstr(vim9.index(l, 'text'), '\\t\\(kind:\\)\\=\\zs\\S\\ze\\(\\t\\|$\\)') + if s ~= '' then + item[vim9.index_expr('kind')] = s + if s == 'f' then + item[vim9.index_expr('match')] = memb .. '(' + end + end + + vim9.fn.add(matches, item) + end + end + end + + if vim9.fn.len(matches) > 0 then + -- # Skip over next [...] items + idx = idx + 1 + while 1 do + if idx >= vim9.fn.len(items) then + return matches + end + if vim9.index(vim9.index(items, idx), 0) ~= '[' then + break + end + idx = idx + 1 + end + + -- # More items following. For each of the possible members find the + -- # matching following members. + return SearchMembers(matches, vim9.slice(items, idx, nil), all) + end + + -- # Failed to find anything. + return {} +end + +SearchMembers = function(matches, items, all) + all = vim9.bool(all) + + -- # For matching members, find matches for following items. + -- # When "all" is true find all, otherwise just return 1 if there is any member. + local res = {} + + for _, i in vim9.iter(vim9.fn.range(vim9.fn.len(matches))) do + local typename = '' + local line = '' + if vim9.bool(vim9.fn.has_key(vim9.index(matches, i), 'dict')) then + if vim9.bool(vim9.fn.has_key(vim9.index(vim9.index(matches, i), 'dict'), 'typename')) then + typename = vim9.index(vim9.index(vim9.index(matches, i), 'dict'), 'typename') + elseif vim9.bool(vim9.fn.has_key(vim9.index(vim9.index(matches, i), 'dict'), 'typeref')) then + typename = vim9.index(vim9.index(vim9.index(matches, i), 'dict'), 'typeref') + end + line = '\t' .. vim9.index(vim9.index(vim9.index(matches, i), 'dict'), 'cmd') + else + line = vim9.index(vim9.index(matches, i), 'tagline') + local eb = vim9.fn.matchend(line, '\\ttypename:') + local e = vim9.fn.charidx(line, eb) + if e < 0 then + eb = vim9.fn.matchend(line, '\\ttyperef:') + e = vim9.fn.charidx(line, eb) + end + if e > 0 then + -- # Use typename field + typename = vim9.fn.matchstr(line, '[^\\t]*', eb) + end + end + + if typename ~= '' then + res = vim9.fn.extend(res, StructMembers(typename, items, all)) + else + -- # Use the search command (the declaration itself). + local sb = vim9.fn.match(line, '\\t\\zs/^') + local s = vim9.fn.charidx(line, sb) + if s > 0 then + local e = vim9.fn.charidx( + line, + vim9.fn.match(line, '\\<' .. vim9.index(vim9.index(matches, i), 'match') .. '\\>', sb) + ) + if e > 0 then + res = + vim9.fn.extend(res, Nextitem(vim9.slice(line, s, vim9.ops.Minus(e, 1)), items, 0, all)) + end + end + end + if vim9.bool(vim9.ops.And(vim9.prefix['Bang'](all), vim9.fn.len(res) > 0)) then + break + end + end + + return res +end + +-- #}}}1 + +-- # vim: noet sw=2 sts=2 +return M diff --git a/runtime/autoload/ccomplete.vim b/runtime/autoload/ccomplete.vim index 95a20e16b0..d7e0ba4ac5 100644 --- a/runtime/autoload/ccomplete.vim +++ b/runtime/autoload/ccomplete.vim @@ -1,639 +1,8 @@ -" Vim completion script -" Language: C -" Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2020 Nov 14 - -let s:cpo_save = &cpo -set cpo&vim - -" This function is used for the 'omnifunc' option. -func ccomplete#Complete(findstart, base) - if a:findstart - " Locate the start of the item, including ".", "->" and "[...]". - let line = getline('.') - let start = col('.') - 1 - let lastword = -1 - while start > 0 - if line[start - 1] =~ '\w' - let start -= 1 - elseif line[start - 1] =~ '\.' - if lastword == -1 - let lastword = start - endif - let start -= 1 - elseif start > 1 && line[start - 2] == '-' && line[start - 1] == '>' - if lastword == -1 - let lastword = start - endif - let start -= 2 - elseif line[start - 1] == ']' - " Skip over [...]. - let n = 0 - let start -= 1 - while start > 0 - let start -= 1 - if line[start] == '[' - if n == 0 - break - endif - let n -= 1 - elseif line[start] == ']' " nested [] - let n += 1 - endif - endwhile - else - break - endif - endwhile - - " Return the column of the last word, which is going to be changed. - " Remember the text that comes before it in s:prepended. - if lastword == -1 - let s:prepended = '' - return start - endif - let s:prepended = strpart(line, start, lastword - start) - return lastword - endif - - " Return list of matches. - - let base = s:prepended . a:base - - " Don't do anything for an empty base, would result in all the tags in the - " tags file. - if base == '' - return [] - endif - - " init cache for vimgrep to empty - let s:grepCache = {} - - " Split item in words, keep empty word after "." or "->". - " "aa" -> ['aa'], "aa." -> ['aa', ''], "aa.bb" -> ['aa', 'bb'], etc. - " We can't use split, because we need to skip nested [...]. - " "aa[...]" -> ['aa', '[...]'], "aa.bb[...]" -> ['aa', 'bb', '[...]'], etc. - let items = [] - let s = 0 - let arrays = 0 - while 1 - let e = match(base, '\.\|->\|\[', s) - if e < 0 - if s == 0 || base[s - 1] != ']' - call add(items, strpart(base, s)) - endif - break - endif - if s == 0 || base[s - 1] != ']' - call add(items, strpart(base, s, e - s)) - endif - if base[e] == '.' - let s = e + 1 " skip over '.' - elseif base[e] == '-' - let s = e + 2 " skip over '->' - else - " Skip over [...]. - let n = 0 - let s = e - let e += 1 - while e < len(base) - if base[e] == ']' - if n == 0 - break - endif - let n -= 1 - elseif base[e] == '[' " nested [...] - let n += 1 - endif - let e += 1 - endwhile - let e += 1 - call add(items, strpart(base, s, e - s)) - let arrays += 1 - let s = e - endif - endwhile - - " Find the variable items[0]. - " 1. in current function (like with "gd") - " 2. in tags file(s) (like with ":tag") - " 3. in current file (like with "gD") - let res = [] - if searchdecl(items[0], 0, 1) == 0 - " Found, now figure out the type. - " TODO: join previous line if it makes sense - let line = getline('.') - let col = col('.') - if stridx(strpart(line, 0, col), ';') != -1 - " Handle multiple declarations on the same line. - let col2 = col - 1 - while line[col2] != ';' - let col2 -= 1 - endwhile - let line = strpart(line, col2 + 1) - let col -= col2 - endif - if stridx(strpart(line, 0, col), ',') != -1 - " Handle multiple declarations on the same line in a function - " declaration. - let col2 = col - 1 - while line[col2] != ',' - let col2 -= 1 - endwhile - if strpart(line, col2 + 1, col - col2 - 1) =~ ' *[^ ][^ ]* *[^ ]' - let line = strpart(line, col2 + 1) - let col -= col2 - endif - endif - if len(items) == 1 - " Completing one word and it's a local variable: May add '[', '.' or - " '->'. - let match = items[0] - let kind = 'v' - if match(line, '\<' . match . '\s*\[') > 0 - let match .= '[' - else - let res = s:Nextitem(strpart(line, 0, col), [''], 0, 1) - if len(res) > 0 - " There are members, thus add "." or "->". - if match(line, '\*[ \t(]*' . match . '\>') > 0 - let match .= '->' - else - let match .= '.' - endif - endif - endif - let res = [{'match': match, 'tagline' : '', 'kind' : kind, 'info' : line}] - elseif len(items) == arrays + 1 - " Completing one word and it's a local array variable: build tagline - " from declaration line - let match = items[0] - let kind = 'v' - let tagline = "\t/^" . line . '$/' - let res = [{'match': match, 'tagline' : tagline, 'kind' : kind, 'info' : line}] - else - " Completing "var.", "var.something", etc. - let res = s:Nextitem(strpart(line, 0, col), items[1:], 0, 1) - endif - endif - - if len(items) == 1 || len(items) == arrays + 1 - " Only one part, no "." or "->": complete from tags file. - if len(items) == 1 - let tags = taglist('^' . base) - else - let tags = taglist('^' . items[0] . '$') - endif - - " Remove members, these can't appear without something in front. - call filter(tags, 'has_key(v:val, "kind") ? v:val["kind"] != "m" : 1') - - " Remove static matches in other files. - call filter(tags, '!has_key(v:val, "static") || !v:val["static"] || bufnr("%") == bufnr(v:val["filename"])') - - call extend(res, map(tags, 's:Tag2item(v:val)')) - endif - - if len(res) == 0 - " Find the variable in the tags file(s) - let diclist = taglist('^' . items[0] . '$') - - " Remove members, these can't appear without something in front. - call filter(diclist, 'has_key(v:val, "kind") ? v:val["kind"] != "m" : 1') - - let res = [] - for i in range(len(diclist)) - " New ctags has the "typeref" field. Patched version has "typename". - if has_key(diclist[i], 'typename') - call extend(res, s:StructMembers(diclist[i]['typename'], items[1:], 1)) - elseif has_key(diclist[i], 'typeref') - call extend(res, s:StructMembers(diclist[i]['typeref'], items[1:], 1)) - endif - - " For a variable use the command, which must be a search pattern that - " shows the declaration of the variable. - if diclist[i]['kind'] == 'v' - let line = diclist[i]['cmd'] - if line[0] == '/' && line[1] == '^' - let col = match(line, '\<' . items[0] . '\>') - call extend(res, s:Nextitem(strpart(line, 2, col - 2), items[1:], 0, 1)) - endif - endif - endfor - endif - - if len(res) == 0 && searchdecl(items[0], 1) == 0 - " Found, now figure out the type. - " TODO: join previous line if it makes sense - let line = getline('.') - let col = col('.') - let res = s:Nextitem(strpart(line, 0, col), items[1:], 0, 1) - endif - - " If the last item(s) are [...] they need to be added to the matches. - let last = len(items) - 1 - let brackets = '' - while last >= 0 - if items[last][0] != '[' - break - endif - let brackets = items[last] . brackets - let last -= 1 - endwhile - - return map(res, 's:Tagline2item(v:val, brackets)') -endfunc - -func s:GetAddition(line, match, memarg, bracket) - " Guess if the item is an array. - if a:bracket && match(a:line, a:match . '\s*\[') > 0 - return '[' - endif - - " Check if the item has members. - if len(s:SearchMembers(a:memarg, [''], 0)) > 0 - " If there is a '*' before the name use "->". - if match(a:line, '\*[ \t(]*' . a:match . '\>') > 0 - return '->' - else - return '.' - endif - endif - return '' -endfunc - -" Turn the tag info "val" into an item for completion. -" "val" is is an item in the list returned by taglist(). -" If it is a variable we may add "." or "->". Don't do it for other types, -" such as a typedef, by not including the info that s:GetAddition() uses. -func s:Tag2item(val) - let res = {'match': a:val['name']} - - let res['extra'] = s:Tagcmd2extra(a:val['cmd'], a:val['name'], a:val['filename']) - - let s = s:Dict2info(a:val) - if s != '' - let res['info'] = s - endif - - let res['tagline'] = '' - if has_key(a:val, "kind") - let kind = a:val['kind'] - let res['kind'] = kind - if kind == 'v' - let res['tagline'] = "\t" . a:val['cmd'] - let res['dict'] = a:val - elseif kind == 'f' - let res['match'] = a:val['name'] . '(' - endif - endif - - return res -endfunc - -" Use all the items in dictionary for the "info" entry. -func s:Dict2info(dict) - let info = '' - for k in sort(keys(a:dict)) - let info .= k . repeat(' ', 10 - len(k)) - if k == 'cmd' - let info .= substitute(matchstr(a:dict['cmd'], '/^\s*\zs.*\ze$/'), '\\\(.\)', '\1', 'g') - else - let info .= a:dict[k] - endif - let info .= "\n" - endfor - return info -endfunc - -" Parse a tag line and return a dictionary with items like taglist() -func s:ParseTagline(line) - let l = split(a:line, "\t") - let d = {} - if len(l) >= 3 - let d['name'] = l[0] - let d['filename'] = l[1] - let d['cmd'] = l[2] - let n = 2 - if l[2] =~ '^/' - " Find end of cmd, it may contain Tabs. - while n < len(l) && l[n] !~ '/;"$' - let n += 1 - let d['cmd'] .= " " . l[n] - endwhile - endif - for i in range(n + 1, len(l) - 1) - if l[i] == 'file:' - let d['static'] = 1 - elseif l[i] !~ ':' - let d['kind'] = l[i] - else - let d[matchstr(l[i], '[^:]*')] = matchstr(l[i], ':\zs.*') - endif - endfor - endif - - return d -endfunc - -" Turn a match item "val" into an item for completion. -" "val['match']" is the matching item. -" "val['tagline']" is the tagline in which the last part was found. -func s:Tagline2item(val, brackets) - let line = a:val['tagline'] - let add = s:GetAddition(line, a:val['match'], [a:val], a:brackets == '') - let res = {'word': a:val['match'] . a:brackets . add } - - if has_key(a:val, 'info') - " Use info from Tag2item(). - let res['info'] = a:val['info'] - else - " Parse the tag line and add each part to the "info" entry. - let s = s:Dict2info(s:ParseTagline(line)) - if s != '' - let res['info'] = s - endif - endif - - if has_key(a:val, 'kind') - let res['kind'] = a:val['kind'] - elseif add == '(' - let res['kind'] = 'f' - else - let s = matchstr(line, '\t\(kind:\)\=\zs\S\ze\(\t\|$\)') - if s != '' - let res['kind'] = s - endif - endif - - if has_key(a:val, 'extra') - let res['menu'] = a:val['extra'] - return res - endif - - " Isolate the command after the tag and filename. - let s = matchstr(line, '[^\t]*\t[^\t]*\t\zs\(/^.*$/\|[^\t]*\)\ze\(;"\t\|\t\|$\)') - if s != '' - let res['menu'] = s:Tagcmd2extra(s, a:val['match'], matchstr(line, '[^\t]*\t\zs[^\t]*\ze\t')) - endif - return res -endfunc - -" Turn a command from a tag line to something that is useful in the menu -func s:Tagcmd2extra(cmd, name, fname) - if a:cmd =~ '^/^' - " The command is a search command, useful to see what it is. - let x = matchstr(a:cmd, '^/^\s*\zs.*\ze$/') - let x = substitute(x, '\<' . a:name . '\>', '@@', '') - let x = substitute(x, '\\\(.\)', '\1', 'g') - let x = x . ' - ' . a:fname - elseif a:cmd =~ '^\d*$' - " The command is a line number, the file name is more useful. - let x = a:fname . ' - ' . a:cmd - else - " Not recognized, use command and file name. - let x = a:cmd . ' - ' . a:fname - endif - return x -endfunc - -" Find composing type in "lead" and match items[0] with it. -" Repeat this recursively for items[1], if it's there. -" When resolving typedefs "depth" is used to avoid infinite recursion. -" Return the list of matches. -func s:Nextitem(lead, items, depth, all) - - " Use the text up to the variable name and split it in tokens. - let tokens = split(a:lead, '\s\+\|\<') - - " Try to recognize the type of the variable. This is rough guessing... - let res = [] - for tidx in range(len(tokens)) - - " Skip tokens starting with a non-ID character. - if tokens[tidx] !~ '^\h' - continue - endif - - " Recognize "struct foobar" and "union foobar". - " Also do "class foobar" when it's C++ after all (doesn't work very well - " though). - if (tokens[tidx] == 'struct' || tokens[tidx] == 'union' || tokens[tidx] == 'class') && tidx + 1 < len(tokens) - let res = s:StructMembers(tokens[tidx] . ':' . tokens[tidx + 1], a:items, a:all) - break - endif - - " TODO: add more reserved words - if index(['int', 'short', 'char', 'float', 'double', 'static', 'unsigned', 'extern'], tokens[tidx]) >= 0 - continue - endif - - " Use the tags file to find out if this is a typedef. - let diclist = taglist('^' . tokens[tidx] . '$') - for tagidx in range(len(diclist)) - let item = diclist[tagidx] - - " New ctags has the "typeref" field. Patched version has "typename". - if has_key(item, 'typeref') - call extend(res, s:StructMembers(item['typeref'], a:items, a:all)) - continue - endif - if has_key(item, 'typename') - call extend(res, s:StructMembers(item['typename'], a:items, a:all)) - continue - endif - - " Only handle typedefs here. - if item['kind'] != 't' - continue - endif - - " Skip matches local to another file. - if has_key(item, 'static') && item['static'] && bufnr('%') != bufnr(item['filename']) - continue - endif - - " For old ctags we recognize "typedef struct aaa" and - " "typedef union bbb" in the tags file command. - let cmd = item['cmd'] - let ei = matchend(cmd, 'typedef\s\+') - if ei > 1 - let cmdtokens = split(strpart(cmd, ei), '\s\+\|\<') - if len(cmdtokens) > 1 - if cmdtokens[0] == 'struct' || cmdtokens[0] == 'union' || cmdtokens[0] == 'class' - let name = '' - " Use the first identifier after the "struct" or "union" - for ti in range(len(cmdtokens) - 1) - if cmdtokens[ti] =~ '^\w' - let name = cmdtokens[ti] - break - endif - endfor - if name != '' - call extend(res, s:StructMembers(cmdtokens[0] . ':' . name, a:items, a:all)) - endif - elseif a:depth < 10 - " Could be "typedef other_T some_T". - call extend(res, s:Nextitem(cmdtokens[0], a:items, a:depth + 1, a:all)) - endif - endif - endif - endfor - if len(res) > 0 - break - endif - endfor - - return res -endfunc - - -" Search for members of structure "typename" in tags files. -" Return a list with resulting matches. -" Each match is a dictionary with "match" and "tagline" entries. -" When "all" is non-zero find all, otherwise just return 1 if there is any -" member. -func s:StructMembers(typename, items, all) - " Todo: What about local structures? - let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) - if fnames == '' - return [] - endif - - let typename = a:typename - let qflist = [] - let cached = 0 - if a:all == 0 - let n = '1' " stop at first found match - if has_key(s:grepCache, a:typename) - let qflist = s:grepCache[a:typename] - let cached = 1 - endif - else - let n = '' - endif - if !cached - while 1 - exe 'silent! keepj noautocmd ' . n . 'vimgrep /\t' . typename . '\(\t\|$\)/j ' . fnames - - let qflist = getqflist() - if len(qflist) > 0 || match(typename, "::") < 0 - break - endif - " No match for "struct:context::name", remove "context::" and try again. - let typename = substitute(typename, ':[^:]*::', ':', '') - endwhile - - if a:all == 0 - " Store the result to be able to use it again later. - let s:grepCache[a:typename] = qflist - endif - endif - - " Skip over [...] items - let idx = 0 - while 1 - if idx >= len(a:items) - let target = '' " No further items, matching all members - break - endif - if a:items[idx][0] != '[' - let target = a:items[idx] - break - endif - let idx += 1 - endwhile - " Put matching members in matches[]. - let matches = [] - for l in qflist - let memb = matchstr(l['text'], '[^\t]*') - if memb =~ '^' . target - " Skip matches local to another file. - if match(l['text'], "\tfile:") < 0 || bufnr('%') == bufnr(matchstr(l['text'], '\t\zs[^\t]*')) - let item = {'match': memb, 'tagline': l['text']} - - " Add the kind of item. - let s = matchstr(l['text'], '\t\(kind:\)\=\zs\S\ze\(\t\|$\)') - if s != '' - let item['kind'] = s - if s == 'f' - let item['match'] = memb . '(' - endif - endif - - call add(matches, item) - endif - endif - endfor - - if len(matches) > 0 - " Skip over next [...] items - let idx += 1 - while 1 - if idx >= len(a:items) - return matches " No further items, return the result. - endif - if a:items[idx][0] != '[' - break - endif - let idx += 1 - endwhile - - " More items following. For each of the possible members find the - " matching following members. - return s:SearchMembers(matches, a:items[idx :], a:all) - endif - - " Failed to find anything. - return [] -endfunc - -" For matching members, find matches for following items. -" When "all" is non-zero find all, otherwise just return 1 if there is any -" member. -func s:SearchMembers(matches, items, all) - let res = [] - for i in range(len(a:matches)) - let typename = '' - if has_key(a:matches[i], 'dict') - if has_key(a:matches[i].dict, 'typename') - let typename = a:matches[i].dict['typename'] - elseif has_key(a:matches[i].dict, 'typeref') - let typename = a:matches[i].dict['typeref'] - endif - let line = "\t" . a:matches[i].dict['cmd'] - else - let line = a:matches[i]['tagline'] - let e = matchend(line, '\ttypename:') - if e < 0 - let e = matchend(line, '\ttyperef:') - endif - if e > 0 - " Use typename field - let typename = matchstr(line, '[^\t]*', e) - endif - endif - - if typename != '' - call extend(res, s:StructMembers(typename, a:items, a:all)) - else - " Use the search command (the declaration itself). - let s = match(line, '\t\zs/^') - if s > 0 - let e = match(line, '\<' . a:matches[i]['match'] . '\>', s) - if e > 0 - call extend(res, s:Nextitem(strpart(line, s, e - s), a:items, 0, a:all)) - endif - endif - endif - if a:all == 0 && len(res) > 0 - break - endif - endfor - return res -endfunc - -let &cpo = s:cpo_save -unlet s:cpo_save - -" vim: noet sw=2 sts=2 +" Generated vim file by vim9jit. Please do not edit +let s:path = expand("<script>") +let s:lua_path = fnamemodify(s:path, ":r") . ".lua" +let s:nvim_module = luaeval('require("_vim9script").autoload(_A)', s:lua_path) + +function! ccomplete#Complete(findstart, abase) abort + return s:nvim_module.Complete(a:findstart, a:abase) +endfunction diff --git a/runtime/autoload/dist/ft.vim b/runtime/autoload/dist/ft.vim deleted file mode 100644 index 77140d62b1..0000000000 --- a/runtime/autoload/dist/ft.vim +++ /dev/null @@ -1,1073 +0,0 @@ -" Vim functions for file type detection -" -" Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2022 Apr 13 - -" These functions are moved here from runtime/filetype.vim to make startup -" faster. - -" Line continuation is used here, remove 'C' from 'cpoptions' -let s:cpo_save = &cpo -set cpo&vim - -func dist#ft#Check_inp() - if getline(1) =~ '^\*' - setf abaqus - else - let n = 1 - if line("$") > 500 - let nmax = 500 - else - let nmax = line("$") - endif - while n <= nmax - if getline(n) =~? "^header surface data" - setf trasys - break - endif - let n = n + 1 - endwhile - endif -endfunc - -" This function checks for the kind of assembly that is wanted by the user, or -" can be detected from the first five lines of the file. -func dist#ft#FTasm() - " make sure b:asmsyntax exists - if !exists("b:asmsyntax") - let b:asmsyntax = "" - endif - - if b:asmsyntax == "" - call dist#ft#FTasmsyntax() - endif - - " if b:asmsyntax still isn't set, default to asmsyntax or GNU - if b:asmsyntax == "" - if exists("g:asmsyntax") - let b:asmsyntax = g:asmsyntax - else - let b:asmsyntax = "asm" - endif - endif - - exe "setf " . fnameescape(b:asmsyntax) -endfunc - -func dist#ft#FTasmsyntax() - " see if file contains any asmsyntax=foo overrides. If so, change - " b:asmsyntax appropriately - let head = " ".getline(1)." ".getline(2)." ".getline(3)." ".getline(4). - \" ".getline(5)." " - let match = matchstr(head, '\sasmsyntax=\zs[a-zA-Z0-9]\+\ze\s') - if match != '' - let b:asmsyntax = match - elseif ((head =~? '\.title') || (head =~? '\.ident') || (head =~? '\.macro') || (head =~? '\.subtitle') || (head =~? '\.library')) - let b:asmsyntax = "vmasm" - endif -endfunc - -let s:ft_visual_basic_content = '\cVB_Name\|Begin VB\.\(Form\|MDIForm\|UserControl\)' - -" See FTfrm() for Visual Basic form file detection -func dist#ft#FTbas() - if exists("g:filetype_bas") - exe "setf " . g:filetype_bas - return - endif - - " most frequent FreeBASIC-specific keywords in distro files - let fb_keywords = '\c^\s*\%(extern\|var\|enum\|private\|scope\|union\|byref\|operator\|constructor\|delete\|namespace\|public\|property\|with\|destructor\|using\)\>\%(\s*[:=(]\)\@!' - let fb_preproc = '\c^\s*\%(' .. - \ '#\s*\a\+\|' .. - \ 'option\s\+\%(byval\|dynamic\|escape\|\%(no\)\=gosub\|nokeyword\|private\|static\)\>\|' .. - \ '\%(''\|rem\)\s*\$lang\>\|' .. - \ 'def\%(byte\|longint\|short\|ubyte\|uint\|ulongint\|ushort\)\>' .. - \ '\)' - let fb_comment = "^\\s*/'" - " OPTION EXPLICIT, without the leading underscore, is common to many dialects - let qb64_preproc = '\c^\s*\%($\a\+\|option\s\+\%(_explicit\|_\=explicitarray\)\>\)' - - for lnum in range(1, min([line("$"), 100])) - let line = getline(lnum) - if line =~ s:ft_visual_basic_content - setf vb - return - elseif line =~ fb_preproc || line =~ fb_comment || line =~ fb_keywords - setf freebasic - return - elseif line =~ qb64_preproc - setf qb64 - return - endif - endfor - setf basic -endfunc - -func dist#ft#FTbtm() - if exists("g:dosbatch_syntax_for_btm") && g:dosbatch_syntax_for_btm - setf dosbatch - else - setf btm - endif -endfunc - -func dist#ft#BindzoneCheck(default) - if getline(1).getline(2).getline(3).getline(4) =~ '^; <<>> DiG [0-9.]\+.* <<>>\|$ORIGIN\|$TTL\|IN\s\+SOA' - setf bindzone - elseif a:default != '' - exe 'setf ' . a:default - endif -endfunc - -" Returns true if file content looks like RAPID -func IsRapid(sChkExt = "") - if a:sChkExt == "cfg" - return getline(1) =~? '\v^%(EIO|MMC|MOC|PROC|SIO|SYS):CFG' - endif - " called from FTmod, FTprg or FTsys - return getline(nextnonblank(1)) =~? '\v^\s*%(\%{3}|module\s+\k+\s*%(\(|$))' -endfunc - -func dist#ft#FTcfg() - if exists("g:filetype_cfg") - exe "setf " .. g:filetype_cfg - elseif IsRapid("cfg") - setf rapid - else - setf cfg - endif -endfunc - -func dist#ft#FTcls() - if exists("g:filetype_cls") - exe "setf " .. g:filetype_cls - return - endif - - if getline(1) =~ '^%' - setf tex - elseif getline(1)[0] == '#' && getline(1) =~ 'rexx' - setf rexx - elseif getline(1) == 'VERSION 1.0 CLASS' - setf vb - else - setf st - endif -endfunc - -func dist#ft#FTlpc() - if exists("g:lpc_syntax_for_c") - let lnum = 1 - while lnum <= 12 - if getline(lnum) =~# '^\(//\|inherit\|private\|protected\|nosave\|string\|object\|mapping\|mixed\)' - setf lpc - return - endif - let lnum = lnum + 1 - endwhile - endif - setf c -endfunc - -func dist#ft#FTheader() - if match(getline(1, min([line("$"), 200])), '^@\(interface\|end\|class\)') > -1 - if exists("g:c_syntax_for_h") - setf objc - else - setf objcpp - endif - elseif exists("g:c_syntax_for_h") - setf c - elseif exists("g:ch_syntax_for_h") - setf ch - else - setf cpp - endif -endfunc - -" This function checks if one of the first ten lines start with a '@'. In -" that case it is probably a change file. -" If the first line starts with # or ! it's probably a ch file. -" If a line has "main", "include", "//" or "/*" it's probably ch. -" Otherwise CHILL is assumed. -func dist#ft#FTchange() - let lnum = 1 - while lnum <= 10 - if getline(lnum)[0] == '@' - setf change - return - endif - if lnum == 1 && (getline(1)[0] == '#' || getline(1)[0] == '!') - setf ch - return - endif - if getline(lnum) =~ "MODULE" - setf chill - return - endif - if getline(lnum) =~ 'main\s*(\|#\s*include\|//' - setf ch - return - endif - let lnum = lnum + 1 - endwhile - setf chill -endfunc - -func dist#ft#FTent() - " This function checks for valid cl syntax in the first five lines. - " Look for either an opening comment, '#', or a block start, '{'. - " If not found, assume SGML. - let lnum = 1 - while lnum < 6 - let line = getline(lnum) - if line =~ '^\s*[#{]' - setf cl - return - elseif line !~ '^\s*$' - " Not a blank line, not a comment, and not a block start, - " so doesn't look like valid cl code. - break - endif - let lnum = lnum + 1 - endw - setf dtd -endfunc - -func dist#ft#ExCheck() - let lines = getline(1, min([line("$"), 100])) - if exists('g:filetype_euphoria') - exe 'setf ' . g:filetype_euphoria - elseif match(lines, '^--\|^ifdef\>\|^include\>') > -1 - setf euphoria3 - else - setf elixir - endif -endfunc - -func dist#ft#EuphoriaCheck() - if exists('g:filetype_euphoria') - exe 'setf ' . g:filetype_euphoria - else - setf euphoria3 - endif -endfunc - -func dist#ft#DtraceCheck() - if did_filetype() - " Filetype was already detected - return - endif - let lines = getline(1, min([line("$"), 100])) - if match(lines, '^module\>\|^import\>') > -1 - " D files often start with a module and/or import statement. - setf d - elseif match(lines, '^#!\S\+dtrace\|#pragma\s\+D\s\+option\|:\S\{-}:\S\{-}:') > -1 - setf dtrace - else - setf d - endif -endfunc - -func dist#ft#FTe() - if exists('g:filetype_euphoria') - exe 'setf ' . g:filetype_euphoria - else - let n = 1 - while n < 100 && n <= line("$") - if getline(n) =~ "^\\s*\\(<'\\|'>\\)\\s*$" - setf specman - return - endif - let n = n + 1 - endwhile - setf eiffel - endif -endfunc - -func dist#ft#FTfrm() - if exists("g:filetype_frm") - exe "setf " . g:filetype_frm - return - endif - - let lines = getline(1, min([line("$"), 5])) - - if match(lines, s:ft_visual_basic_content) > -1 - setf vb - else - setf form - endif -endfunc - -" Distinguish between Forth and F#. -" Provided by Doug Kearns. -func dist#ft#FTfs() - if exists("g:filetype_fs") - exe "setf " . g:filetype_fs - else - let line = getline(nextnonblank(1)) - " comments and colon definitions - if line =~ '^\s*\.\=( ' || line =~ '^\s*\\G\= ' || line =~ '^\\$' - \ || line =~ '^\s*: \S' - setf forth - else - setf fsharp - endif - endif -endfunc - -" Distinguish between HTML, XHTML and Django -func dist#ft#FThtml() - let n = 1 - while n < 10 && n <= line("$") - if getline(n) =~ '\<DTD\s\+XHTML\s' - setf xhtml - return - endif - if getline(n) =~ '{%\s*\(extends\|block\|load\)\>\|{#\s\+' - setf htmldjango - return - endif - let n = n + 1 - endwhile - setf FALLBACK html -endfunc - -" Distinguish between standard IDL and MS-IDL -func dist#ft#FTidl() - let n = 1 - while n < 50 && n <= line("$") - if getline(n) =~ '^\s*import\s\+"\(unknwn\|objidl\)\.idl"' - setf msidl - return - endif - let n = n + 1 - endwhile - setf idl -endfunc - -" Distinguish between "default", Prolog and Cproto prototype file. */ -func dist#ft#ProtoCheck(default) - " Cproto files have a comment in the first line and a function prototype in - " the second line, it always ends in ";". Indent files may also have - " comments, thus we can't match comments to see the difference. - " IDL files can have a single ';' in the second line, require at least one - " chacter before the ';'. - if getline(2) =~ '.;$' - setf cpp - else - " recognize Prolog by specific text in the first non-empty line - " require a blank after the '%' because Perl uses "%list" and "%translate" - let l = getline(nextnonblank(1)) - if l =~ '\<prolog\>' || l =~ '^\s*\(%\+\(\s\|$\)\|/\*\)' || l =~ ':-' - setf prolog - else - exe 'setf ' .. a:default - endif - endif -endfunc - -func dist#ft#FTm() - if exists("g:filetype_m") - exe "setf " . g:filetype_m - return - endif - - " excluding end(for|function|if|switch|while) common to Murphi - let octave_block_terminators = '\<end\%(_try_catch\|classdef\|enumeration\|events\|methods\|parfor\|properties\)\>' - - let objc_preprocessor = '^\s*#\s*\%(import\|include\|define\|if\|ifn\=def\|undef\|line\|error\|pragma\)\>' - - let n = 1 - let saw_comment = 0 " Whether we've seen a multiline comment leader. - while n < 100 - let line = getline(n) - if line =~ '^\s*/\*' - " /* ... */ is a comment in Objective C and Murphi, so we can't conclude - " it's either of them yet, but track this as a hint in case we don't see - " anything more definitive. - let saw_comment = 1 - endif - if line =~ '^\s*//' || line =~ '^\s*@import\>' || line =~ objc_preprocessor - setf objc - return - endif - if line =~ '^\s*\%(#\|%!\)' || line =~ '^\s*unwind_protect\>' || - \ line =~ '\%(^\|;\)\s*' .. octave_block_terminators - setf octave - return - endif - " TODO: could be Matlab or Octave - if line =~ '^\s*%' - setf matlab - return - endif - if line =~ '^\s*(\*' - setf mma - return - endif - if line =~ '^\c\s*\(\(type\|var\)\>\|--\)' - setf murphi - return - endif - let n = n + 1 - endwhile - - if saw_comment - " We didn't see anything definitive, but this looks like either Objective C - " or Murphi based on the comment leader. Assume the former as it is more - " common. - setf objc - else - " Default is Matlab - setf matlab - endif -endfunc - -func dist#ft#FTmms() - let n = 1 - while n < 20 - let line = getline(n) - if line =~ '^\s*\(%\|//\)' || line =~ '^\*' - setf mmix - return - endif - if line =~ '^\s*#' - setf make - return - endif - let n = n + 1 - endwhile - setf mmix -endfunc - -" This function checks if one of the first five lines start with a dot. In -" that case it is probably an nroff file: 'filetype' is set and 1 is returned. -func dist#ft#FTnroff() - if getline(1)[0] . getline(2)[0] . getline(3)[0] . getline(4)[0] . getline(5)[0] =~ '\.' - setf nroff - return 1 - endif - return 0 -endfunc - -func dist#ft#FTmm() - let n = 1 - while n < 20 - let line = getline(n) - if line =~ '^\s*\(#\s*\(include\|import\)\>\|@import\>\|/\*\)' - setf objcpp - return - endif - let n = n + 1 - endwhile - setf nroff -endfunc - -" Returns true if file content looks like LambdaProlog module -func IsLProlog() - " 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 - let l = nextnonblank(l + 1) - endwhile - " this pattern must not catch a go.mod file - return getline(l) =~ '\<module\s\+\w\+\s*\.\s*\(%\|$\)' -endfunc - -" Determine if *.mod is ABB RAPID, LambdaProlog, Modula-2, Modsim III or go.mod -func dist#ft#FTmod() - if exists("g:filetype_mod") - exe "setf " .. g:filetype_mod - elseif IsLProlog() - setf lprolog - elseif getline(nextnonblank(1)) =~ '\%(\<MODULE\s\+\w\+\s*;\|^\s*(\*\)' - setf modula2 - elseif IsRapid() - setf rapid - elseif expand("<afile>") =~ '\<go.mod$' - setf gomod - else - " Nothing recognized, assume modsim3 - setf modsim3 - endif -endfunc - -func dist#ft#FTpl() - if exists("g:filetype_pl") - exe "setf " . g:filetype_pl - else - " recognize Prolog by specific text in the first non-empty line - " require a blank after the '%' because Perl uses "%list" and "%translate" - let l = getline(nextnonblank(1)) - if l =~ '\<prolog\>' || l =~ '^\s*\(%\+\(\s\|$\)\|/\*\)' || l =~ ':-' - setf prolog - else - setf perl - endif - endif -endfunc - -func dist#ft#FTinc() - if exists("g:filetype_inc") - exe "setf " . g:filetype_inc - else - let lines = getline(1).getline(2).getline(3) - if lines =~? "perlscript" - setf aspperl - elseif lines =~ "<%" - setf aspvbs - elseif lines =~ "<?" - setf php - " Pascal supports // comments but they're vary rarely used for file - " headers so assume POV-Ray - elseif lines =~ '^\s*\%({\|(\*\)' || lines =~? s:ft_pascal_keywords - setf pascal - elseif lines =~# '\<\%(require\|inherit\)\>' || lines =~# '[A-Z][A-Za-z0-9_:${}]*\s\+\%(??\|[?:+]\)\?= ' - setf bitbake - else - call dist#ft#FTasmsyntax() - if exists("b:asmsyntax") - exe "setf " . fnameescape(b:asmsyntax) - else - setf pov - endif - endif - endif -endfunc - -func dist#ft#FTprogress_cweb() - if exists("g:filetype_w") - exe "setf " . g:filetype_w - return - endif - if getline(1) =~ '&ANALYZE' || getline(3) =~ '&GLOBAL-DEFINE' - setf progress - else - setf cweb - endif -endfunc - -func dist#ft#FTprogress_asm() - if exists("g:filetype_i") - exe "setf " . g:filetype_i - return - endif - " This function checks for an assembly comment the first ten lines. - " If not found, assume Progress. - let lnum = 1 - while lnum <= 10 && lnum < line('$') - let line = getline(lnum) - if line =~ '^\s*;' || line =~ '^\*' - call dist#ft#FTasm() - return - elseif line !~ '^\s*$' || line =~ '^/\*' - " Not an empty line: Doesn't look like valid assembly code. - " Or it looks like a Progress /* comment - break - endif - let lnum = lnum + 1 - endw - setf progress -endfunc - -let s:ft_pascal_comments = '^\s*\%({\|(\*\|//\)' -let s:ft_pascal_keywords = '^\s*\%(program\|unit\|library\|uses\|begin\|procedure\|function\|const\|type\|var\)\>' - -func dist#ft#FTprogress_pascal() - if exists("g:filetype_p") - exe "setf " . g:filetype_p - return - endif - " This function checks for valid Pascal syntax in the first ten lines. - " Look for either an opening comment or a program start. - " If not found, assume Progress. - let lnum = 1 - while lnum <= 10 && lnum < line('$') - let line = getline(lnum) - if line =~ s:ft_pascal_comments || line =~? s:ft_pascal_keywords - setf pascal - return - elseif line !~ '^\s*$' || line =~ '^/\*' - " Not an empty line: Doesn't look like valid Pascal code. - " Or it looks like a Progress /* comment - break - endif - let lnum = lnum + 1 - endw - setf progress -endfunc - -func dist#ft#FTpp() - if exists("g:filetype_pp") - exe "setf " . g:filetype_pp - else - let line = getline(nextnonblank(1)) - if line =~ s:ft_pascal_comments || line =~? s:ft_pascal_keywords - setf pascal - else - setf puppet - endif - endif -endfunc - -" Determine if *.prg is ABB RAPID. Can also be Clipper, FoxPro or eviews -func dist#ft#FTprg() - if exists("g:filetype_prg") - exe "setf " .. g:filetype_prg - elseif IsRapid() - setf rapid - else - " Nothing recognized, assume Clipper - setf clipper - endif -endfunc - -func dist#ft#FTr() - let max = line("$") > 50 ? 50 : line("$") - - for n in range(1, max) - " Rebol is easy to recognize, check for that first - if getline(n) =~? '\<REBOL\>' - setf rebol - return - endif - endfor - - for n in range(1, max) - " R has # comments - if getline(n) =~ '^\s*#' - setf r - return - endif - " Rexx has /* comments */ - if getline(n) =~ '^\s*/\*' - setf rexx - return - endif - endfor - - " Nothing recognized, use user default or assume Rexx - if exists("g:filetype_r") - exe "setf " . g:filetype_r - else - " Rexx used to be the default, but R appears to be much more popular. - setf r - endif -endfunc - -func dist#ft#McSetf() - " Rely on the file to start with a comment. - " MS message text files use ';', Sendmail files use '#' or 'dnl' - for lnum in range(1, min([line("$"), 20])) - let line = getline(lnum) - if line =~ '^\s*\(#\|dnl\)' - setf m4 " Sendmail .mc file - return - elseif line =~ '^\s*;' - setf msmessages " MS Message text file - return - endif - endfor - setf m4 " Default: Sendmail .mc file -endfunc - -" Called from filetype.vim and scripts.vim. -func dist#ft#SetFileTypeSH(name) - if did_filetype() - " Filetype was already detected - return - endif - if expand("<amatch>") =~ g:ft_ignore_pat - return - endif - if a:name =~ '\<csh\>' - " Some .sh scripts contain #!/bin/csh. - call dist#ft#SetFileTypeShell("csh") - return - elseif a:name =~ '\<tcsh\>' - " Some .sh scripts contain #!/bin/tcsh. - call dist#ft#SetFileTypeShell("tcsh") - return - elseif a:name =~ '\<zsh\>' - " Some .sh scripts contain #!/bin/zsh. - call dist#ft#SetFileTypeShell("zsh") - return - elseif a:name =~ '\<ksh\>' - let b:is_kornshell = 1 - if exists("b:is_bash") - unlet b:is_bash - endif - if exists("b:is_sh") - unlet b:is_sh - endif - elseif exists("g:bash_is_sh") || a:name =~ '\<bash\>' || a:name =~ '\<bash2\>' - let b:is_bash = 1 - if exists("b:is_kornshell") - unlet b:is_kornshell - endif - if exists("b:is_sh") - unlet b:is_sh - endif - elseif a:name =~ '\<sh\>' - let b:is_sh = 1 - if exists("b:is_kornshell") - unlet b:is_kornshell - endif - if exists("b:is_bash") - unlet b:is_bash - endif - endif - call dist#ft#SetFileTypeShell("sh") -endfunc - -" For shell-like file types, check for an "exec" command hidden in a comment, -" as used for Tcl. -" Also called from scripts.vim, thus can't be local to this script. -func dist#ft#SetFileTypeShell(name) - if did_filetype() - " Filetype was already detected - return - endif - if expand("<amatch>") =~ g:ft_ignore_pat - return - endif - let l = 2 - while l < 20 && l < line("$") && getline(l) =~ '^\s*\(#\|$\)' - " Skip empty and comment lines. - let l = l + 1 - endwhile - if l < line("$") && getline(l) =~ '\s*exec\s' && getline(l - 1) =~ '^\s*#.*\\$' - " Found an "exec" line after a comment with continuation - let n = substitute(getline(l),'\s*exec\s\+\([^ ]*/\)\=', '', '') - if n =~ '\<tclsh\|\<wish' - setf tcl - return - endif - endif - exe "setf " . a:name -endfunc - -func dist#ft#CSH() - if did_filetype() - " Filetype was already detected - return - endif - if exists("g:filetype_csh") - call dist#ft#SetFileTypeShell(g:filetype_csh) - elseif &shell =~ "tcsh" - call dist#ft#SetFileTypeShell("tcsh") - else - call dist#ft#SetFileTypeShell("csh") - endif -endfunc - -let s:ft_rules_udev_rules_pattern = '^\s*\cudev_rules\s*=\s*"\([^"]\{-1,}\)/*".*' -func dist#ft#FTRules() - let path = expand('<amatch>:p') - if path =~ '/\(etc/udev/\%(rules\.d/\)\=.*\.rules\|\%(usr/\)\=lib/udev/\%(rules\.d/\)\=.*\.rules\)$' - setf udevrules - return - endif - if path =~ '^/etc/ufw/' - setf conf " Better than hog - return - endif - if path =~ '^/\(etc\|usr/share\)/polkit-1/rules\.d' - setf javascript - return - endif - try - let config_lines = readfile('/etc/udev/udev.conf') - catch /^Vim\%((\a\+)\)\=:E484/ - setf hog - return - endtry - let dir = expand('<amatch>:p:h') - for line in config_lines - if line =~ s:ft_rules_udev_rules_pattern - let udev_rules = substitute(line, s:ft_rules_udev_rules_pattern, '\1', "") - if dir == udev_rules - setf udevrules - endif - break - endif - endfor - setf hog -endfunc - -func dist#ft#SQL() - if exists("g:filetype_sql") - exe "setf " . g:filetype_sql - else - setf sql - endif -endfunc - -" This function checks the first 25 lines of file extension "sc" to resolve -" detection between scala and SuperCollider -func dist#ft#FTsc() - for lnum in range(1, min([line("$"), 25])) - if getline(lnum) =~# '[A-Za-z0-9]*\s:\s[A-Za-z0-9]\|var\s<\|classvar\s<\|\^this.*\||\w*|\|+\s\w*\s{\|\*ar\s' - setf supercollider - return - endif - endfor - setf scala -endfunc - -" This function checks the first line of file extension "scd" to resolve -" detection between scdoc and SuperCollider -func dist#ft#FTscd() - if getline(1) =~# '\%^\S\+(\d[0-9A-Za-z]*)\%(\s\+\"[^"]*\"\%(\s\+\"[^"]*\"\)\=\)\=$' - setf scdoc - else - setf supercollider - endif -endfunc - -" If the file has an extension of 't' and is in a directory 't' or 'xt' then -" it is almost certainly a Perl test file. -" If the first line starts with '#' and contains 'perl' it's probably a Perl -" file. -" (Slow test) If a file contains a 'use' statement then it is almost certainly -" a Perl file. -func dist#ft#FTperl() - let dirname = expand("%:p:h:t") - if expand("%:e") == 't' && (dirname == 't' || dirname == 'xt') - setf perl - return 1 - endif - if getline(1)[0] == '#' && getline(1) =~ 'perl' - setf perl - return 1 - endif - let save_cursor = getpos('.') - call cursor(1,1) - let has_use = search('^use\s\s*\k', 'c', 30) > 0 - call setpos('.', save_cursor) - if has_use - setf perl - return 1 - endif - return 0 -endfunc - -" LambdaProlog and Standard ML signature files -func dist#ft#FTsig() - if exists("g:filetype_sig") - exe "setf " .. g:filetype_sig - return - endif - - let lprolog_comment = '^\s*\%(/\*\|%\)' - let lprolog_keyword = '^\s*sig\s\+\a' - let sml_comment = '^\s*(\*' - let sml_keyword = '^\s*\%(signature\|structure\)\s\+\a' - - let line = getline(nextnonblank(1)) - - if line =~ lprolog_comment || line =~# lprolog_keyword - setf lprolog - elseif line =~ sml_comment || line =~# sml_keyword - setf sml - endif -endfunc - -func dist#ft#FTsys() - if exists("g:filetype_sys") - exe "setf " .. g:filetype_sys - elseif IsRapid() - setf rapid - else - setf bat - endif -endfunc - -" Choose context, plaintex, or tex (LaTeX) based on these rules: -" 1. Check the first line of the file for "%&<format>". -" 2. Check the first 1000 non-comment lines for LaTeX or ConTeXt keywords. -" 3. Default to "plain" or to g:tex_flavor, can be set in user's vimrc. -func dist#ft#FTtex() - let firstline = getline(1) - if firstline =~ '^%&\s*\a\+' - let format = tolower(matchstr(firstline, '\a\+')) - let format = substitute(format, 'pdf', '', '') - if format == 'tex' - let format = 'latex' - elseif format == 'plaintex' - let format = 'plain' - endif - elseif expand('%') =~ 'tex/context/.*/.*.tex' - let format = 'context' - else - " Default value, may be changed later: - let format = exists("g:tex_flavor") ? g:tex_flavor : 'plain' - " Save position, go to the top of the file, find first non-comment line. - let save_cursor = getpos('.') - call cursor(1,1) - let firstNC = search('^\s*[^[:space:]%]', 'c', 1000) - if firstNC > 0 - " Check the next thousand lines for a LaTeX or ConTeXt keyword. - let lpat = 'documentclass\>\|usepackage\>\|begin{\|newcommand\>\|renewcommand\>' - let cpat = 'start\a\+\|setup\a\+\|usemodule\|enablemode\|enableregime\|setvariables\|useencoding\|usesymbols\|stelle\a\+\|verwende\a\+\|stel\a\+\|gebruik\a\+\|usa\a\+\|imposta\a\+\|regle\a\+\|utilisemodule\>' - let kwline = search('^\s*\\\%(' . lpat . '\)\|^\s*\\\(' . cpat . '\)', - \ 'cnp', firstNC + 1000) - if kwline == 1 " lpat matched - let format = 'latex' - elseif kwline == 2 " cpat matched - let format = 'context' - endif " If neither matched, keep default set above. - " let lline = search('^\s*\\\%(' . lpat . '\)', 'cn', firstNC + 1000) - " let cline = search('^\s*\\\%(' . cpat . '\)', 'cn', firstNC + 1000) - " if cline > 0 - " let format = 'context' - " endif - " if lline > 0 && (cline == 0 || cline > lline) - " let format = 'tex' - " endif - endif " firstNC - call setpos('.', save_cursor) - endif " firstline =~ '^%&\s*\a\+' - - " Translation from formats to file types. TODO: add AMSTeX, RevTex, others? - if format == 'plain' - setf plaintex - elseif format == 'context' - setf context - else " probably LaTeX - setf tex - endif - return -endfunc - -func dist#ft#FTxml() - let n = 1 - while n < 100 && n <= line("$") - let line = getline(n) - " DocBook 4 or DocBook 5. - let is_docbook4 = line =~ '<!DOCTYPE.*DocBook' - let is_docbook5 = line =~ ' xmlns="http://docbook.org/ns/docbook"' - if is_docbook4 || is_docbook5 - let b:docbk_type = "xml" - if is_docbook5 - let b:docbk_ver = 5 - else - let b:docbk_ver = 4 - endif - setf docbk - return - endif - if line =~ 'xmlns:xbl="http://www.mozilla.org/xbl"' - setf xbl - return - endif - let n += 1 - endwhile - setf xml -endfunc - -func dist#ft#FTy() - let n = 1 - while n < 100 && n <= line("$") - let line = getline(n) - if line =~ '^\s*%' - setf yacc - return - endif - if getline(n) =~ '^\s*\(#\|class\>\)' && getline(n) !~ '^\s*#\s*include' - setf racc - return - endif - let n = n + 1 - endwhile - setf yacc -endfunc - -func dist#ft#Redif() - let lnum = 1 - while lnum <= 5 && lnum < line('$') - if getline(lnum) =~ "^\ctemplate-type:" - setf redif - return - endif - let lnum = lnum + 1 - endwhile -endfunc - -" This function is called for all files under */debian/patches/*, make sure not -" to non-dep3patch files, such as README and other text files. -func dist#ft#Dep3patch() - if expand('%:t') ==# 'series' - return - endif - - for ln in getline(1, 100) - if ln =~# '^\%(Description\|Subject\|Origin\|Bug\|Forwarded\|Author\|From\|Reviewed-by\|Acked-by\|Last-Updated\|Applied-Upstream\):' - setf dep3patch - return - elseif ln =~# '^---' - " end of headers found. stop processing - return - endif - endfor -endfunc - -" This function checks the first 15 lines for appearance of 'FoamFile' -" and then 'object' in a following line. -" In that case, it's probably an OpenFOAM file -func dist#ft#FTfoam() - let ffile = 0 - let lnum = 1 - while lnum <= 15 - if getline(lnum) =~# '^FoamFile' - let ffile = 1 - elseif ffile == 1 && getline(lnum) =~# '^\s*object' - setf foam - return - endif - let lnum = lnum + 1 - endwhile -endfunc - -" Determine if a *.tf file is TF mud client or terraform -func dist#ft#FTtf() - let numberOfLines = line('$') - for i in range(1, numberOfLines) - let currentLine = trim(getline(i)) - let firstCharacter = currentLine[0] - if firstCharacter !=? ";" && firstCharacter !=? "/" && firstCharacter !=? "" - setf terraform - return - endif - endfor - setf tf -endfunc - -let s:ft_krl_header = '\&\w+' -" Determine if a *.src file is Kuka Robot Language -func dist#ft#FTsrc() - let ft_krl_def_or_deffct = '%(global\s+)?def%(fct)?>' - if exists("g:filetype_src") - exe "setf " .. g:filetype_src - elseif getline(nextnonblank(1)) =~? '\v^\s*%(' .. s:ft_krl_header .. '|' .. ft_krl_def_or_deffct .. ')' - setf krl - endif -endfunc - -" Determine if a *.dat file is Kuka Robot Language -func dist#ft#FTdat() - let ft_krl_defdat = 'defdat>' - if exists("g:filetype_dat") - exe "setf " .. g:filetype_dat - elseif getline(nextnonblank(1)) =~? '\v^\s*%(' .. s:ft_krl_header .. '|' .. ft_krl_defdat .. ')' - setf krl - endif -endfunc - -" Restore 'cpoptions' -let &cpo = s:cpo_save -unlet s:cpo_save diff --git a/runtime/autoload/health.vim b/runtime/autoload/health.vim index a693868381..5fd4627b11 100644 --- a/runtime/autoload/health.vim +++ b/runtime/autoload/health.vim @@ -5,8 +5,13 @@ function! health#check(plugin_names) abort \ ? s:discover_healthchecks() \ : s:get_healthcheck(a:plugin_names) - " create scratch-buffer - execute 'tab sbuffer' nvim_create_buf(v:true, v:true) + " Create buffer and open in a tab, unless this is the default buffer when Nvim starts. + let emptybuf = (bufnr('$') == 1 && empty(getline(1)) && 1 == line('$')) + execute (emptybuf ? 'buffer' : 'tab sbuffer') nvim_create_buf(v:true, v:true) + if bufexists('health://') + bwipe health:// + endif + file health:// setfiletype checkhealth if empty(healthchecks) @@ -38,7 +43,7 @@ function! health#check(plugin_names) abort \ name, v:throwpoint, v:exception)) endif endtry - let header = [name. ': ' . func, repeat('=', 72)] + let header = [repeat('=', 78), name .. ': ' .. func, ''] " remove empty line after header from report_start let s:output = s:output[0] == '' ? s:output[1:] : s:output let s:output = header + s:output + [''] @@ -47,8 +52,7 @@ function! health#check(plugin_names) abort endfor endif - " needed for plasticboy/vim-markdown, because it uses fdm=expr - normal! zR + " Clear the 'Running healthchecks...' message. redraw|echo '' endfunction @@ -58,7 +62,7 @@ endfunction " Starts a new report. function! health#report_start(name) abort - call s:collect_output("\n## " . a:name) + call s:collect_output(printf("\n%s ~", a:name)) endfunction " Indents lines *except* line 1 of a string if it contains newlines. @@ -81,7 +85,7 @@ endfunction " Format a message for a specific report item. " a:1: Optional advice (string or list) function! s:format_report_message(status, msg, ...) abort " {{{ - let output = ' - ' . a:status . ': ' . s:indent_after_line1(a:msg, 4) + let output = '- ' .. a:status .. (empty(a:status) ? '' : ' ') .. s:indent_after_line1(a:msg, 2) " Optional parameters if a:0 > 0 @@ -92,9 +96,9 @@ function! s:format_report_message(status, msg, ...) abort " {{{ " Report each suggestion if !empty(advice) - let output .= "\n - ADVICE:" + let output .= "\n - ADVICE:" for suggestion in advice - let output .= "\n - " . s:indent_after_line1(suggestion, 10) + let output .= "\n - " . s:indent_after_line1(suggestion, 6) endfor endif endif @@ -102,9 +106,9 @@ function! s:format_report_message(status, msg, ...) abort " {{{ return s:help_to_link(output) endfunction " }}} -" Use {msg} to report information in the current section +" Reports a message as a listitem in the current section. function! health#report_info(msg) abort " {{{ - call s:collect_output(s:format_report_message('INFO', a:msg)) + call s:collect_output(s:format_report_message('', a:msg)) endfunction " }}} " Reports a successful healthcheck. diff --git a/runtime/autoload/health/nvim.vim b/runtime/autoload/health/nvim.vim deleted file mode 100644 index 9b387095ee..0000000000 --- a/runtime/autoload/health/nvim.vim +++ /dev/null @@ -1,284 +0,0 @@ -let s:suggest_faq = 'https://github.com/neovim/neovim/wiki/FAQ' - -function! s:check_config() abort - let ok = v:true - call health#report_start('Configuration') - - let vimrc = empty($MYVIMRC) ? stdpath('config').'/init.vim' : $MYVIMRC - if !filereadable(vimrc) - let ok = v:false - let has_vim = filereadable(expand('~/.vimrc')) - call health#report_warn((-1 == getfsize(vimrc) ? 'Missing' : 'Unreadable').' user config file: '.vimrc, - \[ has_vim ? ':help nvim-from-vim' : ':help init.vim' ]) - endif - - " If $VIM is empty we don't care. Else make sure it is valid. - if !empty($VIM) && !filereadable($VIM.'/runtime/doc/nvim.txt') - let ok = v:false - call health#report_error('$VIM is invalid: '.$VIM) - endif - - if exists('$NVIM_TUI_ENABLE_CURSOR_SHAPE') - let ok = v:false - call health#report_warn('$NVIM_TUI_ENABLE_CURSOR_SHAPE is ignored in Nvim 0.2+', - \ [ "Use the 'guicursor' option to configure cursor shape. :help 'guicursor'", - \ 'https://github.com/neovim/neovim/wiki/Following-HEAD#20170402' ]) - endif - - if v:ctype ==# 'C' - let ok = v:false - call health#report_error('Locale does not support UTF-8. Unicode characters may not display correctly.' - \ .printf("\n$LANG=%s $LC_ALL=%s $LC_CTYPE=%s", $LANG, $LC_ALL, $LC_CTYPE), - \ [ 'If using tmux, try the -u option.', - \ 'Ensure that your terminal/shell/tmux/etc inherits the environment, or set $LANG explicitly.' , - \ 'Configure your system locale.' ]) - endif - - if &paste - let ok = v:false - call health#report_error("'paste' is enabled. This option is only for pasting text.\nIt should not be set in your config.", - \ [ 'Remove `set paste` from your init.vim, if applicable.', - \ 'Check `:verbose set paste?` to see if a plugin or script set the option.', ]) - endif - - let writeable = v:true - let shadafile = empty(&shada) ? &shada : substitute(matchstr( - \ split(&shada, ',')[-1], '^n.\+'), '^n', '', '') - let shadafile = empty(&shadafile) ? empty(shadafile) ? - \ stdpath('state').'/shada/main.shada' : expand(shadafile) - \ : &shadafile ==# 'NONE' ? '' : &shadafile - if !empty(shadafile) && empty(glob(shadafile)) - " Since this may be the first time neovim has been run, we will try to - " create a shada file - try - wshada - catch /.*/ - let writeable = v:false - endtry - endif - if !writeable || (!empty(shadafile) && - \ (!filereadable(shadafile) || !filewritable(shadafile))) - let ok = v:false - call health#report_error('shada file is not '. - \ ((!writeable || filereadable(shadafile)) ? - \ 'writeable' : 'readable').":\n".shadafile) - endif - - if ok - call health#report_ok('no issues found') - endif -endfunction - -" Load the remote plugin manifest file and check for unregistered plugins -function! s:check_rplugin_manifest() abort - call health#report_start('Remote Plugins') - let existing_rplugins = {} - - for item in remote#host#PluginsForHost('python') - let existing_rplugins[item.path] = 'python' - endfor - - for item in remote#host#PluginsForHost('python3') - let existing_rplugins[item.path] = 'python3' - endfor - - let require_update = 0 - - for path in map(split(&runtimepath, ','), 'resolve(v:val)') - let python_glob = glob(path.'/rplugin/python*', 1, 1) - if empty(python_glob) - continue - endif - - let python_dir = python_glob[0] - let python_version = fnamemodify(python_dir, ':t') - - for script in glob(python_dir.'/*.py', 1, 1) - \ + glob(python_dir.'/*/__init__.py', 1, 1) - let contents = join(readfile(script)) - if contents =~# '\<\%(from\|import\)\s\+neovim\>' - if script =~# '[\/]__init__\.py$' - let script = tr(fnamemodify(script, ':h'), '\', '/') - endif - - if !has_key(existing_rplugins, script) - let msg = printf('"%s" is not registered.', fnamemodify(path, ':t')) - if python_version ==# 'pythonx' - if !has('python3') - let msg .= ' (python3 not available)' - endif - elseif !has(python_version) - let msg .= printf(' (%s not available)', python_version) - else - let require_update = 1 - endif - - call health#report_warn(msg) - endif - - break - endif - endfor - endfor - - if require_update - call health#report_warn('Out of date', ['Run `:UpdateRemotePlugins`']) - else - call health#report_ok('Up to date') - endif -endfunction - -function! s:check_performance() abort - call health#report_start('Performance') - - " check buildtype - let buildtype = matchstr(execute('version'), '\v\cbuild type:?\s*[^\n\r\t ]+') - if empty(buildtype) - call health#report_error('failed to get build type from :version') - elseif buildtype =~# '\v(MinSizeRel|Release|RelWithDebInfo)' - call health#report_ok(buildtype) - else - call health#report_info(buildtype) - call health#report_warn( - \ 'Non-optimized '.(has('debug')?'(DEBUG) ':'').'build. Nvim will be slower.', - \ ['Install a different Nvim package, or rebuild with `CMAKE_BUILD_TYPE=RelWithDebInfo`.', - \ s:suggest_faq]) - endif - - " check for slow shell invocation - let slow_cmd_time = 1.5 - let start_time = reltime() - call system('echo') - let elapsed_time = reltimefloat(reltime(start_time)) - if elapsed_time > slow_cmd_time - call health#report_warn( - \ 'Slow shell invocation (took '.printf('%.2f', elapsed_time).' seconds).') - endif -endfunction - -function! s:get_tmux_option(option) abort - let cmd = 'tmux show-option -qvg '.a:option " try global scope - let out = system(split(cmd)) - let val = substitute(out, '\v(\s|\r|\n)', '', 'g') - if v:shell_error - call health#report_error('command failed: '.cmd."\n".out) - return 'error' - elseif empty(val) - let cmd = 'tmux show-option -qvgs '.a:option " try session scope - let out = system(split(cmd)) - let val = substitute(out, '\v(\s|\r|\n)', '', 'g') - if v:shell_error - call health#report_error('command failed: '.cmd."\n".out) - return 'error' - endif - endif - return val -endfunction - -function! s:check_tmux() abort - if empty($TMUX) || !executable('tmux') - return - endif - call health#report_start('tmux') - - " check escape-time - let suggestions = ["set escape-time in ~/.tmux.conf:\nset-option -sg escape-time 10", - \ s:suggest_faq] - let tmux_esc_time = s:get_tmux_option('escape-time') - if tmux_esc_time !=# 'error' - if empty(tmux_esc_time) - call health#report_error('`escape-time` is not set', suggestions) - elseif tmux_esc_time > 300 - call health#report_error( - \ '`escape-time` ('.tmux_esc_time.') is higher than 300ms', suggestions) - else - call health#report_ok('escape-time: '.tmux_esc_time) - endif - endif - - " check focus-events - let suggestions = ["(tmux 1.9+ only) Set `focus-events` in ~/.tmux.conf:\nset-option -g focus-events on"] - let tmux_focus_events = s:get_tmux_option('focus-events') - call health#report_info('Checking stuff') - if tmux_focus_events !=# 'error' - if empty(tmux_focus_events) || tmux_focus_events !=# 'on' - call health#report_warn( - \ "`focus-events` is not enabled. |'autoread'| may not work.", suggestions) - else - call health#report_ok('focus-events: '.tmux_focus_events) - endif - endif - - " check default-terminal and $TERM - call health#report_info('$TERM: '.$TERM) - let cmd = 'tmux show-option -qvg default-terminal' - let out = system(split(cmd)) - let tmux_default_term = substitute(out, '\v(\s|\r|\n)', '', 'g') - if empty(tmux_default_term) - let cmd = 'tmux show-option -qvgs default-terminal' - let out = system(split(cmd)) - let tmux_default_term = substitute(out, '\v(\s|\r|\n)', '', 'g') - endif - - if v:shell_error - call health#report_error('command failed: '.cmd."\n".out) - elseif tmux_default_term !=# $TERM - call health#report_info('default-terminal: '.tmux_default_term) - call health#report_error( - \ '$TERM differs from the tmux `default-terminal` setting. Colors might look wrong.', - \ ['$TERM may have been set by some rc (.bashrc, .zshrc, ...).']) - elseif $TERM !~# '\v(tmux-256color|screen-256color)' - call health#report_error( - \ '$TERM should be "screen-256color" or "tmux-256color" in tmux. Colors might look wrong.', - \ ["Set default-terminal in ~/.tmux.conf:\nset-option -g default-terminal \"screen-256color\"", - \ s:suggest_faq]) - endif - - " check for RGB capabilities - let info = system(['tmux', 'server-info']) - let has_tc = stridx(info, " Tc: (flag) true") != -1 - let has_rgb = stridx(info, " RGB: (flag) true") != -1 - if !has_tc && !has_rgb - call health#report_warn( - \ "Neither Tc nor RGB capability set. True colors are disabled. |'termguicolors'| won't work properly.", - \ ["Put this in your ~/.tmux.conf and replace XXX by your $TERM outside of tmux:\nset-option -sa terminal-overrides ',XXX:RGB'", - \ "For older tmux versions use this instead:\nset-option -ga terminal-overrides ',XXX:Tc'"]) - endif -endfunction - -function! s:check_terminal() abort - if !executable('infocmp') - return - endif - call health#report_start('terminal') - let cmd = 'infocmp -L' - let out = system(split(cmd)) - let kbs_entry = matchstr(out, 'key_backspace=[^,[:space:]]*') - let kdch1_entry = matchstr(out, 'key_dc=[^,[:space:]]*') - - if v:shell_error - \ && (!has('win32') - \ || empty(matchstr(out, - \ 'infocmp: couldn''t open terminfo file .\+' - \ ..'\%(conemu\|vtpcon\|win32con\)'))) - call health#report_error('command failed: '.cmd."\n".out) - else - call health#report_info('key_backspace (kbs) terminfo entry: ' - \ .(empty(kbs_entry) ? '? (not found)' : kbs_entry)) - call health#report_info('key_dc (kdch1) terminfo entry: ' - \ .(empty(kbs_entry) ? '? (not found)' : kdch1_entry)) - endif - for env_var in ['XTERM_VERSION', 'VTE_VERSION', 'TERM_PROGRAM', 'COLORTERM', 'SSH_TTY'] - if exists('$'.env_var) - call health#report_info(printf("$%s='%s'", env_var, eval('$'.env_var))) - endif - endfor -endfunction - -function! health#nvim#check() abort - call s:check_config() - call s:check_performance() - call s:check_rplugin_manifest() - call s:check_terminal() - call s:check_tmux() -endfunction 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/netrw.vim b/runtime/autoload/netrw.vim index ef0282848f..2fcf0b32c7 100644 --- a/runtime/autoload/netrw.vim +++ b/runtime/autoload/netrw.vim @@ -1751,8 +1751,10 @@ fun! s:NetrwOptionsRestore(vt) " call Decho("settings buf#".bufnr("%")."<".bufname("%").">: ".((&l:ma == 0)? "no" : "")."ma ".((&l:mod == 0)? "no" : "")."mod ".((&l:bl == 0)? "no" : "")."bl ".((&l:ro == 0)? "no" : "")."ro fo=".&l:fo." a:vt=".a:vt,'~'.expand("<slnum>")) if !exists("{a:vt}netrw_optionsave") " call Decho("case ".a:vt."netrw_optionsave : doesn't exist",'~'.expand("<slnum>")) -" call Decho("..doing filetype detect anyway") - filetype detect + if !isdirectory(expand('%')) +" call Decho("..doing filetype detect anyway") + filetype detect + endif " call Decho("..settings buf#".bufnr("%")."<".bufname("%").">: ".((&l:ma == 0)? "no" : "")."ma ".((&l:mod == 0)? "no" : "")."mod ".((&l:bl == 0)? "no" : "")."bl ".((&l:ro == 0)? "no" : "")."ro fo=".&l:fo." a:vt=".a:vt,'~'.expand("<slnum>")) " call Decho("..ro=".&l:ro." ma=".&l:ma." mod=".&l:mod." wrap=".&l:wrap." (filename<".expand("%")."> win#".winnr()." ft<".&ft.">)",'~'.expand("<slnum>")) " call Dret("s:NetrwOptionsRestore : ".a:vt."netrw_optionsave doesn't exist") @@ -1859,9 +1861,11 @@ fun! s:NetrwOptionsRestore(vt) " were having their filetype detect-generated settings overwritten by " NetrwOptionRestore. if &ft != "netrw" -" call Decho("before: filetype detect (ft=".&ft.")",'~'.expand("<slnum>")) - filetype detect -" call Decho("after : filetype detect (ft=".&ft.")",'~'.expand("<slnum>")) + if !isdirectory(expand('%')) +" call Decho("before: filetype detect (ft=".&ft.")",'~'.expand("<slnum>")) + filetype detect +" call Decho("after : filetype detect (ft=".&ft.")",'~'.expand("<slnum>")) + endif endif " call Decho("(s:NetrwOptionsRestore) lines=".&lines) " call Decho("settings buf#".bufnr("%")."<".bufname("%").">: ".((&l:ma == 0)? "no" : "")."ma ".((&l:mod == 0)? "no" : "")."mod ".((&l:bl == 0)? "no" : "")."bl ".((&l:ro == 0)? "no" : "")."ro fo=".&l:fo." a:vt=".a:vt,'~'.expand("<slnum>")) @@ -6442,7 +6446,6 @@ fun! s:NetrwMaps(islocal) " if !hasmapto('<Plug>NetrwMarkFileGrep') |nmap <buffer> <silent> <nowait> mg <Plug>NetrwMarkFileGrep|endif " if !hasmapto('<Plug>NetrwMarkHideSfx') |nmap <buffer> <silent> <nowait> mh <Plug>NetrwMarkHideSfx|endif " if !hasmapto('<Plug>NetrwMarkFileMove') |nmap <buffer> <silent> <nowait> mm <Plug>NetrwMarkFileMove|endif -" if !hasmapto('<Plug>NetrwMarkFilePrint') |nmap <buffer> <silent> <nowait> mp <Plug>NetrwMarkFilePrint|endif " if !hasmapto('<Plug>NetrwMarkFileRegexp') |nmap <buffer> <silent> <nowait> mr <Plug>NetrwMarkFileRegexp|endif " if !hasmapto('<Plug>NetrwMarkFileSource') |nmap <buffer> <silent> <nowait> ms <Plug>NetrwMarkFileSource|endif " if !hasmapto('<Plug>NetrwMarkFileTag') |nmap <buffer> <silent> <nowait> mT <Plug>NetrwMarkFileTag|endif @@ -6505,7 +6508,6 @@ fun! s:NetrwMaps(islocal) nnoremap <buffer> <silent> <nowait> mg :<c-u>call <SID>NetrwMarkFileGrep(1)<cr> nnoremap <buffer> <silent> <nowait> mh :<c-u>call <SID>NetrwMarkHideSfx(1)<cr> nnoremap <buffer> <silent> <nowait> mm :<c-u>call <SID>NetrwMarkFileMove(1)<cr> - nnoremap <buffer> <silent> <nowait> mp :<c-u>call <SID>NetrwMarkFilePrint(1)<cr> nnoremap <buffer> <silent> <nowait> mr :<c-u>call <SID>NetrwMarkFileRegexp(1)<cr> nnoremap <buffer> <silent> <nowait> ms :<c-u>call <SID>NetrwMarkFileSource(1)<cr> nnoremap <buffer> <silent> <nowait> mT :<c-u>call <SID>NetrwMarkFileTag(1)<cr> @@ -6618,7 +6620,6 @@ fun! s:NetrwMaps(islocal) nnoremap <buffer> <silent> <nowait> mg :<c-u>call <SID>NetrwMarkFileGrep(0)<cr> nnoremap <buffer> <silent> <nowait> mh :<c-u>call <SID>NetrwMarkHideSfx(0)<cr> nnoremap <buffer> <silent> <nowait> mm :<c-u>call <SID>NetrwMarkFileMove(0)<cr> - nnoremap <buffer> <silent> <nowait> mp :<c-u>call <SID>NetrwMarkFilePrint(0)<cr> nnoremap <buffer> <silent> <nowait> mr :<c-u>call <SID>NetrwMarkFileRegexp(0)<cr> nnoremap <buffer> <silent> <nowait> ms :<c-u>call <SID>NetrwMarkFileSource(0)<cr> nnoremap <buffer> <silent> <nowait> mT :<c-u>call <SID>NetrwMarkFileTag(0)<cr> @@ -7836,46 +7837,6 @@ fun! s:NetrwMarkFileMove(islocal) endfun " --------------------------------------------------------------------- -" s:NetrwMarkFilePrint: (invoked by mp) This function prints marked files {{{2 -" using the hardcopy command. Local marked-file list only. -fun! s:NetrwMarkFilePrint(islocal) -" call Dfunc("s:NetrwMarkFilePrint(islocal=".a:islocal.")") - let curbufnr= bufnr("%") - - " sanity check - if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr}) - NetrwKeepj call netrw#ErrorMsg(2,"there are no marked files in this window (:help netrw-mf)",66) -" call Dret("s:NetrwMarkFilePrint") - return - endif -" call Decho("sanity chk passed: s:netrwmarkfilelist_".curbufnr."<".string(s:netrwmarkfilelist_{curbufnr}),'~'.expand("<slnum>")) - let curdir= s:NetrwGetCurdir(a:islocal) - - if exists("s:netrwmarkfilelist_{curbufnr}") - let netrwmarkfilelist = s:netrwmarkfilelist_{curbufnr} - call s:NetrwUnmarkList(curbufnr,curdir) - for fname in netrwmarkfilelist - if a:islocal - if g:netrw_keepdir - let fname= s:ComposePath(curdir,fname) - endif - else - let fname= curdir.fname - endif - 1split - " the autocmds will handle both local and remote files -" call Decho("exe sil e ".escape(fname,' '),'~'.expand("<slnum>")) - exe "sil NetrwKeepj e ".fnameescape(fname) -" call Decho("hardcopy",'~'.expand("<slnum>")) - hardcopy - q - endfor - 2match none - endif -" call Dret("s:NetrwMarkFilePrint") -endfun - -" --------------------------------------------------------------------- " s:NetrwMarkFileRegexp: (invoked by mr) This function is used to mark {{{2 " files when given a regexp (for which a prompt is " issued) (matches to name of files). diff --git a/runtime/autoload/provider/clipboard.vim b/runtime/autoload/provider/clipboard.vim index 991bed6bbd..98c80f1843 100644 --- a/runtime/autoload/provider/clipboard.vim +++ b/runtime/autoload/provider/clipboard.vim @@ -97,18 +97,24 @@ function! provider#clipboard#Executable() abort let s:copy['*'] = ['wl-copy', '--foreground', '--primary', '--type', 'text/plain'] let s:paste['*'] = ['wl-paste', '--no-newline', '--primary'] return 'wl-copy' - elseif !empty($DISPLAY) && executable('xclip') - let s:copy['+'] = ['xclip', '-quiet', '-i', '-selection', 'clipboard'] - let s:paste['+'] = ['xclip', '-o', '-selection', 'clipboard'] - let s:copy['*'] = ['xclip', '-quiet', '-i', '-selection', 'primary'] - let s:paste['*'] = ['xclip', '-o', '-selection', 'primary'] - return 'xclip' + elseif !empty($WAYLAND_DISPLAY) && executable('waycopy') && executable('waypaste') + let s:copy['+'] = ['waycopy', '-t', 'text/plain'] + let s:paste['+'] = ['waypaste', '-t', 'text/plain'] + let s:copy['*'] = s:copy['+'] + let s:paste['*'] = s:paste['+'] + return 'wayclip' elseif !empty($DISPLAY) && executable('xsel') && s:cmd_ok('xsel -o -b') let s:copy['+'] = ['xsel', '--nodetach', '-i', '-b'] let s:paste['+'] = ['xsel', '-o', '-b'] let s:copy['*'] = ['xsel', '--nodetach', '-i', '-p'] let s:paste['*'] = ['xsel', '-o', '-p'] return 'xsel' + elseif !empty($DISPLAY) && executable('xclip') + let s:copy['+'] = ['xclip', '-quiet', '-i', '-selection', 'clipboard'] + let s:paste['+'] = ['xclip', '-o', '-selection', 'clipboard'] + let s:copy['*'] = ['xclip', '-quiet', '-i', '-selection', 'primary'] + let s:paste['*'] = ['xclip', '-o', '-selection', 'primary'] + return 'xclip' elseif executable('lemonade') let s:copy['+'] = ['lemonade', 'copy'] let s:paste['+'] = ['lemonade', 'paste'] @@ -139,7 +145,12 @@ function! provider#clipboard#Executable() abort let s:paste['*'] = s:paste['+'] return 'termux-clipboard' elseif !empty($TMUX) && executable('tmux') - let s:copy['+'] = ['tmux', 'load-buffer', '-'] + let ver = matchlist(systemlist(['tmux', '-V'])[0], '\vtmux %(next-)?(\d+)\.(\d+)') + if len(ver) >= 3 && (ver[1] > 3 || (ver[1] == 3 && ver[2] >= 2)) + let s:copy['+'] = ['tmux', 'load-buffer', '-w', '-'] + else + let s:copy['+'] = ['tmux', 'load-buffer', '-'] + endif let s:paste['+'] = ['tmux', 'save-buffer', '-'] let s:copy['*'] = s:copy['+'] let s:paste['*'] = s:paste['+'] diff --git a/runtime/autoload/provider/node.vim b/runtime/autoload/provider/node.vim index 45b1dd4fd7..87af0094fe 100644 --- a/runtime/autoload/provider/node.vim +++ b/runtime/autoload/provider/node.vim @@ -71,13 +71,11 @@ function! provider#node#Detect() abort let yarn_opts = deepcopy(s:NodeHandler) let yarn_opts.entry_point = '/node_modules/neovim/bin/cli.js' " `yarn global dir` is slow (> 250ms), try the default path first - " XXX: The following code is not portable " https://github.com/yarnpkg/yarn/issues/2049#issuecomment-263183768 - if has('unix') - let yarn_default_path = $HOME . '/.config/yarn/global/' . yarn_opts.entry_point - if filereadable(yarn_default_path) - return [yarn_default_path, ''] - endif + let yarn_config_dir = has('win32') ? '/AppData/Local/Yarn/Data' : '/.config/yarn' + let yarn_default_path = $HOME . yarn_config_dir . '/global/' . yarn_opts.entry_point + if filereadable(yarn_default_path) + return [yarn_default_path, ''] endif let yarn_opts.job_id = jobstart('yarn global dir', yarn_opts) endif 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/autoload/tohtml.vim b/runtime/autoload/tohtml.vim index 66f1cb46cb..4ae17815ba 100644 --- a/runtime/autoload/tohtml.vim +++ b/runtime/autoload/tohtml.vim @@ -712,6 +712,9 @@ func! tohtml#GetUserSettings() "{{{ call tohtml#GetOption(user_settings, 'no_foldcolumn', user_settings.ignore_folding) call tohtml#GetOption(user_settings, 'hover_unfold', 0 ) call tohtml#GetOption(user_settings, 'no_pre', 0 ) + call tohtml#GetOption(user_settings, 'no_doc', 0 ) + call tohtml#GetOption(user_settings, 'no_links', 0 ) + call tohtml#GetOption(user_settings, 'no_modeline', 0 ) call tohtml#GetOption(user_settings, 'no_invalid', 0 ) call tohtml#GetOption(user_settings, 'whole_filler', 0 ) call tohtml#GetOption(user_settings, 'use_xhtml', 0 ) @@ -752,7 +755,7 @@ func! tohtml#GetUserSettings() "{{{ " pre_wrap doesn't do anything if not using pre or not using CSS if user_settings.no_pre || !user_settings.use_css - let user_settings.pre_wrap=0 + let user_settings.pre_wrap = 0 endif "}}} diff --git a/runtime/autoload/tutor.vim b/runtime/autoload/tutor.vim index abf5c5e2c8..4da4213826 100644 --- a/runtime/autoload/tutor.vim +++ b/runtime/autoload/tutor.vim @@ -104,7 +104,7 @@ function! tutor#CheckLine(line) if exists('b:tutor_metadata') && has_key(b:tutor_metadata, 'expect') let bufn = bufnr('%') let ctext = getline(a:line) - let signs = sign_getplaced('.', {'lnum': a:line})[0].signs + let signs = sign_getplaced(bufn, {'lnum': a:line})[0].signs if !empty(signs) call sign_unplace('', {'id': signs[0].id}) endif diff --git a/runtime/autoload/zig/fmt.vim b/runtime/autoload/zig/fmt.vim new file mode 100644 index 0000000000..b78c1994dd --- /dev/null +++ b/runtime/autoload/zig/fmt.vim @@ -0,0 +1,100 @@ +" Adapted from fatih/vim-go: autoload/go/fmt.vim +" +" Copyright 2011 The Go Authors. All rights reserved. +" Use of this source code is governed by a BSD-style +" license that can be found in the LICENSE file. +" +" Upstream: https://github.com/ziglang/zig.vim + +function! zig#fmt#Format() abort + " Save cursor position and many other things. + let view = winsaveview() + + if !executable('zig') + echohl Error | echomsg "no zig binary found in PATH" | echohl None + return + endif + + let cmdline = 'zig fmt --stdin --ast-check' + let current_buf = bufnr('') + + " The formatted code is output on stdout, the errors go on stderr. + if exists('*systemlist') + silent let out = systemlist(cmdline, current_buf) + else + silent let out = split(system(cmdline, current_buf)) + endif + if len(out) == 1 + if out[0] == "error: unrecognized parameter: '--ast-check'" + let cmdline = 'zig fmt --stdin' + if exists('*systemlist') + silent let out = systemlist(cmdline, current_buf) + else + silent let out = split(system(cmdline, current_buf)) + endif + endif + endif + let err = v:shell_error + + + if err == 0 + " remove undo point caused via BufWritePre. + try | silent undojoin | catch | endtry + + " Replace the file content with the formatted version. + if exists('*deletebufline') + call deletebufline(current_buf, len(out), line('$')) + else + silent execute ':' . len(out) . ',' . line('$') . ' delete _' + endif + call setline(1, out) + + " No errors detected, close the loclist. + call setloclist(0, [], 'r') + lclose + elseif get(g:, 'zig_fmt_parse_errors', 1) + let errors = s:parse_errors(expand('%'), out) + + call setloclist(0, [], 'r', { + \ 'title': 'Errors', + \ 'items': errors, + \ }) + + let max_win_height = get(g:, 'zig_fmt_max_window_height', 5) + " Prevent the loclist from becoming too long. + let win_height = min([max_win_height, len(errors)]) + " Open the loclist, but only if there's at least one error to show. + execute 'silent! lwindow ' . win_height + endif + + call winrestview(view) + + if err != 0 + echohl Error | echomsg "zig fmt returned error" | echohl None + return + endif + + " Run the syntax highlighter on the updated content and recompute the folds if + " needed. + syntax sync fromstart +endfunction + +" parse_errors parses the given errors and returns a list of parsed errors +function! s:parse_errors(filename, lines) abort + " list of errors to be put into location list + let errors = [] + for line in a:lines + let tokens = matchlist(line, '^\(.\{-}\):\(\d\+\):\(\d\+\)\s*\(.*\)') + if !empty(tokens) + call add(errors,{ + \"filename": a:filename, + \"lnum": tokens[2], + \"col": tokens[3], + \"text": tokens[4], + \ }) + endif + endfor + + return errors +endfunction +" vim: sw=2 ts=2 et diff --git a/runtime/colors/blue.vim b/runtime/colors/blue.vim index 0d2f07c654..aa99bacd3b 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi Normal guifg=#ffd700 guibg=#000087 gui=NONE cterm=NONE hi CursorLine guifg=NONE guibg=#005faf gui=NONE cterm=NONE @@ -57,7 +61,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 +124,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 +171,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 +234,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 +284,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 +347,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 +459,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..c7bba4471e 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link CursorColumn CursorLine @@ -65,6 +69,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 +177,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..d9db90f2c5 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -25,6 +29,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 +63,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 +103,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 +137,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..0b56740664 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -25,6 +29,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 +103,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..4a33e33eec 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 = &t_Co hi! link Terminal Normal hi! link Boolean Constant @@ -43,9 +43,15 @@ 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi Normal guifg=#00ffff guibg=#000000 gui=NONE cterm=NONE hi QuickFixLine guifg=#ffffff guibg=#2e8b57 gui=NONE cterm=NONE diff --git a/runtime/colors/evening.vim b/runtime/colors/evening.vim index 7e0609e9c4..70ae55aa8d 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,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link VertSplit StatusLineNC hi! link StatusLineTerm StatusLine @@ -64,6 +68,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 +104,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 +176,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 +212,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 +287,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 +323,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 +504,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..f6aa5609b1 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,14 +13,20 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor 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 +148,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..f09786000d 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi Normal guifg=#dadada guibg=#000000 gui=NONE cterm=NONE hi EndOfBuffer guifg=#444444 guibg=#000000 gui=NONE cterm=NONE @@ -51,7 +55,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 +88,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 +129,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 +162,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 +206,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 +239,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..67719123a2 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 = &t_Co hi! link Terminal Normal hi! link Boolean Constant @@ -49,9 +49,15 @@ 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi Normal guifg=#ffffff guibg=#000000 gui=NONE cterm=NONE hi ColorColumn guifg=NONE guibg=#8b0000 gui=NONE cterm=NONE diff --git a/runtime/colors/lunaperche.vim b/runtime/colors/lunaperche.vim index d6c73eb28c..2954f622aa 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 = &t_Co 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,56 @@ 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor 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 +141,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 +149,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 +158,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 +170,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 +190,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 +199,20 @@ 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi Normal guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE hi Statusline guifg=#ffffff guibg=#000000 gui=bold cterm=bold @@ -193,46 +231,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 +280,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 +312,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 +370,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 +420,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 +428,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 +447,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 +467,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 +476,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 +501,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 +548,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 +572,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 +588,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 +617,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 +636,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 +669,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 +679,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 +698,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 +717,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 +755,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 +773,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 +787,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 +818,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 +836,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 +851,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 +947,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 +963,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 +975,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 +997,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..5c6a617137 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -26,6 +30,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 +102,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..47d7dbe22e 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -26,6 +30,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 +102,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..8766cc4776 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,24 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor 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 +94,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 +125,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 +171,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 +193,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 +284,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 +406,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..0bab72dace 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -24,6 +28,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 +100,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..d286839250 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 = &t_Co 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 @@ -47,6 +49,10 @@ hi! link debugPC CursorLine if &background ==# 'dark' if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#080808', '#d7005f', '#00af5f', '#d78700', '#0087d7', '#d787d7', '#00afaf', '#dadada', '#707070', '#ff005f', '#00d75f', '#ffaf00', '#5fafff', '#ff87ff', '#00d7d7', '#ffffff'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi Normal guifg=#dadada guibg=#080808 gui=NONE cterm=NONE hi ColorColumn guifg=NONE guibg=#1c1c1c gui=NONE cterm=NONE @@ -59,8 +65,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 +90,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 @@ -112,6 +118,10 @@ else " Light background if (has('termguicolors') && &termguicolors) || has('gui_running') let g:terminal_ansi_colors = ['#080808', '#af0000', '#005f00', '#af5f00', '#005faf', '#870087', '#008787', '#d7d7d7', '#626262', '#d70000', '#008700', '#d78700', '#0087d7', '#af00af', '#00afaf', '#ffffff'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi Normal guifg=#080808 guibg=#d7d7d7 gui=NONE cterm=NONE hi ColorColumn guifg=NONE guibg=#e4e4e4 gui=NONE cterm=NONE @@ -153,9 +163,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 +198,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 +223,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 +289,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 +358,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 +420,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 +487,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 +549,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 +660,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..d3a692a69f 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 = &t_Co hi! link Terminal Normal hi! link Boolean Constant @@ -46,9 +46,15 @@ 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi Normal guifg=#00ffff guibg=#000000 gui=NONE cterm=NONE hi ColorColumn guifg=NONE guibg=#cd0000 gui=NONE cterm=NONE diff --git a/runtime/colors/shine.vim b/runtime/colors/shine.vim index b84be280e1..b30ac415d0 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -28,6 +32,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 +110,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..6da572d9a7 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -24,6 +28,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 +105,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..bec681bb4e 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -26,6 +30,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 +103,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..af48ef86dc 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,10 +13,14 @@ 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 = &t_Co 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'] + " Nvim uses g:terminal_color_{0-15} instead + for i in range(g:terminal_ansi_colors->len()) + let g:terminal_color_{i} = g:terminal_ansi_colors[i] + endfor endif hi! link Terminal Normal hi! link LineNrAbove LineNr @@ -24,6 +28,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 +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=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/dotnet.vim b/runtime/compiler/dotnet.vim new file mode 100644 index 0000000000..ac64084663 --- /dev/null +++ b/runtime/compiler/dotnet.vim @@ -0,0 +1,39 @@ +" Vim compiler file +" Compiler: dotnet build (.NET CLI) +" Maintainer: Nick Jensen <nickspoon@gmail.com> +" Last Change: 2022-12-06 +" License: Vim (see :h license) +" Repository: https://github.com/nickspoons/vim-cs + +if exists("current_compiler") + finish +endif +let current_compiler = "dotnet" + +if exists(":CompilerSet") != 2 " older Vim always used :setlocal + command -nargs=* CompilerSet setlocal <args> +endif + +let s:cpo_save = &cpo +set cpo&vim + +if get(g:, "dotnet_errors_only", v:false) + CompilerSet makeprg=dotnet\ build\ -nologo + \\ -consoleloggerparameters:NoSummary + \\ -consoleloggerparameters:ErrorsOnly +else + CompilerSet makeprg=dotnet\ build\ -nologo\ -consoleloggerparameters:NoSummary +endif + +if get(g:, "dotnet_show_project_file", v:true) + CompilerSet errorformat=%E%f(%l\\,%c):\ %trror\ %m, + \%W%f(%l\\,%c):\ %tarning\ %m, + \%-G%.%# +else + CompilerSet errorformat=%E%f(%l\\,%c):\ %trror\ %m\ [%.%#], + \%W%f(%l\\,%c):\ %tarning\ %m\ [%.%#], + \%-G%.%# +endif + +let &cpo = s:cpo_save +unlet s:cpo_save 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/compiler/zig.vim b/runtime/compiler/zig.vim new file mode 100644 index 0000000000..2cc6831329 --- /dev/null +++ b/runtime/compiler/zig.vim @@ -0,0 +1,28 @@ +" Vim compiler file +" Compiler: Zig Compiler +" Upstream: https://github.com/ziglang/zig.vim + +if exists("current_compiler") + finish +endif +let current_compiler = "zig" + +let s:save_cpo = &cpo +set cpo&vim + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +" a subcommand must be provided for the this compiler (test, build-exe, etc) +if has('patch-7.4.191') + CompilerSet makeprg=zig\ \$*\ \%:S +else + CompilerSet makeprg=zig\ \$*\ \"%\" +endif + +" TODO: improve errorformat as needed. + +let &cpo = s:save_cpo +unlet s:save_cpo +" vim: tabstop=8 shiftwidth=4 softtabstop=4 expandtab diff --git a/runtime/compiler/zig_build.vim b/runtime/compiler/zig_build.vim new file mode 100644 index 0000000000..0441267b64 --- /dev/null +++ b/runtime/compiler/zig_build.vim @@ -0,0 +1,29 @@ +" Vim compiler file +" Compiler: Zig Compiler (zig build) +" Upstream: https://github.com/ziglang/zig.vim + +if exists('current_compiler') + finish +endif +runtime compiler/zig.vim +let current_compiler = 'zig_build' + +let s:save_cpo = &cpo +set cpo&vim + + +if exists(':CompilerSet') != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +if exists('g:zig_build_makeprg_params') + execute 'CompilerSet makeprg=zig\ build\ '.escape(g:zig_build_makeprg_params, ' \|"').'\ $*' +else + CompilerSet makeprg=zig\ build\ $* +endif + +" TODO: anything to add to errorformat for zig build specifically? + +let &cpo = s:save_cpo +unlet s:save_cpo +" vim: tabstop=8 shiftwidth=4 softtabstop=4 expandtab diff --git a/runtime/compiler/zig_build_exe.vim b/runtime/compiler/zig_build_exe.vim new file mode 100644 index 0000000000..20f0bb3366 --- /dev/null +++ b/runtime/compiler/zig_build_exe.vim @@ -0,0 +1,27 @@ +" Vim compiler file +" Compiler: Zig Compiler (zig build-exe) +" Upstream: https://github.com/ziglang/zig.vim + +if exists('current_compiler') + finish +endif +runtime compiler/zig.vim +let current_compiler = 'zig_build_exe' + +let s:save_cpo = &cpo +set cpo&vim + + +if exists(':CompilerSet') != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +if has('patch-7.4.191') + CompilerSet makeprg=zig\ build-exe\ \%:S\ \$* +else + CompilerSet makeprg=zig\ build-exe\ \"%\"\ \$* +endif + +let &cpo = s:save_cpo +unlet s:save_cpo +" vim: tabstop=8 shiftwidth=4 softtabstop=4 expandtab diff --git a/runtime/compiler/zig_test.vim b/runtime/compiler/zig_test.vim new file mode 100644 index 0000000000..a82d2a6378 --- /dev/null +++ b/runtime/compiler/zig_test.vim @@ -0,0 +1,27 @@ +" Vim compiler file +" Compiler: Zig Compiler (zig test) +" Upstream: https://github.com/ziglang/zig.vim + +if exists('current_compiler') + finish +endif +runtime compiler/zig.vim +let current_compiler = 'zig_test' + +let s:save_cpo = &cpo +set cpo&vim + + +if exists(':CompilerSet') != 2 + command -nargs=* CompilerSet setlocal <args> +endif + +if has('patch-7.4.191') + CompilerSet makeprg=zig\ test\ \%:S\ \$* +else + CompilerSet makeprg=zig\ test\ \"%\"\ \$* +endif + +let &cpo = s:save_cpo +unlet s:save_cpo +" vim: tabstop=8 shiftwidth=4 softtabstop=4 expandtab 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..0e1cc3c28c 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -51,7 +51,7 @@ Connecting to the socket is the easiest way a programmer can test the API, which can be done through any msgpack-rpc client library or full-featured |api-client|. Here's a Ruby script that prints "hello world!" in the current Nvim instance: -> +>ruby #!/usr/bin/env ruby # Requires msgpack-rpc: gem install msgpack-rpc # @@ -79,10 +79,11 @@ functions can be called interactively: < You can also embed Nvim via |jobstart()|, and communicate using |rpcrequest()| and |rpcnotify()|: -> +>vim 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: @@ -200,9 +201,9 @@ any of these approaches: Example (requires Python "pyyaml" and "msgpack-python" modules): > nvim --api-info | python -c 'import msgpack, sys, yaml; yaml.dump(msgpack.unpackb(sys.stdin.buffer.read()), sys.stdout)' < - 3. Use the |api_info()| Vimscript function. > + 3. Use the |api_info()| Vimscript function. >vim :lua print(vim.inspect(vim.fn.api_info())) -< Example using |filter()| to exclude non-deprecated API functions: > +< Example using |filter()| to exclude non-deprecated API functions: >vim :new|put =map(filter(api_info().functions, '!has_key(v:val,''deprecated_since'')'), 'v:val.name') ============================================================================== @@ -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,16 +355,16 @@ 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}, {new_lastline}, {old_byte_size} [, {old_utf32_size}, {old_utf16_size}]). Unlike remote channel events the text contents are not passed. The new text can -be accessed inside the callback as - - `vim.api.nvim_buf_get_lines(buf, firstline, new_lastline, true)` +be accessed inside the callback as >lua + vim.api.nvim_buf_get_lines(buf, firstline, new_lastline, true) +< {old_byte_size} is the total size of the replaced region {firstline} to {lastline} in bytes, including the final newline after {lastline}. if `utf_sizes` is set to true in |nvim_buf_attach()| keyword args, then the @@ -390,7 +400,7 @@ performance can be improved by calling |nvim_buf_add_highlight()| as an asynchronous notification, after first (synchronously) requesting a source id. Example using the Python API client (|pynvim|): -> +>python src = vim.new_highlight_source() buf = vim.current.buffer for i in range(5): @@ -404,7 +414,7 @@ clear highlights from a specific source, in a specific line range or the entire buffer by passing in the line range 0, -1 (the latter is the default in python as used above). -Example using the API from Vimscript: > +Example using the API from Vimscript: >vim call nvim_buf_set_lines(0, 0, 0, v:true, ["test text"]) let src = nvim_buf_add_highlight(0, 0, "String", 1, 0, 4) @@ -428,12 +438,12 @@ Two ways to create a floating window: To close it use |nvim_win_close()| or a command such as |:close|. To check whether a window is floating, check whether the `relative` option in -its config is non-empty: > +its config is non-empty: >lua 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; @@ -446,7 +456,7 @@ Currently, floating windows don't support some widgets like scrollbar. The output of |:mksession| does not include commands for restoring floating windows. -Example: create a float with scratch buffer: > +Example: create a float with scratch buffer: >vim let buf = nvim_create_buf(v:false, v:true) call nvim_buf_set_lines(buf, 0, -1, v:true, ["test", "text"]) @@ -455,10 +465,10 @@ 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* +Extended marks *api-extended-marks* *extmarks* *extmark* Extended marks (extmarks) represent buffer annotations that track text changes in the buffer. They can represent cursors, folds, misspelled words, anything @@ -499,30 +509,32 @@ 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 +< +>vim let g:mark_ns = nvim_create_namespace('myplugin') let g:mark_id = nvim_buf_set_extmark(0, g:mark_ns, 0, 2, {}) < -We can get the mark by its id: > +We can get the mark by its id: >vim echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {}) - => [0, 2] + " => [0, 2] -We can get all marks in a buffer by |namespace| (or by a range): > +We can get all marks in a buffer by |namespace| (or by a range): >vim echo nvim_buf_get_extmarks(0, g:mark_ns, 0, -1, {}) - => [[1, 0, 2]] + " => [[1, 0, 2]] Deleting all surrounding text does NOT remove an extmark! To remove extmarks use |nvim_buf_del_extmark()|. Deleting "x" in our example: > 0 12345678 0 e|ample.. -< ^ extmark position -> + ^ extmark position +< +>vim echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {}) - => [0, 1] + " => [0, 1] < Note: Extmark "gravity" decides how it will shift after a text edit. See |nvim_buf_set_extmark()| @@ -544,9 +556,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 +570,7 @@ nvim__id({obj}) *nvim__id()* in plugins. Parameters: ~ - {obj} Object to return. + • {obj} Object to return. Return: ~ its argument. @@ -570,7 +582,7 @@ nvim__id_array({arr}) *nvim__id_array()* in plugins. Parameters: ~ - {arr} Array to return. + • {arr} Array to return. Return: ~ its argument. @@ -582,7 +594,7 @@ nvim__id_dictionary({dct}) *nvim__id_dictionary()* in plugins. Parameters: ~ - {dct} Dictionary to return. + • {dct} Dictionary to return. Return: ~ its argument. @@ -594,7 +606,7 @@ nvim__id_float({flt}) *nvim__id_float()* in plugins. Parameters: ~ - {flt} Value to return. + • {flt} Value to return. Return: ~ its argument. @@ -624,7 +636,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 +660,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 +702,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 +715,35 @@ 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()* +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. + • verbose: Message was printed as a result of 'verbose' + option if Nvim was invoked with -V3log_file, the message + will be redirected to the log_file and suppressed from + direct output. 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 +755,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 +766,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 +775,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 +791,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. @@ -791,15 +807,15 @@ nvim_feedkeys({keys}, {mode}, {escape_ks}) *nvim_feedkeys()* with escape_ks=false) to replace |keycodes|, then pass the result to nvim_feedkeys(). - Example: > + Example: >vim :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true) :call nvim_feedkeys(key, 'n', v:false) < 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. @@ -847,13 +863,13 @@ nvim_get_color_by_name({name}) *nvim_get_color_by_name()* Returns the 24-bit RGB value of a |nvim_get_color_map()| color name or "#rrggbb" hexadecimal string. - Example: > + Example: >vim :echo nvim_get_color_by_name("Pink") :echo nvim_get_color_by_name("#cbcbcb") < 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 +887,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 +922,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 +935,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 +953,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 +969,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 +1005,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 +1016,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 +1026,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 +1035,7 @@ nvim_get_vvar({name}) *nvim_get_vvar()* Gets a v: variable. Parameters: ~ - {name} Variable name + • {name} Variable name Return: ~ Variable value @@ -1043,7 +1059,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 +1083,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 @@ -1115,7 +1133,7 @@ nvim_list_uis() *nvim_list_uis()* • "width" Requested width of the UI • "rgb" true if the UI uses RGB colors (false implies |cterm-colors|) • "ext_..." Requested UI extensions, see |ui-option| - • "chan" Channel id of remote UI (not present for TUI) + • "chan" |channel-id| of remote UI nvim_list_wins() *nvim_list_wins()* Gets the current list of window handles. @@ -1127,7 +1145,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 +1154,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 +1174,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 +1191,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 +1208,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 +1230,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 +1246,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 @@ -1239,20 +1257,22 @@ nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special}) *nvim_select_popupmenu_item()* nvim_select_popupmenu_item({item}, {insert}, {finish}, {opts}) - Selects an item in the completion popupmenu. + Selects an item in the completion popup menu. - If |ins-completion| is not active this API call is silently ignored. - Useful for an external UI using |ui-popupmenu| to control the popupmenu - with the mouse. Can also be used in a mapping; use <cmd> |:map-cmd| to - ensure the mapping doesn't end completion mode. + If neither |ins-completion| nor |cmdline-completion| popup menu is active + this API call is silently ignored. Useful for an external UI using + |ui-popupmenu| to control the popup menu with the mouse. Can also be used + in a mapping; use <Cmd> |:map-cmd| or a Lua mapping to 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`. - {opts} Optional parameters. Reserved for future use. + • {insert} For |ins-completion|, whether the selection should be + inserted in the buffer. Ignored for |cmdline-completion|. + • {finish} Finish the completion and dismiss the popup menu. Implies + {insert}. + • {opts} Optional parameters. Reserved for future use. *nvim_set_client_info()* nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) @@ -1274,8 +1294,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 +1304,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 +1313,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 +1325,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 +1341,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 +1356,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 +1365,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 +1374,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 +1392,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 +1414,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. @@ -1428,22 +1448,22 @@ nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()* Unlike |:map|, leading/trailing whitespace is accepted as part of the {lhs} or {rhs}. Empty {rhs} is |<Nop>|. |keycodes| are replaced as usual. - Example: > + Example: >vim call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true}) < - is equivalent to: > + is equivalent to: >vim nmap <nowait> <Space><NL> <Nop> < 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 +1476,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 +1503,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 +1512,7 @@ nvim_unsubscribe({event}) *nvim_unsubscribe()* |RPC| only Parameters: ~ - {event} Event type string + • {event} Event type string ============================================================================== @@ -1505,9 +1525,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 +1538,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 +1556,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 +1565,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 +1580,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 +1600,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 +1613,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 +1681,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 +1694,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 +1714,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. @@ -1724,19 +1750,20 @@ nvim_create_user_command({name}, {command}, {*opts}) {command} is the replacement text or Lua function to execute. - Example: > + Example: >vim :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {}) :SayHello Hello world! < 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: + • name: (string) Command name • args: (string) The args passed to the command, if any |<args>| • fargs: (table) The args split by unescaped whitespace @@ -1756,7 +1783,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 +1801,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 +1809,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,24 +1823,25 @@ 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. + • addr: (string) Value of |:command-addr|. Uses short name or "line" + for -addr=lines. • nargs: (string) Value of |:command-nargs|. • nextcmd: (string) Next command if there are multiple commands separated by a |:bar|. Empty if there isn't a next command. @@ -1839,13 +1867,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 +1893,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 +1904,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 +1921,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 +1944,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 +1956,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 +1971,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 +1983,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 +1995,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 +2006,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 ============================================================================== @@ -2003,20 +2032,20 @@ whether a buffer is loaded. nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()* Activates buffer-update events on a channel, or as Lua callbacks. - Example (Lua): capture buffer updates in a global `events` variable (use "print(vim.inspect(events))" to see its contents): > + Example (Lua): capture buffer updates in a global `events` variable (use "print(vim.inspect(events))" to see its contents): >lua events = {} vim.api.nvim_buf_attach(0, false, { on_lines=function(...) table.insert(events, {...}) end}) < 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 +2116,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 +2131,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 +2144,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 +2158,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 +2168,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 +2180,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 +2194,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 +2203,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 +2222,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 +2237,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 +2252,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 +2269,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 +2289,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 +2303,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 +2314,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 +2327,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 +2336,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 +2346,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 +2369,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 +2389,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 +2406,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 +2429,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 +2476,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: ~ @@ -2454,39 +2489,39 @@ nvim_buf_add_highlight({buffer}, {ns_id}, {hl_group}, {line}, {col_start}, *nvim_buf_clear_namespace()* nvim_buf_clear_namespace({buffer}, {ns_id}, {line_start}, {line_end}) - Clears namespaced objects (highlights, extmarks, virtual text) from a + Clears |namespace|d objects (highlights, |extmarks|, virtual text) from a region. Lines are 0-indexed. |api-indexing| To clear the namespace in the entire 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. + 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 *nvim_buf_get_extmark_by_id()* nvim_buf_get_extmark_by_id({buffer}, {ns_id}, {id}, {opts}) - Gets the position (0-indexed) of an extmark. + 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: ~ @@ -2494,45 +2529,43 @@ nvim_buf_get_extmark_by_id({buffer}, {ns_id}, {id}, {opts}) *nvim_buf_get_extmarks()* nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) - Gets extmarks in "traversal order" from a |charwise| region defined by + Gets |extmarks| in "traversal order" from a |charwise| region defined by buffer positions (inclusive, 0-indexed |api-indexing|). Region can be given as (row,col) tuples, or valid extmark ids (whose positions define the bounds). 0 and -1 are understood as (0,0) and (-1,-1) - respectively, thus the following are equivalent: -> - nvim_buf_get_extmarks(0, my_ns, 0, -1, {}) - nvim_buf_get_extmarks(0, my_ns, [0,0], [-1,-1], {}) + respectively, thus the following are equivalent: >lua + vim.api.nvim_buf_get_extmarks(0, my_ns, 0, -1, {}) + vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) < If `end` is less than `start`, traversal works backwards. (Useful with `limit`, to get the first marks prior to a given position.) - Example: -> - local a = vim.api - local pos = a.nvim_win_get_cursor(0) - local ns = a.nvim_create_namespace('my-plugin') - -- Create new extmark at line 1, column 1. - local m1 = a.nvim_buf_set_extmark(0, ns, 0, 0, {}) - -- Create new extmark at line 3, column 1. - local m2 = a.nvim_buf_set_extmark(0, ns, 0, 2, {}) - -- Get extmarks only from line 3. - local ms = a.nvim_buf_get_extmarks(0, ns, {2,0}, {2,0}, {}) - -- Get all marks in this buffer + namespace. - local all = a.nvim_buf_get_extmarks(0, ns, 0, -1, {}) - print(vim.inspect(ms)) + Example: >lua + local a = vim.api + local pos = a.nvim_win_get_cursor(0) + local ns = a.nvim_create_namespace('my-plugin') + -- Create new extmark at line 1, column 1. + local m1 = a.nvim_buf_set_extmark(0, ns, 0, 0, {}) + -- Create new extmark at line 3, column 1. + local m2 = a.nvim_buf_set_extmark(0, ns, 2, 0, {}) + -- Get extmarks only from line 3. + local ms = a.nvim_buf_get_extmarks(0, ns, {2,0}, {2,0}, {}) + -- Get all marks in this buffer + namespace. + local all = a.nvim_buf_get_extmarks(0, ns, 0, -1, {}) + print(vim.inspect(ms)) < 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 @@ -2541,7 +2574,7 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) *nvim_buf_set_extmark()* nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) - Creates or updates an extmark. + Creates or updates an |extmark|. By default a new extmark is created when no id is passed in, but it is also possible to create a new mark by passing in a previously unused id or @@ -2553,11 +2586,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 +2602,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 +2638,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 +2676,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 @@ -2652,7 +2687,7 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) Id of the created/updated extmark nvim_create_namespace({name}) *nvim_create_namespace()* - Creates a new *namespace* or gets an existing one. + Creates a new namespace or gets an existing one. *namespace* Namespaces are used for buffer highlights and virtual text, see |nvim_buf_add_highlight()| and |nvim_buf_set_extmark()|. @@ -2662,26 +2697,26 @@ 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 nvim_get_namespaces() *nvim_get_namespaces()* - Gets existing, non-anonymous namespaces. + Gets existing, non-anonymous |namespace|s. Return: ~ dict that maps from names to namespace ids. *nvim_set_decoration_provider()* -nvim_set_decoration_provider({ns_id}, {opts}) - Set or change decoration provider for a namespace +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 + 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 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 +2737,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 +2761,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 +2783,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 +2792,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 +2819,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 +2828,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 +2837,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 +2846,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 +2855,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 +2865,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 +2876,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 +2900,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 ============================================================================== @@ -2935,12 +2972,12 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* could let floats hover outside of the main window like a tooltip, but this should not be used to specify arbitrary WM screen positions. - Example (Lua): window-relative float > + Example (Lua): window-relative float >lua vim.api.nvim_open_win(0, false, {relative='win', row=3, col=3, width=12, height=3}) < - Example (Lua): buffer-relative float (travels as buffer is scrolled) > + Example (Lua): buffer-relative float (travels as buffer is scrolled) >lua vim.api.nvim_open_win(0, false, {relative='win', width=12, height=3, bufpos={100,10}}) < @@ -2949,15 +2986,16 @@ 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 • "win" Window given by the `win` field, or current window. • "cursor" Cursor position in current window. + • "mouse" Mouse position • win: |window-ID| for relative="win". • anchor: Decides which corner of the float to place at @@ -3005,10 +3043,10 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* Disables 'number', 'relativenumber', 'cursorline', 'cursorcolumn', 'foldcolumn', 'spell' and 'list' 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 - 'winhighlight'. + 'colorcolumn' is cleared. 'statuscolumn' is changed to + empty. The end-of-buffer region is hidden by setting + `eob` flag of 'fillchars' to a space char, and clearing + the |hl-EndOfBuffer| region in 'winhighlight'. • border: Style of (optional) window border. This can either be a string or an array. The string values are @@ -3034,9 +3072,14 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* borders but not horizontal ones. By default, `FloatBorder` highlight is used, which links to `WinSeparator` when not defined. It could also be - specified by character: [ {"+", "MyCorner"}, {"x", - "MyBorder"} ]. - + specified by character: [ ["+", "MyCorner"], ["x", + "MyBorder"] ]. + + • title: Title (optional) in window border, String or list. + List is [text, highlight] tuples. if is string the default + highlight group is `FloatTitle`. + • title_pos: Title position must set with title option. + value can be of `left` `center` `right` default is left. • noautocmd: If true then no buffer-related autocommand events such as |BufEnter|, |BufLeave| or |BufWinEnter| may fire from calling this function. @@ -3052,7 +3095,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 +3108,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 +3122,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 +3138,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 +3148,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 +3157,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 +3166,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 +3176,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 +3186,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" } @@ -3171,15 +3214,15 @@ nvim_clear_autocmds({*opts}) *nvim_clear_autocmds()* nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()* Create or get an autocommand group |autocmd-groups|. - To get an existing group id, do: > + To get an existing group id, do: >lua local id = vim.api.nvim_create_augroup("MyGroup", { clear = false }) < 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|. @@ -3190,84 +3233,54 @@ nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()* |autocmd-groups| nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* - Create an |autocommand| - - The API allows for two (mutually exclusive) types of actions to be - executed when the autocommand triggers: a callback function (Lua or - Vimscript), or a command (like regular autocommands). - - Example using callback: > - -- Lua function - local myluafun = function() print("This buffer enters") end - - -- Vimscript function name (as a string) - local myvimfun = "g:MyVimFunction" + Creates an |autocommand| event handler, defined by `callback` (Lua function or Vimscript function name string) or `command` (Ex command string). + Example using Lua callback: >lua vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { pattern = {"*.c", "*.h"}, - callback = myluafun, -- Or myvimfun + callback = function(ev) + print(string.format('event fired: s', vim.inspect(ev))) + end }) < - Lua functions receive a table with information about the autocmd event as - an argument. To use a function which itself accepts another (optional) - parameter, wrap the function in a lambda: -> - -- Lua function with an optional parameter. - -- The autocmd callback would pass a table as argument but this - -- function expects number|nil - local myluafun = function(bufnr) bufnr = bufnr or vim.api.nvim_get_current_buf() end - - vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { - pattern = {"*.c", "*.h"}, - callback = function() myluafun() end, - }) -< - - Example using command: > + Example using an Ex command as the handler: >lua vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { pattern = {"*.c", "*.h"}, command = "echo 'Entering a C or C++ file'", }) < - Example values for pattern: > - pattern = "*.py" - pattern = { "*.py", "*.pyi" } -< - - Example values for event: > - "BufWritePre" - {"CursorHold", "BufWritePre", "BufWritePost"} + Note: `pattern` is NOT automatically expanded (unlike with |:autocmd|), thus names like + "$HOME" and "~" must be expanded explicitly: >lua + pattern = vim.fn.expand("~") .. "/some/path/*.py" < Parameters: ~ - {event} (string|array) The event or events to register this - autocommand - {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 - match against |autocmd-pattern|. - • buffer (integer) optional: buffer number for buffer local + • {event} (string|array) Event(s) that will trigger the handler + (`callback` or `command`). + • {opts} Options dict: + • group (string|integer) optional: autocommand group name or + id to match against. + • pattern (string|array) optional: pattern(s) to match + literally |autocmd-pattern|. + • buffer (integer) optional: buffer number for buffer-local autocommands |autocmd-buflocal|. Cannot be used with {pattern}. - • desc (string) optional: description of the autocommand. - • callback (function|string) optional: if a string, the name - of a Vimscript function to call when this autocommand is - triggered. Otherwise, a Lua function which is called when - this autocommand is triggered. Cannot be used with - {command}. Lua callbacks can return true to delete the - autocommand; in addition, they accept a single table - argument with the following keys: - • id: (number) the autocommand id - • event: (string) the name of the event that triggered the - autocommand |autocmd-events| - • group: (number|nil) the autocommand group id, if it - exists - • match: (string) the expanded value of |<amatch>| - • buf: (number) the expanded value of |<abuf>| - • file: (string) the expanded value of |<afile>| + • desc (string) optional: description (for documentation and + troubleshooting). + • callback (function|string) optional: Lua function (or + Vimscript function name, if string) called when the + event(s) is triggered. Lua callback can return true to + delete the autocommand, and receives a table argument with + these keys: + • id: (number) autocommand id + • event: (string) name of the triggered event + |autocmd-events| + • group: (number|nil) autocommand group id, if any + • match: (string) expanded value of |<amatch>| + • buf: (number) expanded value of |<abuf>| + • file: (string) expanded value of |<afile>| • data: (any) arbitrary data passed to |nvim_exec_autocmds()| @@ -3279,7 +3292,7 @@ nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* autocommands |autocmd-nested|. Return: ~ - Integer id of the created autocommand. + Autocommand id (number) See also: ~ |autocommand| @@ -3290,12 +3303,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 +3317,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 +3333,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 +3343,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 "*" @@ -3349,7 +3362,7 @@ nvim_exec_autocmds({event}, {*opts}) *nvim_exec_autocmds()* nvim_get_autocmds({*opts}) *nvim_get_autocmds()* Get all autocommands that match the corresponding {opts}. - These examples will get autocommands matching ALL the given criteria: > + These examples will get autocommands matching ALL the given criteria: >lua -- Matches all criteria autocommands = vim.api.nvim_get_autocmds({ group = "MyGroup", @@ -3367,13 +3380,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 +3429,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 +3443,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 +3457,26 @@ 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_focus({gained}) *nvim_ui_set_focus()* + Tells the nvim server if focus was gained or lost by the GUI. + + Attributes: ~ + |RPC| only nvim_ui_set_option({name}, {value}) *nvim_ui_set_option()* TODO: Documentation @@ -3479,8 +3501,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/arabic.txt b/runtime/doc/arabic.txt index 0df861111c..0a80edb981 100644 --- a/runtime/doc/arabic.txt +++ b/runtime/doc/arabic.txt @@ -14,8 +14,9 @@ It is best to view this file with these settings within VIM's GUI: > :set arabicshape +------------------------------------------------------------------------------ Introduction ------------- + Arabic is a rather demanding language in which a number of special features are required. Characters are right-to-left oriented and ought to appear as such on the screen (i.e. from right to left). @@ -34,8 +35,9 @@ The commands, prompts and help files are not in Arabic, therefore the user interface remains the standard Vi interface. +------------------------------------------------------------------------------ Highlights ----------- + o Editing left-to-right files as in the original Vim hasn't changed. o Viewing and editing files in right-to-left windows. File @@ -64,8 +66,8 @@ o Proper Bidirectional functionality is possible given Vim is started within a Bidi capable terminal emulator. +------------------------------------------------------------------------------ Arabic Fonts *arabicfonts* ------------- Vim requires monospaced fonts of which there are many out there. Arabic requires ISO-8859-6 as well as Presentation Form-B fonts @@ -75,8 +77,8 @@ Do an Internet search or check www.arabeyes.org for further info on where to obtain the necessary Arabic fonts. +------------------------------------------------------------------------------ Font Installation ------------------ o Installation of fonts for X Window systems (Unix/Linux) @@ -88,8 +90,9 @@ o Installation of fonts for X Window systems (Unix/Linux) % xset +fp path_name_of_arabic_fonts_directory +------------------------------------------------------------------------------ Usage ------ + Prior to the actual usage of Arabic within Vim, a number of settings need to be accounted for and invoked. @@ -259,8 +262,8 @@ o Enable Arabic settings [short-cut] ':set arabicshape' to your vimrc file. +------------------------------------------------------------------------------ Keymap/Keyboard *arabickeymap* ---------------- The character/letter encoding used in Vim is the standard UTF-8. It is widely discouraged that any other encoding be used or even @@ -276,7 +279,7 @@ o Keyboard + CTRL-^ in insert/replace mode toggles between Arabic/Latin mode + Keyboard mapping is based on the Microsoft's Arabic keymap (the - de facto standard in the Arab world): + de facto standard in the Arab world): > +---------------------------------------------------------------------+ |! |@ |# |$ |% |^ |& |* |( |) |_ |+ || |~ Ù‘ | @@ -291,17 +294,18 @@ o Keyboard |Z ~ |X Ù’ |C { |V } |B لآ |N Ø¢ |M ' |< , |> . |? ØŸ | |z ئ |x Ø¡ |c ؤ |v ر |b لا |n Ù‰ |m Ø© |, Ùˆ |. ز |/ ظ | +-------------------------------------------------+ +< +------------------------------------------------------------------------------ Restrictions ------------- o Vim in its GUI form does not currently support Bi-directionality (i.e. the ability to see both Arabic and Latin intermixed within the same line). +------------------------------------------------------------------------------ Known Bugs ----------- There is one known minor bug, diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt index 63226fe701..8cc4754880 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 @@ -678,16 +681,12 @@ FuncUndefined When a user function is used but it isn't UIEnter After a UI connects via |nvim_ui_attach()|, or after builtin TUI is started, after |VimEnter|. Sets these |v:event| keys: - chan: 0 for builtin TUI - 1 for |--embed| - |channel-id| of the UI otherwise + chan: |channel-id| of the UI *UILeave* UILeave After a UI disconnects from Nvim, or after builtin TUI is stopped, after |VimLeave|. Sets these |v:event| keys: - chan: 0 for builtin TUI - 1 for |--embed| - |channel-id| of the UI otherwise + chan: |channel-id| of the UI *InsertChange* InsertChange When typing <Insert> while in Insert or Replace mode. The |v:insertmode| variable @@ -803,7 +802,7 @@ OptionSet After setting an option (except during QuickFixCmdPre Before a quickfix command is run (|:make|, |:lmake|, |:grep|, |:lgrep|, |:grepadd|, |:lgrepadd|, |:vimgrep|, |:lvimgrep|, - |:vimgrepadd|, |:lvimgrepadd|, |:cscope|, + |:vimgrepadd|, |:lvimgrepadd|, |:cfile|, |:cgetfile|, |:caddfile|, |:lfile|, |:lgetfile|, |:laddfile|, |:helpgrep|, |:lhelpgrep|, |:cexpr|, |:cgetexpr|, @@ -820,8 +819,8 @@ QuickFixCmdPre Before a quickfix command is run (|:make|, QuickFixCmdPost Like QuickFixCmdPre, but after a quickfix command is run, before jumping to the first location. For |:cfile| and |:lfile| commands - it is run after error file is read and before - moving to the first error. + it is run after the error file is read and + before moving to the first error. See |QuickFixCmdPost-example|. *QuitPre* QuitPre When using `:quit`, `:wq` or `:qall`, before @@ -833,13 +832,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 @@ -993,6 +992,10 @@ TextChangedP After a change was made to the text in the current buffer in Insert mode, only when the popup menu is visible. Otherwise the same as TextChanged. + *TextChangedT* +TextChangedT After a change was made to the text in the + current buffer in |Terminal-mode|. Otherwise + the same as TextChanged. *TextYankPost* TextYankPost Just after a |yank| or |deleting| command, but not if the black hole register |quote_| is used nor @@ -1058,8 +1061,9 @@ VimResume After Nvim resumes from |suspend| state. *VimSuspend* VimSuspend Before Nvim enters |suspend| state. *WinClosed* -WinClosed After closing a window. The pattern is - matched against the |window-ID|. Both +WinClosed When closing a window, just before it is + removed from the window layout. The pattern + is matched against the |window-ID|. Both <amatch> and <afile> are set to the |window-ID|. After WinLeave. Non-recursive (event cannot trigger itself). @@ -1088,23 +1092,48 @@ WinNew When a new window was created. Not done for Before WinEnter. *WinScrolled* -WinScrolled After scrolling the content of a window or - resizing a window. - The pattern is matched against the - |window-ID|. Both <amatch> and <afile> are - set to the |window-ID|. - Non-recursive (the event cannot trigger - itself). However, if the command causes the - window to scroll or change size another +WinScrolled After any window in the current tab page + scrolled the text (horizontally or vertically) + or changed width or height. See + |win-scrolled-resized|. + + The pattern is matched against the |window-ID| + of the first window that scrolled or resized. + Both <amatch> and <afile> are set to the + |window-ID|. + + |v:event| is set with information about size + and scroll changes. |WinScrolled-event| + + Only starts triggering after startup finished + and the first screen redraw was done. + Does not trigger when defining the first + WinScrolled or WinResized event, but may + trigger when adding more. + + Non-recursive: the event will not trigger + while executing commands for the WinScrolled + event. However, if the command causes a + window to scroll or change size, then another WinScrolled event will be triggered later. - Does not trigger when the command is added, - only after the first scroll or resize. + + + *WinResized* +WinResized After a window in the current tab page changed + width or height. + See |win-scrolled-resized|. + + |v:event| is set with information about size + changes. |WinResized-event| + + Same behavior as |WinScrolled| for the + pattern, triggering and recursiveness. ============================================================================== 6. Patterns *autocmd-pattern* *{aupat}* -The {aupat} argument of `:autocmd` can be a comma-separated list. This works -as if the command was given with each pattern separately. Thus this command: > +The {aupat} argument of `:autocmd` can be a comma-separated list. This works as +if the command was given with each pattern separately. Thus this command: > :autocmd BufRead *.txt,*.info set et Is equivalent to: > :autocmd BufRead *.txt set et @@ -1204,7 +1233,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..4d2c85b134 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -4,11 +4,11 @@ VIM REFERENCE MANUAL by Bram Moolenaar -Builtin functions *builtin-functions* +Builtin functions *vimscript-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* @@ -68,8 +68,8 @@ bufnr([{expr} [, {create}]]) Number Number of the buffer {expr} bufwinid({expr}) Number |window-ID| of buffer {expr} bufwinnr({expr}) Number window number of buffer {expr} byte2line({byte}) Number line number at byte count {byte} -byteidx({expr}, {nr}) Number byte index of {nr}'th char in {expr} -byteidxcomp({expr}, {nr}) Number byte index of {nr}'th char in {expr} +byteidx({expr}, {nr}) Number byte index of {nr}th char in {expr} +byteidxcomp({expr}, {nr}) Number byte index of {nr}th char in {expr} call({func}, {arglist} [, {dict}]) any call {func} with arguments {arglist} ceil({expr}) Float round {expr} up @@ -78,13 +78,13 @@ chanclose({id} [, {stream}]) Number Closes a channel or one of its streams chansend({id}, {data}) Number Writes {data} to channel char2nr({expr} [, {utf8}]) Number ASCII/UTF-8 value of first char in {expr} charclass({string}) Number character class of {string} -charcol({expr}) Number column number of cursor or mark +charcol({expr} [, {winid}]) Number column number of cursor or mark charidx({string}, {idx} [, {countcc}]) Number char index of byte {idx} in {string} chdir({dir}) String change current working directory cindent({lnum}) Number C indent for line {lnum} clearmatches([{win}]) none clear all matches -col({expr}) Number column byte index of cursor or mark +col({expr} [, {winid}]) Number column byte index of cursor or mark complete({startcol}, {matches}) none set Insert mode completion complete_add({expr}) Number add completion match complete_check() Number check for key typed during completion @@ -96,8 +96,6 @@ cos({expr}) Float cosine of {expr} cosh({expr}) Float hyperbolic cosine of {expr} count({comp}, {expr} [, {ic} [, {start}]]) Number count how many {expr} are in {comp} -cscope_connection([{num}, {dbpath} [, {prepend}]]) - Number checks existence of cscope connection ctxget([{index}]) Dict return the |context| dict at {index} ctxpop() none pop and restore |context| from the |context-stack| @@ -136,7 +134,8 @@ exists({expr}) Number |TRUE| if {expr} exists exp({expr}) Float exponential of {expr} expand({expr} [, {nosuf} [, {list}]]) any expand special keywords in {expr} -expandcmd({expr}) String expand {expr} like with `:edit` +expandcmd({string} [, {options}]) + String expand {string} like with `:edit` extend({expr1}, {expr2} [, {expr3}]) List/Dict insert items of {expr2} into {expr1} feedkeys({string} [, {mode}]) Number add key sequence to typeahead buffer @@ -171,8 +170,10 @@ get({func}, {what}) any get property of funcref/partial {func} getbufinfo([{buf}]) List information about buffers getbufline({buf}, {lnum} [, {end}]) List lines {lnum} to {end} of buffer {buf} +getbufoneline({buf}, {lnum}) String line {lnum} of buffer {buf} getbufvar({buf}, {varname} [, {def}]) any variable {varname} in buffer {buf} +getcellwidths() List get character cell width overrides getchangelist([{buf}]) List list of change list items getchar([expr]) Number or String get one character from the user @@ -222,6 +223,7 @@ gettabvar({nr}, {varname} [, {def}]) gettabwinvar({tabnr}, {winnr}, {name} [, {def}]) any {name} in {winnr} in tab page {tabnr} gettagstack([{nr}]) Dict get the tag stack of window {nr} +gettext({text}) String lookup translation of {text} getwininfo([{winid}]) List list of info about each window getwinpos([{timeout}]) List X and Y coord in pixels of the Vim window getwinposx() Number X coord in pixels of Vim window @@ -279,6 +281,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 @@ -315,9 +319,9 @@ matchfuzzypos({list}, {str} [, {dict}]) matchlist({expr}, {pat} [, {start} [, {count}]]) List match and submatches of {pat} in {expr} matchstr({expr}, {pat} [, {start} [, {count}]]) - String {count}'th match of {pat} in {expr} + String {count}th match of {pat} in {expr} matchstrpos({expr}, {pat} [, {start} [, {count}]]) - List {count}'th match of {pat} in {expr} + List {count}th match of {pat} in {expr} max({expr}) Number maximum value of items in {expr} menu_get({path} [, {modes}]) List description of |menus| matched by {path} menu_info({name} [, {mode}]) Dict get menu item information @@ -348,6 +352,7 @@ pyxeval({expr}) any evaluate |python_x| expression rand([{expr}]) Number get pseudo-random number range({expr} [, {max} [, {stride}]]) List items from {expr} to {max} +readblob({fname}) Blob read a |Blob| from {fname} readdir({dir} [, {expr}]) List file names in {dir} selected by {expr} readfile({fname} [, {type} [, {max}]]) List get list of lines from file {fname} @@ -400,6 +405,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 @@ -463,10 +469,11 @@ str2list({expr} [, {utf8}]) List convert each character of {expr} to ASCII/UTF-8 value str2nr({expr} [, {base} [, {quoted}]]) Number convert String to Number +strcharlen({expr}) Number character length of the String {expr} strcharpart({str}, {start} [, {len}]) String {len} characters of {str} at character {start} -strchars({expr} [, {skipcc}]) Number character length of the String {expr} +strchars({expr} [, {skipcc}]) Number character count of the String {expr} strdisplaywidth({expr} [, {col}]) Number display length of the String {expr} strftime({format} [, {time}]) String format time with a specified format strgetchar({str}, {index}) Number get char {index} from {str} @@ -527,6 +534,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 @@ -631,6 +640,7 @@ append({lnum}, {text}) *append()* text line below line {lnum} in the current buffer. Otherwise append {text} as one text line below line {lnum} in the current buffer. + Any type of item is accepted and converted to a String. {lnum} can be zero to insert a line before the first one. {lnum} is used like with |getline()|. Returns 1 for failure ({lnum} out of range or out of memory), @@ -649,9 +659,10 @@ appendbufline({buf}, {lnum}, {text}) *appendbufline()* For the use of {buf}, see |bufname()|. - {lnum} is used like with |append()|. Note that using |line()| - would use the current buffer, not the one appending to. - Use "$" to append at the end of the buffer. + {lnum} is the line number to append below. Note that using + |line()| would use the current buffer, not the one appending + to. Use "$" to append at the end of the buffer. Other string + values are not supported. On success 0 is returned, on failure 1 is returned. @@ -784,7 +795,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 +847,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()|. @@ -910,7 +923,8 @@ bufwinid({buf}) *bufwinid()* echo "A window containing buffer 1 is " .. (bufwinid(1)) < - Only deals with the current tab page. + Only deals with the current tab page. See |win_findbuf()| for + finding more. Can also be used as a |method|: > FindBuffer()->bufwinid() @@ -943,7 +957,7 @@ byte2line({byte}) *byte2line()* GetOffset()->byte2line() byteidx({expr}, {nr}) *byteidx()* - Return byte index of the {nr}'th character in the String + Return byte index of the {nr}th character in the String {expr}. Use zero for the first character, it then returns zero. If there are no multibyte characters the returned value is @@ -1027,7 +1041,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 @@ -1078,8 +1092,8 @@ charclass({string}) *charclass()* Returns 0 if {string} is not a |String|. - *charcol()* -charcol({expr}) Same as |col()| but returns the character index of the column +charcol({expr} [, {winid}]) *charcol()* + Same as |col()| but returns the character index of the column position given with {expr} instead of the byte position. Example: @@ -1126,16 +1140,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 @@ -1157,8 +1175,8 @@ clearmatches([{win}]) *clearmatches()* Can also be used as a |method|: > GetWin()->clearmatches() < - *col()* -col({expr}) The result is a Number, which is the byte index of the column +col({expr} [, {winid}) *col()* + The result is a Number, which is the byte index of the column position given with {expr}. The accepted positions are: . the cursor position $ the end of the cursor line (the result is the @@ -1173,6 +1191,8 @@ col({expr}) The result is a Number, which is the byte index of the column and column number. Most useful when the column is "$", to get the last column of a specific line. When "lnum" or "col" is out of range then col() returns zero. + With the optional {winid} argument the values are obtained for + that window instead of the current window. To get the line number use |line()|. To get both use |getpos()|. For the screen column position use |virtcol()|. For the @@ -1183,16 +1203,15 @@ col({expr}) The result is a Number, which is the byte index of the column col("$") length of cursor line plus one col("'t") column of mark t col("'" .. markname) column of mark markname -< The first column is 1. Returns 0 if {expr} is invalid. +< The first column is 1. Returns 0 if {expr} is invalid or when + the window with ID {winid} is not found. For an uppercase mark the column may actually be in another buffer. For the cursor position, when 'virtualedit' is active, the column is one higher if the cursor is after the end of the - line. This can be used to obtain the column in Insert mode: > - :imap <F2> <C-O>:let save_ve = &ve<CR> - \<C-O>:set ve=all<CR> - \<C-O>:echo col(".") .. "\n" <Bar> - \let &ve = save_ve<CR> + line. Also, when using a <Cmd> mapping the cursor isn't + moved, this can be used to obtain the column in Insert mode: > + :imap <F2> <Cmd>echo col(".").."\n"<CR> < Can also be used as a |method|: > GetPos()->col() @@ -1270,7 +1289,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: @@ -1425,47 +1444,6 @@ count({comp}, {expr} [, {ic} [, {start}]]) *count()* Can also be used as a |method|: > mylist->count(val) < - *cscope_connection()* -cscope_connection([{num} , {dbpath} [, {prepend}]]) - Checks for the existence of a |cscope| connection. If no - parameters are specified, then the function returns: - 0, if there are no cscope connections; - 1, if there is at least one cscope connection. - - If parameters are specified, then the value of {num} - determines how existence of a cscope connection is checked: - - {num} Description of existence check - ----- ------------------------------ - 0 Same as no parameters (e.g., "cscope_connection()"). - 1 Ignore {prepend}, and use partial string matches for - {dbpath}. - 2 Ignore {prepend}, and use exact string matches for - {dbpath}. - 3 Use {prepend}, use partial string matches for both - {dbpath} and {prepend}. - 4 Use {prepend}, use exact string matches for both - {dbpath} and {prepend}. - - Note: All string comparisons are case sensitive! - - Examples. Suppose we had the following (from ":cs show"): > - - # pid database name prepend path - 0 27664 cscope.out /usr/local -< - Invocation Return Val ~ - ---------- ---------- > - cscope_connection() 1 - cscope_connection(1, "out") 1 - cscope_connection(2, "out") 0 - cscope_connection(3, "out") 0 - cscope_connection(3, "out", "local") 1 - cscope_connection(4, "out") 0 - cscope_connection(4, "out", "local") 0 - cscope_connection(4, "cscope.out", "/usr/local") 1 -< - ctxget([{index}]) *ctxget()* Returns a |Dictionary| representing the |context| at {index} from the top of the |context-stack| (see |context-dict|). @@ -1508,9 +1486,10 @@ cursor({list}) |setcursorcharpos()|. Does not change the jumplist. + {lnum} is used like with |getline()|, except that if {lnum} is + zero, the cursor will stay in the current line. If {lnum} is greater than the number of lines in the buffer, the cursor will be positioned at the last line in the buffer. - If {lnum} is zero, the cursor will stay in the current line. If {col} is greater than the number of bytes in the line, the cursor will be positioned at the last character in the line. @@ -1526,6 +1505,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. @@ -1607,9 +1598,9 @@ dictwatcheradd({dict}, {pattern}, {callback}) *dictwatcheradd()* call dictwatcheradd(g:, '*', 'OnDictChanged') < For now {pattern} only accepts very simple patterns that can - contain a '*' at the end of the string, in which case it will - match every key that begins with the substring before the '*'. - That means if '*' is not the last character of {pattern}, only + contain a "*" at the end of the string, in which case it will + match every key that begins with the substring before the "*". + That means if "*" is not the last character of {pattern}, only keys that are exactly equal as {pattern} will be matched. The {callback} receives three arguments: @@ -1967,18 +1958,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 +1989,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 +2024,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. @@ -2068,18 +2052,27 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* Can also be used as a |method|: > Getpattern()->expand() -expandcmd({string}) *expandcmd()* +expandcmd({string} [, {options}]) *expandcmd()* Expand special items in String {string} like what is done for an Ex command such as `:edit`. This expands special keywords, like with |expand()|, and environment variables, anywhere in {string}. "~user" and "~/path" are only expanded at the start. + + The following items are supported in the {options} Dict + argument: + errmsg If set to TRUE, error messages are displayed + if an error is encountered during expansion. + By default, error messages are not displayed. + Returns the expanded string. If an error is encountered during expansion, the unmodified {string} is returned. + Example: > :echo expandcmd('make %<.o') -< make /path/runtime/doc/builtin.o ~ - + make /path/runtime/doc/builtin.o + :echo expandcmd('make %<.o', {'errmsg': v:true}) +< Can also be used as a |method|: > GetCommand()->expandcmd() < @@ -2305,7 +2298,7 @@ flatten({list} [, {maxdepth}]) *flatten()* float2nr({expr}) *float2nr()* Convert {expr} to a Number by omitting the part after the decimal point. - {expr} must evaluate to a |Float| or a Number. + {expr} must evaluate to a |Float| or a |Number|. Returns 0 if {expr} is not a |Float| or a |Number|. When the value of {expr} is out of range for a |Number| the result is truncated to 0x7fffffff or -0x7fffffff (or when @@ -2496,10 +2489,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 +2512,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 +2607,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: @@ -2667,11 +2687,13 @@ getbufinfo([{dict}]) Can also be used as a |method|: > GetBufnr()->getbufinfo() < + *getbufline()* getbufline({buf}, {lnum} [, {end}]) Return a |List| with the lines starting from {lnum} to {end} (inclusive) in the buffer {buf}. If {end} is omitted, a - |List| with only the line {lnum} is returned. + |List| with only the line {lnum} is returned. See + `getbufoneline()` for only getting the line. For the use of {buf}, see |bufname()| above. @@ -2694,6 +2716,11 @@ getbufline({buf}, {lnum} [, {end}]) < Can also be used as a |method|: > GetBufnr()->getbufline(lnum) +< + *getbufoneline()* +getbufoneline({buf}, {lnum}) + Just like `getbufline()` but only get one line and return it + as a string. getbufvar({buf}, {varname} [, {def}]) *getbufvar()* The result is the value of option or local buffer variable @@ -2719,6 +2746,13 @@ getbufvar({buf}, {varname} [, {def}]) *getbufvar()* < Can also be used as a |method|: > GetBufnr()->getbufvar(varname) < +getcellwidths() *getcellwidths()* + Returns a |List| of cell widths of character ranges overridden + by |setcellwidths()|. The format is equal to the argument of + |setcellwidths()|. If no character ranges have their cell + widths overridden, an empty List is returned. + + getchangelist([{buf}]) *getchangelist()* Returns the |changelist| for the buffer {buf}. For the use of {buf}, see |bufname()| above. If buffer {buf} doesn't @@ -2870,7 +2904,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 +2914,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 +2925,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 +2935,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 @@ -2928,12 +2966,12 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* arglist file names in argument list augroup autocmd groups buffer buffer names - behave :behave suboptions + behave |:behave| suboptions + breakpoint |:breakadd| and |:breakdel| suboptions cmdline |cmdline-completion| result color color schemes command Ex command compiler compilers - cscope |:cscope| suboptions diff_buffer |:diffget| and |:diffput| completion dir directory names environment environment variable names @@ -2945,7 +2983,7 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* function function name help help subjects highlight highlight groups - history :history suboptions + history |:history| suboptions locale locale names (as output of locale -a) mapclear buffer argument mapping mapping name @@ -2953,6 +2991,7 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* messages |:messages| suboptions option options packadd optional package |pack-add| names + scriptnames sourced script names |:scriptnames| shellcmd Shell command sign |:sign| suboptions syntax syntax file names |'syntax'| @@ -2970,6 +3009,13 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* is applied to filter the results. Otherwise all the matches are returned. The 'wildignorecase' option always applies. + If the 'wildoptions' option contains "fuzzy", then fuzzy + matching is used to get the completion matches. Otherwise + regular expression matching is used. Thus this function + follows the user preference, what happens on the command line. + If you do not want this you can make 'wildoptions' empty + before calling getcompletion() and restore it afterwards. + If {type} is "cmdline", then the |cmdline-completion| result is returned. For example, to complete the possible values after a ":call" command: > @@ -2990,7 +3036,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 @@ -3178,7 +3224,8 @@ getline({lnum} [, {end}]) < Can also be used as a |method|: > ComputeLnum()->getline() -< To get lines from another buffer see |getbufline()| +< To get lines from another buffer see |getbufline()| and + |getbufoneline()| getloclist({nr} [, {what}]) *getloclist()* Returns a |List| with all the entries in the location list for @@ -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 @@ -3580,6 +3627,19 @@ gettagstack([{winnr}]) *gettagstack()* Can also be used as a |method|: > GetWinnr()->gettagstack() + +gettext({text}) *gettext()* + Translate String {text} if possible. + This is mainly for use in the distributed Vim scripts. When + generating message translations the {text} is extracted by + xgettext, the translator can add the translated message in the + .po file and Vim will lookup the translation when gettext() is + called. + For {text} double quoted strings are preferred, because + xgettext does not understand escaping in single quoted + strings. + + getwininfo([{winid}]) *getwininfo()* Returns information about windows as a |List| with Dictionaries. @@ -3759,15 +3819,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 +4431,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 +4555,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 @@ -4903,7 +4973,7 @@ match({expr}, {pat} [, {start} [, {count}]]) *match()* If {start} is out of range ({start} > strlen({expr}) for a String or {start} > len({expr}) for a |List|) -1 is returned. - When {count} is given use the {count}'th match. When a match + When {count} is given use the {count}th match. When a match is found in a String the search for the next one starts one character further. Thus this example results in 1: > echo match("testing", "..", 0, 2) @@ -4955,7 +5025,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 +5033,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 +5083,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: > @@ -5135,7 +5203,7 @@ matchfuzzy({list}, {str} [, {dict}]) *matchfuzzy()* :let l = readfile("buffer.c")->matchfuzzy("str") < results in a list of lines in "buffer.c" fuzzy matching "str". > :echo ['one two', 'two one']->matchfuzzy('two one') -< results in ['two one', 'one two']. > +< results in `['two one', 'one two']` . > :echo ['one two', 'two one']->matchfuzzy('two one', \ {'matchseq': 1}) < results in ['two one']. @@ -5155,12 +5223,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 +5648,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. @@ -6005,9 +6080,19 @@ rand([{expr}]) *rand()* Can also be used as a |method|: > seed->rand() < + +readblob({fname}) *readblob()* + Read file {fname} in binary mode and return a |Blob|. + When the file can't be opened an error message is given and + the result is an empty |Blob|. + Also see |readfile()| and |writefile()|. + + *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: @@ -6037,6 +6122,7 @@ readdir({directory} [, {expr}]) Can also be used as a |method|: > GetDirName()->readdir() < + *readfile()* readfile({fname} [, {type} [, {max}]]) Read file {fname} and return a |List|, each line of the file @@ -6048,8 +6134,6 @@ readfile({fname} [, {type} [, {max}]]) - When the last line ends in a NL an extra empty list item is added. - No CR characters are removed. - When {type} contains "B" a |Blob| is returned with the binary - data of the file unmodified. Otherwise: - CR characters that appear before a NL are removed. - Whether the last line ends in a NL or not does not matter. @@ -6066,6 +6150,9 @@ readfile({fname} [, {type} [, {max}]]) Note that without {max} the whole file is read into memory. Also note that there is no recognition of encoding. Read a file into a buffer if you need to. + Deprecated (use |readblob()| instead): When {type} contains + "B" a |Blob| is returned with the binary data of the file + unmodified. When the file can't be opened an error message is given and the result is an empty list. Also see |writefile()|. @@ -6106,7 +6193,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 +6249,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 +6268,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 +6508,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 @@ -6607,7 +6700,7 @@ searchcount([{options}]) *searchcount()* pos |List| `[lnum, col, off]` value when recomputing the result. this changes "current" result - value. see |cursor()|, |getpos() + value. see |cursor()|, |getpos()| (default: cursor's position) Can also be used as a |method|: > @@ -6763,18 +6856,24 @@ serverstart([{address}]) *serverstart()* |RPC| messages. Clients can send |API| commands to the returned address to control Nvim. - Returns the address string (may differ from the requested - {address}). - - - If {address} contains a colon ":" it is interpreted as - a TCP/IPv4/IPv6 address where the last ":" separates host - and port (empty or zero assigns a random port). - - Else it is interpreted as a named pipe or Unix domain socket - path. If there are no slashes it is treated as a name and - appended to a generated path. - - If {address} is empty it generates a path. - - Example named pipe: > + Returns the address string (which may differ from the + {address} argument, see below). + + - If {address} has a colon (":") it is a TCP/IPv4/IPv6 address + where the last ":" separates host and port (empty or zero + assigns a random port). + - Else {address} is the path to a named pipe (except on Windows). + - If {address} has no slashes ("/") it is treated as the + "name" part of a generated path in this format: > + stdpath("run").."/{name}.{pid}.{counter}" +< - If {address} is omitted the name is "nvim". > + :echo serverstart() + => /tmp/nvim.bram/oknANW/nvim.15430.5 + +< Example bash command to list all Nvim servers: > + ls ${XDG_RUNTIME_DIR:-${TMPDIR}nvim.${USER}}/*/nvim.*.0 + +< Example named pipe: > if has('win32') echo serverstart('\\.\pipe\nvim-pipe-1234') else @@ -6839,29 +6938,38 @@ setbufvar({buf}, {varname}, {val}) *setbufvar()* setcellwidths({list}) *setcellwidths()* Specify overrides for cell widths of character ranges. This - tells Vim how wide characters are, counted in screen cells. - This overrides 'ambiwidth'. Example: > - setcellwidths([[0xad, 0xad, 1], - \ [0x2194, 0x2199, 2]]) - -< *E1109* *E1110* *E1111* *E1112* *E1113* *E1114* - The {list} argument is a list of lists with each three - numbers. These three numbers are [low, high, width]. "low" - and "high" can be the same, in which case this refers to one - character. Otherwise it is the range of characters from "low" - to "high" (inclusive). "width" is either 1 or 2, indicating - the character width in screen cells. + tells Vim how wide characters are when displayed in the + terminal, counted in screen cells. The values override + 'ambiwidth'. Example: > + call setcellwidths([ + \ [0x111, 0x111, 1], + \ [0x2194, 0x2199, 2], + \ ]) + +< The {list} argument is a List of Lists with each three + numbers: [{low}, {high}, {width}]. *E1109* *E1110* + {low} and {high} can be the same, in which case this refers to + one character. Otherwise it is the range of characters from + {low} to {high} (inclusive). *E1111* *E1114* + Only characters with value 0x80 and higher can be used. + + {width} must be either 1 or 2, indicating the character width + in screen cells. *E1112* An error is given if the argument is invalid, also when a - range overlaps with another. - Only characters with value 0x100 and higher can be used. + range overlaps with another. *E1113* If the new value causes 'fillchars' or 'listchars' to become invalid it is rejected and an error is given. - To clear the overrides pass an empty list: > - setcellwidths([]); + To clear the overrides pass an empty {list}: > + call setcellwidths([]) + < You can use the script $VIMRUNTIME/tools/emoji_list.vim to see - the effect for known emoji characters. + the effect for known emoji characters. Move the cursor + through the text to check if the cell widths of your terminal + match with what Vim knows about each emoji. If it doesn't + look right you need to adjust the {list} argument. + setcharpos({expr}, {list}) *setcharpos()* Same as |setpos()| but uses the specified column number as the @@ -6900,6 +7008,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 +7030,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() @@ -6972,6 +7090,8 @@ setline({lnum}, {text}) *setline()* {lnum} is used like with |getline()|. When {lnum} is just below the last line the {text} will be added below the last line. + {text} can be any type or a List of any type, each item is + converted to a String. If this succeeds, FALSE is returned. If this fails (most likely because {lnum} is invalid) TRUE is returned. @@ -7014,8 +7134,8 @@ setloclist({nr}, {list} [, {action} [, {what}]]) *setloclist()* GetLoclist()->setloclist(winnr) setmatches({list} [, {win}]) *setmatches()* - Restores a list of matches saved by |getmatches() for the - current window|. Returns 0 if successful, otherwise -1. All + Restores a list of matches saved by |getmatches()| for the + current window. Returns 0 if successful, otherwise -1. All current matches are cleared before the list is restored. See example for |getmatches()|. If {win} is specified, use the window with this number or @@ -7150,7 +7270,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} @@ -7195,6 +7315,7 @@ setqflist({list} [, {action} [, {what}]]) *setqflist()* *setreg()* setreg({regname}, {value} [, {options}]) Set the register {regname} to {value}. + If {regname} is "" or "@", the unnamed register '"' is used. The {regname} argument is a string. {value} may be any value returned by |getreg()| or @@ -7642,7 +7763,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 +7818,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") @@ -7769,6 +7889,21 @@ str2nr({string} [, {base}]) *str2nr()* Can also be used as a |method|: > GetText()->str2nr() + +strcharlen({string}) *strcharlen()* + The result is a Number, which is the number of characters + in String {string}. Composing characters are ignored. + |strchars()| can count the number of characters, counting + composing characters separately. + + Returns 0 if {string} is empty or on error. + + Also see |strlen()|, |strdisplaywidth()| and |strwidth()|. + + Can also be used as a |method|: > + GetText()->strcharlen() + + strcharpart({src}, {start} [, {len}]) *strcharpart()* Like |strpart()| but using character index and length instead of byte index and length. Composing characters are counted @@ -7783,12 +7918,14 @@ strcharpart({src}, {start} [, {len}]) *strcharpart()* Can also be used as a |method|: > GetText()->strcharpart(5) + strchars({string} [, {skipcc}]) *strchars()* The result is a Number, which is the number of characters in String {string}. When {skipcc} is omitted or zero, composing characters are counted separately. When {skipcc} set to 1, Composing characters are ignored. + |strcharlen()| always does this. Returns zero on error. @@ -7883,7 +8020,7 @@ stridx({haystack}, {needle} [, {start}]) *stridx()* Can also be used as a |method|: > GetHaystack()->stridx(needle) - +< *string()* string({expr}) Return {expr} converted to a String. If {expr} is a Number, Float, String, Blob or a composition of them, then the result @@ -8027,7 +8164,7 @@ strwidth({string}) *strwidth()* submatch({nr} [, {list}]) *submatch()* *E935* Only for an expression in a |:substitute| command or substitute() function. - Returns the {nr}'th submatch of the matched text. When {nr} + Returns the {nr}th submatch of the matched text. When {nr} is 0 the whole matched text is returned. Note that a NL in the string can stand for a line break of a multi-line match or a NUL character in the text. @@ -8175,7 +8312,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" @@ -8191,6 +8328,7 @@ synIDattr({synID}, {what} [, {mode}]) *synIDattr()* "underdotted" "1" if dotted underlined "underdashed" "1" if dashed underlined "strikethrough" "1" if struckthrough + "altfont" "1" if alternative font "nocombine" "1" if nocombine Returns an empty string on error. @@ -8231,12 +8369,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 +8918,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 @@ -8833,7 +8991,12 @@ win_execute({id}, {command} [, {silent}]) *win_execute()* have unexpected side effects. Use |:noautocmd| if needed. Example: > call win_execute(winid, 'syntax enable') -< +< Doing the same with `setwinvar()` would not trigger + autocommands and not actually show syntax highlighting. + + When window {id} does not exist then no error is given and + an empty string is returned. + Can also be used as a |method|, the base is passed as the second argument: > GetCommand()->win_execute(winid) @@ -8914,6 +9077,7 @@ win_move_separator({nr}, {offset}) *win_move_separator()* FALSE otherwise. This will fail for the rightmost window and a full-width window, since it has no separator on the right. + Only works for the current tab page. *E1308* Can also be used as a |method|: > GetWinnr()->win_move_separator(offset) @@ -8928,6 +9092,7 @@ win_move_statusline({nr}, {offset}) *win_move_statusline()* movement may be smaller than specified (e.g., as a consequence of maintaining 'winminheight'). Returns TRUE if the window can be found and FALSE otherwise. + Only works for the current tab page. Can also be used as a |method|: > GetWinnr()->win_move_statusline(offset) @@ -9014,12 +9179,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 +9376,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..990ba3d8fd 100644 --- a/runtime/doc/change.txt +++ b/runtime/doc/change.txt @@ -204,7 +204,6 @@ gR Enter Virtual Replace mode: Each character you type *v_S* {Visual}["x]S Delete the highlighted lines [into register x] and start insert (for {Visual} see |Visual-mode|). - *v_R* {Visual}["x]R Currently just like {Visual}["x]S. In a next version it might work differently. @@ -441,13 +440,13 @@ steps to make a numbered list. SHIFTING LINES LEFT OR RIGHT *shift-left-right* *<* -<{motion} Shift {motion} lines one 'shiftwidth' leftwards. + <{motion} Shift {motion} lines one 'shiftwidth' leftwards. If the 'shiftwidth' option is set to zero, the amount of indent is calculated at the first non-blank character in the line. *<<* -<< Shift [count] lines one 'shiftwidth' leftwards. + << Shift [count] lines one 'shiftwidth' leftwards. *v_<* {Visual}[count]< Shift the highlighted lines [count] 'shiftwidth' @@ -1130,11 +1129,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..1c52b2d692 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: >vim let s:lines = [''] func! s:on_event(job_id, data, event) dict let eof = (a:data == ['']) @@ -106,7 +108,7 @@ callbacks. Data can be sent to the channel using the |chansend()| function. Here is a simple example, echoing some data through a cat-process: -> +>vim function! s:OnEvent(id, data, event) dict let str = join(a:data, "\n") echomsg str @@ -117,7 +119,7 @@ simple example, echoing some data through a cat-process: Here is a example of setting a buffer to the result of grep, but only after all data has been processed: -> +>vim function! s:OnEvent(id, data, event) dict call nvim_buf_set_lines(2, 0, -1, v:true, a:data) endfunction @@ -140,7 +142,7 @@ However, change of PTY size can be signaled to the slave using |jobresize()|. See also |terminal-emulator|. Terminal characteristics (termios) for |:terminal| and PTY channels are copied -from the host TTY, or if Nvim is |--headless| it uses default values: > +from the host TTY, or if Nvim is |--headless| it uses default values: >vim :echo system('nvim --headless +"te stty -a" +"sleep 1" +"1,/^$/print" +q') ============================================================================== @@ -161,7 +163,7 @@ used as a channel. See also |--embed|. Call |stdioopen()| during |startup| to open the stdio channel as |channel-id| 1. Nvim's stderr is always available as |v:stderr|, a write-only bytes channel. -Example: > +Example: >vim func! OnEvent(id, data, event) if a:data == [""] quit @@ -170,7 +172,7 @@ Example: > endfunc call stdioopen({'on_stdin': 'OnEvent'}) < -Put this in `uppercase.vim` and run: > +Put this in `uppercase.vim` and run: >bash nvim --headless --cmd "source uppercase.vim" ============================================================================== @@ -221,7 +223,7 @@ start of the line. Here is an example for Unix. It starts a shell in the background and prompts for the next shell command. Output from the shell is displayed above the -prompt. > +prompt. >vim " Function handling a line of text that has been typed. func TextEntered(text) diff --git a/runtime/doc/cmdline.txt b/runtime/doc/cmdline.txt index 29eff75bfa..b4923b0d70 100644 --- a/runtime/doc/cmdline.txt +++ b/runtime/doc/cmdline.txt @@ -524,7 +524,6 @@ that see the '"' as part of their argument: :cexpr (and the like) :cdo (and the like) :command - :cscope (and the like) :debug :display :echo (and the like) @@ -566,7 +565,6 @@ followed by another Vim command: :cdo :cfdo :command - :cscope :debug :eval :folddoopen @@ -575,7 +573,6 @@ followed by another Vim command: :global :help :helpgrep - :lcscope :ldo :lfdo :lhelpgrep @@ -586,7 +583,6 @@ followed by another Vim command: :python :registers :read ! - :scscope :sign :terminal :vglobal @@ -694,7 +690,9 @@ Line numbers may be specified with: *:range* *{address}* 'T position of mark T (uppercase); when the mark is in another file it cannot be used in a range /{pattern}[/] the next line where {pattern} matches *:/* + also see |:range-pattern| below ?{pattern}[?] the previous line where {pattern} matches *:?* + also see |:range-pattern| below \/ the next line where the previously used search pattern matches \? the previous line where the previously used search @@ -702,11 +700,49 @@ Line numbers may be specified with: *:range* *{address}* \& the next line where the previously used substitute pattern matches + *:range-offset* Each may be followed (several times) by '+' or '-' and an optional number. This number is added or subtracted from the preceding line number. If the number is omitted, 1 is used. If there is nothing before the '+' or '-' then the current line is used. - + *:range-closed-fold* +When a line number after the comma is in a closed fold it is adjusted to the +last line of the fold, thus the whole fold is included. + +When a number is added this is done after the adjustment to the last line of +the fold. This means these lines are additionally included in the range. For +example: > + :3,4+2print +On this text: + 1 one ~ + 2 two ~ + 3 three ~ + 4 four FOLDED ~ + 5 five FOLDED ~ + 6 six ~ + 7 seven ~ + 8 eight ~ +Where lines four and five are a closed fold, ends up printing lines 3 to 7. +The 7 comes from the "4" in the range, which is adjusted to the end of the +closed fold, which is 5, and then the offset 2 is added. + +An example for subtracting (which isn't very useful): > + :2,4-1print +On this text: + 1 one ~ + 2 two ~ + 3 three FOLDED~ + 4 four FOLDED ~ + 5 five FOLDED ~ + 6 six FOLDED ~ + 7 seven ~ + 8 eight ~ +Where lines three to six are a closed fold, ends up printing lines 2 to 6. +The 6 comes from the "4" in the range, which is adjusted to the end of the +closed fold, which is 6, and then 1 is subtracted, then this is still in the +closed fold and the last line of that fold is used, which is 6. + + *:range-pattern* The "/" and "?" after {pattern} are required to separate the pattern from anything that follows. @@ -762,9 +798,9 @@ always be swapped then. Count and Range *N:* -When giving a count before entering ":", this is translated into: +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 +917,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 +927,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..1bdd13ac0c 100644 --- a/runtime/doc/deprecated.txt +++ b/runtime/doc/deprecated.txt @@ -10,150 +10,144 @@ 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: >vim + 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.buf.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 - 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 +- *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. +- '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/dev_style.txt b/runtime/doc/dev_style.txt index 77253e7831..b96b01dbff 100644 --- a/runtime/doc/dev_style.txt +++ b/runtime/doc/dev_style.txt @@ -8,7 +8,7 @@ Nvim style guide *dev-style* This is style guide for developers working on Nvim's source code. -License: CC-By 3.0 http://creativecommons.org/licenses/by/3.0/ +License: CC-By 3.0 https://creativecommons.org/licenses/by/3.0/ Type |gO| to see the table of contents. @@ -38,7 +38,7 @@ All header files should have `#define` guards to prevent multiple inclusion. The format of the symbol name should be `NVIM_<DIRECTORY>_<FILE>_H`. In foo/bar.h: -> +>c #ifndef NVIM_FOO_BAR_H #define NVIM_FOO_BAR_H @@ -71,7 +71,7 @@ C99 allows you to declare variables anywhere in a function. Declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization -should be used instead of declaration and assignment, e.g. > +should be used instead of declaration and assignment, e.g. >c int i; i = f(); // BAD: initialization separate from declaration. @@ -110,7 +110,7 @@ Variable-length arrays can cause hard to detect stack overflows. Postincrement and Postdecrement ~ -Use postfix form (`i++`) in statements. > +Use postfix form (`i++`) in statements. >c for (int i = 0; i < 3; i++) { } int j = ++i; // OK: ++i is used as an expression. @@ -136,7 +136,7 @@ Use `const` pointers whenever possible. Avoid `const` on non-pointer parameter d before the "noun" (`int`). That said, while we encourage putting `const` first, we do not require it. - But be consistent with the code around you! > + But be consistent with the code around you! >c void foo(const char *p, int i); } @@ -176,21 +176,14 @@ Type unsigned signed Booleans ~ -Use `bool` to represent boolean values. > +Use `bool` to represent boolean values. >c int loaded = 1; // BAD: loaded should have type bool. -Variable declarations ~ - -Declare only one variable per line. > - - int i, j = 1 - - Conditions ~ -Don't use "yoda-conditions". Use at most one assignment per condition. > +Don't use "yoda-conditions". Use at most one assignment per condition. >c if (1 == x) { @@ -203,7 +196,7 @@ Function declarations ~ Every function must not have a separate declaration. -Function declarations are created by the gendeclarations.lua script. > +Function declarations are created by the gendeclarations.lua script. >c static void f(void); @@ -216,7 +209,7 @@ Function declarations are created by the gendeclarations.lua script. > General translation unit layout ~ The definitions of public functions precede the definitions of static -functions. > +functions. >c <HEADER> @@ -237,7 +230,7 @@ if .c file does not contain any static functions. Included file name consists of the .c file name without extension, preceded by the directory name relative to src/nvim. Name of the file containing static functions declarations ends with `.c.generated.h`, `*.h.generated.h` files -contain only non-static function declarations. > +contain only non-static function declarations. >c // src/nvim/foo.c file #include <stddef.h> @@ -281,7 +274,7 @@ comparisons, and structure alignment. `#pragma pack()` and `__declspec(align())`. - Use the `LL` or `ULL` suffixes as needed to create 64-bit constants. For - example: > + example: >c int64_t my_value = 0x123456789LL; uint64_t my_mask = 3ULL << 48; @@ -295,7 +288,7 @@ Use `sizeof(varname)` when you take the size of a particular variable. `sizeof(varname)` will update appropriately if someone changes the variable type either now or later. You may use `sizeof(type)` for code unrelated to any particular variable, such as code that manages an external or internal data -format where a variable of an appropriate C type is not convenient. > +format where a variable of an appropriate C type is not convenient. >c Struct data; memset(&data, 0, sizeof(data)); @@ -331,7 +324,7 @@ Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate -by deleting letters within a word. > +by deleting letters within a word. >c int price_count_reader; // No abbreviation. int num_errors; // "num" is a widespread convention. @@ -368,7 +361,7 @@ Typedef-ed structs and enums start with a capital letter and have a capital letter for each new word, with no underscores: `MyExcitingStruct`. Non-Typedef-ed structs and enums are all lowercase with underscores between -words: `struct my_exciting_struct` . > +words: `struct my_exciting_struct` . >c struct my_struct { ... @@ -383,7 +376,7 @@ instance: `my_exciting_local_variable`. Common Variable names ~ - For example: > + For example: >c string table_name; // OK: uses underscore. string tablename; // OK: all lowercase. @@ -393,7 +386,7 @@ instance: `my_exciting_local_variable`. Struct Variables ~ - Data members in structs should be named like regular variables. > + Data members in structs should be named like regular variables. >c struct url_table_properties { string name; @@ -413,7 +406,7 @@ Use a `k` followed by mixed case: `kDaysInAWeek`. All compile-time constants, whether they are declared locally or globally, follow a slightly different naming convention from other variables. Use a `k` -followed by words with uppercase first letters: > +followed by words with uppercase first letters: >c const int kDaysInAWeek = 7; @@ -423,7 +416,7 @@ Function names are all lowercase, with underscores between words. For instance: `my_exceptional_function()`. All functions in the same header file should have a common prefix. -In `os_unix.h`: > +In `os_unix.h`: >c void unix_open(const char *path); void unix_user_id(void); @@ -436,7 +429,7 @@ normal operation. Enumerator Names ~ -Enumerators should be named like constants: `kEnumName`. > +Enumerators should be named like constants: `kEnumName`. >c enum url_table_errors { kOK = 0, @@ -447,7 +440,7 @@ Enumerators should be named like constants: `kEnumName`. > Macro Names ~ -They're like this: `MY_MACRO_THAT_SCARES_CPP_DEVELOPERS`. > +They're like this: `MY_MACRO_THAT_SCARES_CPP_DEVELOPERS`. >c #define ROUND(x) ... #define PI_ROUNDED 5.0 @@ -468,7 +461,7 @@ Nvim uses Doxygen comments. Comment Style ~ -Use the `//`-style syntax only. > +Use the `//`-style syntax only. >c // This is a comment spanning // multiple lines @@ -496,7 +489,7 @@ Start each file with a description of its contents. mention in the `.c` that the documentation is in the `.h` file. Do not duplicate comments in both the `.h` and the `.c`. Duplicated - comments diverge. > + comments diverge. >c /// A brief description of this file. /// @@ -507,7 +500,7 @@ Start each file with a description of its contents. Struct Comments ~ Every struct definition should have accompanying comments that describes what -it is for and how it should be used. > +it is for and how it should be used. >c /// Window info stored with a buffer. /// @@ -529,7 +522,7 @@ it is for and how it should be used. > }; If the field comments are short, you can also put them next to the field. But -be consistent within one struct, and follow the necessary doxygen style. > +be consistent within one struct, and follow the necessary doxygen style. >c struct wininfo_S { WinInfo *wi_next; ///< Next entry or NULL for last entry. @@ -567,8 +560,7 @@ of a function describe operation. - If the function allocates memory that the caller must free. - Whether any of the arguments can be a null pointer. - If there are any performance implications of how a function is used. - - If the function is re-entrant. What are its synchronization assumptions? - > + - If the function is re-entrant. What are its synchronization assumptions? >c /// Brief description of the function. /// /// Detailed description. @@ -596,7 +588,7 @@ of a function describe operation. Note you should not just repeat the comments given with the function declaration, in the `.h` file or wherever. It's okay to recapitulate briefly what the function does, but the focus of the comments should be on - how it does it. > + how it does it. >c // Note that we don't use Doxygen comments here. Iterator *get_iterator(void *arg1, void *arg2) @@ -614,7 +606,7 @@ comments are required. Global Variables ~ All global variables should have a comment describing what they are and - what they are used for. For example: > + what they are used for. For example: >c /// The total number of tests cases that we run /// through in this regression test. @@ -630,7 +622,7 @@ interesting, or important parts of your code. Also, lines that are non-obvious should get a comment at the end of the line. These end-of-line comments should be separated from the code by 2 - spaces. Example: > + spaces. Example: >c // If we have enough memory, mmap the data portion too. mmap_budget = max<int64>(0, mmap_budget - index_->length()); @@ -643,7 +635,7 @@ interesting, or important parts of your code. function returns. If you have several comments on subsequent lines, it can often be more - readable to line them up: > + readable to line them up: >c do_something(); // Comment here so the comments line up. do_something_else_that_is_longer(); // Comment here so there are two spaces between @@ -659,7 +651,7 @@ interesting, or important parts of your code. When you pass in a null pointer, boolean, or literal integer values to functions, you should consider adding a comment about what they are, or make your code self-documenting by using constants. For example, compare: - > + >c bool success = calculate_something(interesting_value, 10, @@ -667,7 +659,7 @@ interesting, or important parts of your code. NULL); // What are these arguments?? < - versus: > + versus: >c bool success = calculate_something(interesting_value, 10, // Default base value. @@ -675,7 +667,7 @@ interesting, or important parts of your code. NULL); // No callback. < - Or alternatively, constants or self-describing variables: > + Or alternatively, constants or self-describing variables: >c const int kDefaultBaseValue = 10; const bool kFirstTimeCalling = false; @@ -690,7 +682,7 @@ interesting, or important parts of your code. Note that you should never describe the code itself. Assume that the person reading the code knows C better than you do, even though he or she - does not know what you are trying to do: > + does not know what you are trying to do: >c // Now go through the b array and make sure that if i occurs, // the next element is i+1. @@ -725,7 +717,7 @@ about the problem referenced by the `TODO`. The main purpose is to have a consistent `TODO` format that can be searched to find the person who can provide more details upon request. A `TODO` is not a commitment that the person referenced will fix the problem. Thus when you create a `TODO`, it is -almost always your name that is given. > +almost always your name that is given. >c // TODO(kl@gmail.com): Use a "*" here for concatenation operator. // TODO(Zeke): change this to use relations. @@ -789,72 +781,23 @@ example, `"\uFEFF"`, is the Unicode zero-width no-break space character, which would be invisible if included in the source as straight UTF-8. -Function Declarations and Definitions ~ - -Return type on the same line as function name, parameters on the same line if -they fit. - -Functions look like this: > - - ReturnType function_name(Type par_name1, Type par_name2) - { - do_something(); - ... - } - -If you have too much text to fit on one line: > - - ReturnType really_long_function_name(Type par_name1, Type par_name2, - Type par_name3) - { - do_something(); - ... - } - -or if you cannot fit even the first parameter (but only then): > - - ReturnType really_really_really_long_function_name( - Type par_name1, // 4 space indent - Type par_name2, - Type par_name3) - { - do_something(); // 2 space indent - ... - } - -Some points to note: - -- The open parenthesis is always on the same line as the function name. -- There is never a space between the function name and the open parenthesis. -- There is never a space between the parentheses and the parameters. -- The open curly brace is always on the next line. -- The close curly brace is always on the last line by itself. -- There should be a space between the close parenthesis and the open curly - brace. -- All parameters should be named, with identical names in the declaration and - implementation. -- All parameters should be aligned if possible. -- Default indentation is 2 spaces. -- Wrapped parameters have a 4 space indent. - - Function Calls ~ On one line if it fits; otherwise, wrap arguments at the parenthesis. -Function calls have the following format: > +Function calls have the following format: >c bool retval = do_something(argument1, argument2, argument3); If the arguments do not all fit on one line, they should be broken up onto multiple lines, with each subsequent line aligned with the first argument. Do -not add spaces after the open paren or before the close paren: > +not add spaces after the open paren or before the close paren: >c bool retval = do_something(averyveryveryverylongargument1, argument2, argument3); If the function has many arguments, consider having one per line if this makes -the code more readable: > +the code more readable: >c bool retval = do_something(argument1, argument2, @@ -862,7 +805,7 @@ the code more readable: > argument4); Arguments may optionally all be placed on subsequent lines, with one line per -argument: > +argument: >c if (...) { ... @@ -886,7 +829,7 @@ place but with one space after the `{` and one space before the `}` If the braced list follows a name (e.g. a type or variable name), format as if the `{}` were the parentheses of a function call with that name. If there is -no name, assume a zero-length name. > +no name, assume a zero-length name. >c struct my_struct m = { // Here, you could also break before {. superlongvariablename1, @@ -896,18 +839,6 @@ no name, assume a zero-length name. > interiorwrappinglist2 } }; -Conditionals ~ - -Don't use spaces inside parentheses. > - - if (condition) { // no spaces inside parentheses - ... // 2 space indent. - } else if (...) { // The else goes on the same line as the closing brace. - ... - } else { - ... - } - Loops and Switch Statements ~ Annotate non-trivial fall-through between cases. @@ -915,7 +846,7 @@ Annotate non-trivial fall-through between cases. If not conditional on an enumerated value, switch statements should always have a `default` case (in the case of an enumerated value, the compiler will warn you if any values are not handled). If the default case should never -execute, simply `assert`: > +execute, simply `assert`: >c switch (var) { case 0: @@ -928,45 +859,12 @@ execute, simply `assert`: > assert(false); } -Pointer Expressions ~ - -No spaces around period or arrow. Pointer operators do not have trailing -spaces. - -The following are examples of correctly-formatted pointer and reference -expressions: > - - x = *p; - p = &x; - x = r.y; - x = r->y; - -Note that: - - - There are no spaces around the period or arrow when accessing a member. - - Pointer operators have no space after the * or &. - -Boolean Expressions ~ - -When you have a boolean expression that is longer than the standard line -length, keep operators at the start of the line. > - - if (this_one_thing > this_other_thing - && a_third_thing == a_fourth_thing - && yet_another && last_one) { - ... - } - -Also note that you should always use the punctuation operators, such as `&&` -and `~`, rather than the word operators, such as `and` and `compl`. - - Return Values ~ Do not needlessly surround the `return` expression with parentheses. Use parentheses in `return expr`; only where you would use them in `x = -expr;`. > +expr;`. >c return result; return (some_long_condition && another_condition); @@ -980,12 +878,12 @@ Horizontal Whitespace ~ Use of horizontal whitespace depends on location. General ~ -> +>c int x[] = { 0 }; // Spaces inside braces for braced-init-list. < Variables ~ -> +>c int long_variable = 0; // Don't align assignments. int i = 1; @@ -1002,14 +900,12 @@ Use of horizontal whitespace depends on location. Operators ~ -> +>c x = 0; // Assignment operators always have spaces around // them. x = -5; // No spaces separating unary operators and their x++; // arguments. if (x && !y) - ... - i = (int)d; // No spaces after a cast operator. < Vertical Whitespace ~ diff --git a/runtime/doc/develop.txt b/runtime/doc/develop.txt index b31ac47bda..ff48ae3e26 100644 --- a/runtime/doc/develop.txt +++ b/runtime/doc/develop.txt @@ -28,11 +28,9 @@ The Neo bits of Nvim should make it a better Vim, without becoming a completely different editor. - In matters of taste, prefer Vim/Unix tradition. If there is no relevant Vim/Unix tradition, consider the "common case". -- A feature that people do not know about is a useless feature. Don't add - obscure features, or at least add hints in documentation that they exist. -- There is no limit to the features that can be added. Selecting new features - is based on (1) what users ask for, (2) how much effort it takes to - implement and (3) someone actually implementing it. +- There is no limit to the features that can be added. Select new features + based on (1) what users ask for, (2) how much effort it takes to implement + and (3) someone actually implementing it. - Backwards compatibility is a feature. The RPC API in particular should never break. @@ -48,7 +46,7 @@ NVIM IS... WELL DOCUMENTED *design-documented* NVIM IS... FAST AND SMALL *design-speed-size* -Keep Nvim small and fast. +Keep Nvim small and fast. This directly affects versatility and usability. - Computers are becoming faster and bigger each year. Vim can grow too, but no faster than computers are growing. Keep Vim usable on older systems. - Many users start Vim from a shell very often. Startup time must be short. @@ -57,7 +55,8 @@ Keep Nvim small and fast. - Don't forget that some people use Vim over a slow connection. Minimize the communication overhead. - Vim is a component among other components. Don't turn it into a massive - application, but have it work well together with other programs. + application, but have it work well together with other programs + ("composability"). NVIM IS... MAINTAINABLE *design-maintain* @@ -119,7 +118,7 @@ reflects whether Python support is working. *provider-reload* Sometimes a GUI or other application may want to force a provider to "reload". To reload a provider, undefine its "loaded" flag, then use -|:runtime| to reload it: > +|:runtime| to reload it: >vim :unlet g:loaded_clipboard_provider :runtime autoload/provider/clipboard.vim @@ -131,6 +130,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 +144,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 +183,8 @@ 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. + Code samples can be annotated as `vim` or `lua` Example: the help for |nvim_open_win()| is generated from a docstring defined in src/nvim/api/win_config.c like this: > @@ -172,7 +193,7 @@ in src/nvim/api/win_config.c like this: > /// ... /// /// Example (Lua): window-relative float - /// <pre> + /// <pre>lua /// vim.api.nvim_open_win(0, false, /// {relative='win', row=3, col=3, width=12, height=3}) /// </pre> @@ -201,7 +222,8 @@ 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. + Code samples can be annotated as `vim` or `lua` Example: the help for |vim.paste()| is generated from a docstring decorating vim.paste in runtime/lua/vim/_editor.lua like this: > @@ -210,7 +232,7 @@ vim.paste in runtime/lua/vim/_editor.lua like this: > --- (such as the |TUI|) pastes text into the editor. --- --- Example: To remove ANSI color codes when pasting: - --- <pre> + --- <pre>lua --- vim.paste = (function() --- local overridden = vim.paste --- ... @@ -227,14 +249,27 @@ vim.paste in runtime/lua/vim/_editor.lua like this: > LUA *dev-lua* - Keep the core Lua modules |lua-stdlib| simple. Avoid elaborate OOP or - pseudo-OOP designs. Plugin authors just want functions to call, they don't - want to learn a big, fancy inheritance hierarchy. Thus avoid specialized - objects; tables or values are usually better. + pseudo-OOP designs. Plugin authors just want functions to call, not a big, + fancy inheritance hierarchy. +- Avoid requiring or returning special objects in the Nvim stdlib. Plain + tables or values are easier to serialize, easier to construct from literals, + easier to inspect and print, and inherently compatible with all Lua plugins. + (This guideline doesn't apply to opaque, non-data objects like `vim.cmd`.) API *dev-api* -Use this template to name new RPC |API| functions: +- Avoid "mutually exclusive" parameters--via constraints or limitations, if + necessary. For example nvim_create_autocmd() has mutually exclusive + "callback" and "command" args; but the "command" arg could be eliminated by + simply not supporting Vimscript function names, and treating a string + "callback" arg as an Ex command (which can call Vimscript functions). The + "buffer" arg could also be eliminated by treating a number "pattern" as + a buffer number. + + *dev-api-naming* +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 +278,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 +363,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 +432,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..7066a3739a 100644 --- a/runtime/doc/diagnostic.txt +++ b/runtime/doc/diagnostic.txt @@ -68,11 +68,11 @@ The "severity" key in a diagnostic is one of the values defined in Functions that take a severity as an optional parameter (e.g. |vim.diagnostic.get()|) accept one of two forms: -1. A single |vim.diagnostic.severity| value: > +1. A single |vim.diagnostic.severity| value: >lua vim.diagnostic.get(0, { severity = vim.diagnostic.severity.WARN }) -2. A table with a "min" or "max" key (or both): > +2. A table with a "min" or "max" key (or both): >lua vim.diagnostic.get(0, { severity = { min = vim.diagnostic.severity.WARN } }) @@ -107,7 +107,7 @@ Nvim provides these handlers by default: "virtual_text", "signs", and *diagnostic-handlers-example* The example below creates a new handler that notifies the user of diagnostics -with |vim.notify()|: > +with |vim.notify()|: >lua -- It's good practice to namespace custom handlers to avoid collisions vim.diagnostic.handlers["my/notify"] = { @@ -135,7 +135,7 @@ In this example, there is nothing to do when diagnostics are hidden, so we omit the "hide" function. Existing handlers can be overridden. For example, use the following to only -show a sign for the highest severity diagnostic on a given line: > +show a sign for the highest severity diagnostic on a given line: >lua -- Create a custom namespace. This will aggregate signs from all other -- namespaces and only show the one with the highest severity on a @@ -185,7 +185,7 @@ own default highlight groups. For example, the default highlighting for |hl-DiagnosticSignError| is linked to |hl-DiagnosticError|. To change the default (and therefore the linked -highlights), use the |:highlight| command: > +highlights), use the |:highlight| command: >vim highlight DiagnosticError guifg="BrightRed" < @@ -209,6 +209,11 @@ DiagnosticHint Used as the base highlight group. Other Diagnostic highlights link to this by default (except Underline) + *hl-DiagnosticOk* +DiagnosticOk + Used as the base highlight group. + Other Diagnostic highlights link to this by default (except Underline) + *hl-DiagnosticVirtualTextError* DiagnosticVirtualTextError Used for "Error" diagnostic virtual text. @@ -225,6 +230,10 @@ DiagnosticVirtualTextInfo DiagnosticVirtualTextHint Used for "Hint" diagnostic virtual text. + *hl-DiagnosticVirtualTextOk* +DiagnosticVirtualTextOk + Used for "Ok" diagnostic virtual text. + *hl-DiagnosticUnderlineError* DiagnosticUnderlineError Used to underline "Error" diagnostics. @@ -241,6 +250,10 @@ DiagnosticUnderlineInfo DiagnosticUnderlineHint Used to underline "Hint" diagnostics. + *hl-DiagnosticUnderlineOk* +DiagnosticUnderlineOk + Used to underline "Ok" diagnostics. + *hl-DiagnosticFloatingError* DiagnosticFloatingError Used to color "Error" diagnostic messages in diagnostics float. @@ -258,6 +271,10 @@ DiagnosticFloatingInfo DiagnosticFloatingHint Used to color "Hint" diagnostic messages in diagnostics float. + *hl-DiagnosticFloatingOk* +DiagnosticFloatingOk + Used to color "Ok" diagnostic messages in diagnostics float. + *hl-DiagnosticSignError* DiagnosticSignError Used for "Error" signs in sign column. @@ -274,12 +291,16 @@ DiagnosticSignInfo DiagnosticSignHint Used for "Hint" signs in sign column. + *hl-DiagnosticSignOk* +DiagnosticSignOk + Used for "Ok" signs in sign column. + ============================================================================== SIGNS *diagnostic-signs* Signs are defined for each diagnostic severity. The default text for each sign is the first letter of the severity name (for example, "E" for ERROR). Signs -can be customized using the following: > +can be customized using the following: >vim sign define DiagnosticSignError text=E texthl=DiagnosticSignError linehl= numhl= sign define DiagnosticSignWarn text=W texthl=DiagnosticSignWarn linehl= numhl= @@ -295,10 +316,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: >lua -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* @@ -312,12 +341,12 @@ config({opts}, {namespace}) *vim.diagnostic.config()* |vim.diagnostic.show()|). Ephemeral configuration has highest priority, followed by namespace configuration, and finally global configuration. - For example, if a user enables virtual text globally with > + For example, if a user enables virtual text globally with >lua vim.diagnostic.config({ virtual_text = true }) < - and a diagnostic producer sets diagnostics with > + and a diagnostic producer sets diagnostics with >lua vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) < @@ -334,7 +363,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 @@ -357,16 +386,21 @@ config({opts}, {namespace}) *vim.diagnostic.config()* the beginning of the virtual text. • prefix: (string) Prepend diagnostic message with prefix. + • suffix: (string or function) Append diagnostic + message with suffix. If a function, it must have the + signature (diagnostic) -> string, where {diagnostic} + is of type |diagnostic-structure|. This can be used + to render an LSP diagnostic error code. • format: (function) A function that takes a diagnostic as input and returns a string. The return value is - the text used to display the diagnostic. Example: > + the text used to display the diagnostic. Example: >lua - function(diagnostic) - if diagnostic.severity == vim.diagnostic.severity.ERROR then - return string.format("E: %s", diagnostic.message) + function(diagnostic) + if diagnostic.severity == vim.diagnostic.severity.ERROR then + return string.format("E: %s", diagnostic.message) + end + return diagnostic.message end - return diagnostic.message - end < • signs: (default true) Use signs for diagnostics. @@ -389,57 +423,57 @@ 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: ~ - array of diagnostics |diagnostic-structure| + Diagnostic [] array of |diagnostic-structure| 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. • severity: See |diagnostic-severity|. Return: ~ - (table) A list of diagnostic items |diagnostic-structure|. + Diagnostic [] table A list of diagnostic items |diagnostic-structure|. get_namespace({namespace}) *vim.diagnostic.get_namespace()* Get namespace metadata. Parameters: ~ - {namespace} (number) Diagnostic namespace + • {namespace} (number) Diagnostic namespace Return: ~ (table) Namespace metadata @@ -454,43 +488,45 @@ 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|nil) See |vim.diagnostic.goto_next()| Return: ~ - (table) Next diagnostic + Diagnostic|nil Next diagnostic get_next_pos({opts}) *vim.diagnostic.get_next_pos()* Return the position of the next diagnostic in the current buffer. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table|nil) See |vim.diagnostic.goto_next()| Return: ~ - (table) Next diagnostic position as a (row, col) tuple. + table|false Next diagnostic position as a (row, col) tuple or false if + no next diagnostic. get_prev({opts}) *vim.diagnostic.get_prev()* Get the previous diagnostic closest to the cursor position. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} nil|table See |vim.diagnostic.goto_next()| Return: ~ - (table) Previous diagnostic + Diagnostic|nil Previous diagnostic get_prev_pos({opts}) *vim.diagnostic.get_prev_pos()* Return the position of the previous diagnostic in the current buffer. Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + • {opts} (table|nil) See |vim.diagnostic.goto_next()| Return: ~ - (table) Previous diagnostic position as a (row, col) tuple. + table|false Previous diagnostic position as a (row, col) tuple or + false if there is no prior diagnostic goto_next({opts}) *vim.diagnostic.goto_next()* Move to the next diagnostic. Parameters: ~ - {opts} (table|nil) Configuration table with the following keys: + • {opts} (table|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 +547,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|nil) See |vim.diagnostic.goto_next()| hide({namespace}, {bufnr}) *vim.diagnostic.hide()* Hide currently displayed diagnostics. @@ -524,11 +560,23 @@ hide({namespace}, {bufnr}) *vim.diagnostic.hide()* |vim.diagnostic.disable()|. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, hide - diagnostics from all namespaces. - {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + • {namespace} (number|nil) Diagnostic namespace. When omitted, hide diagnostics from all + namespaces. + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. When omitted, hide diagnostics in all buffers. +is_disabled({bufnr}, {namespace}) *vim.diagnostic.is_disabled()* + Check whether diagnostics are disabled in a given buffer. + + Parameters: ~ + • {bufnr} (number|nil) Buffer number, or 0 for current buffer. + • {namespace} (number|nil) Diagnostic namespace. When omitted, checks if all diagnostics are + disabled in {bufnr}. Otherwise, only checks if + diagnostics from {namespace} are disabled. + + Return: ~ + (boolean) + *vim.diagnostic.match()* match({str}, {pat}, {groups}, {severity_map}, {defaults}) Parse a diagnostic from a string. @@ -538,34 +586,34 @@ match({str}, {pat}, {groups}, {severity_map}, {defaults}) WARNING filename:27:3: Variable 'foo' does not exist < - This can be parsed into a diagnostic |diagnostic-structure| with: > + This can be parsed into a diagnostic |diagnostic-structure| with: >lua - local s = "WARNING filename:27:3: Variable 'foo' does not exist" - local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" - local groups = { "severity", "lnum", "col", "message" } - vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) + local s = "WARNING filename:27:3: Variable 'foo' does not exist" + local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" + local groups = { "severity", "lnum", "col", "message" } + vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) < 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. Return: ~ - diagnostic |diagnostic-structure| or `nil` if {pat} fails to match - {str}. + Diagnostic|nil: |diagnostic-structure| or `nil` if {pat} fails to + match {str}. open_float({opts}, {...}) *vim.diagnostic.open_float()* Show diagnostics in a floating window. Parameters: ~ - {opts} (table|nil) Configuration table with the same keys as + • {opts} (table|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. @@ -610,9 +658,12 @@ open_float({opts}, {...}) *vim.diagnostic.open_float()* {prefix} is a string, it is prepended to each diagnostic in the window with no highlight. Overrides the setting from |vim.diagnostic.config()|. + • suffix: Same as {prefix}, but appends the text to the + diagnostic instead of prepending it. Overrides the setting + from |vim.diagnostic.config()|. Return: ~ - tuple ({float_bufnr}, {win_id}) + number|nil, number|nil: ({float_bufnr}, {win_id}) reset({namespace}, {bufnr}) *vim.diagnostic.reset()* Remove all diagnostics from the given namespace. @@ -623,27 +674,27 @@ reset({namespace}, {bufnr}) *vim.diagnostic.reset()* re-displayed, use |vim.diagnostic.hide()|. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, remove - diagnostics from all namespaces. - {bufnr} (number|nil) Remove diagnostics for the given buffer. + • {namespace} (number|nil) Diagnostic namespace. When omitted, remove diagnostics from all + namespaces. + • {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 +709,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 +723,17 @@ show({namespace}, {bufnr}, {diagnostics}, {opts}) Display diagnostics for the given namespace and buffer. Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When omitted, show - diagnostics from all namespaces. - {bufnr} (number|nil) Buffer number, or 0 for current buffer. + • {namespace} (number|nil) Diagnostic namespace. When omitted, show diagnostics from all + namespaces. + • {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,9 +741,9 @@ toqflist({diagnostics}) *vim.diagnostic.toqflist()* passed to |setqflist()| or |setloclist()|. Parameters: ~ - {diagnostics} (table) List of diagnostics |diagnostic-structure|. + • {diagnostics} (table) List of diagnostics |diagnostic-structure|. Return: ~ - array of quickfix list items |setqflist-what| + table[] of quickfix list items |setqflist-what| vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/diff.txt b/runtime/doc/diff.txt index 9c5792dd43..382d025d3c 100644 --- a/runtime/doc/diff.txt +++ b/runtime/doc/diff.txt @@ -137,6 +137,10 @@ Otherwise they are set to their default value: 'foldmethod' "manual" 'foldcolumn' 0 +'foldenable' will most-likely be reset to off. That is when 'foldmethod' is +restored to "manual". The folds themselves are not cleared but they should +not show up, resetting 'foldenable' is the best way to do that. + ============================================================================== 2. Viewing diffs *view-diffs* @@ -388,6 +392,11 @@ mode, so that a CTRL-Z doesn't end the text on DOS. The `redraw!` command may not be needed, depending on whether executing a shell command shows something on the display or not. +If the 'diffexpr' expression starts with s: or |<SID>|, then it is replaced +with the script ID (|local-function|). Example: > + set diffexpr=s:MyDiffExpr() + set diffexpr=<SID>SomeDiffExpr() +< *E810* *E97* Vim will do a test if the diff output looks alright. If it doesn't, you will get an error message. Possible causes: @@ -401,7 +410,7 @@ to see more messages. The self-installing Vim for MS-Windows includes a diff program. If you don't have it you might want to download a diff.exe. For example from -http://gnuwin32.sourceforge.net/packages/diffutils.htm. +https://gnuwin32.sourceforge.net/packages/diffutils.htm. USING PATCHES *diff-patchexpr* @@ -439,4 +448,9 @@ evaluating 'patchexpr'. This hopefully avoids that files in the current directory are accidentally patched. Vim will also delete files starting with v:fname_in and ending in ".rej" and ".orig". +If the 'patchexpr' expression starts with s: or |<SID>|, then it is replaced +with the script ID (|local-function|). Example: > + set patchexpr=s:MyPatchExpr() + set patchexpr=<SID>SomePatchExpr() +< vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/digraph.txt b/runtime/doc/digraph.txt index eb3de0111f..ce0a929bc1 100644 --- a/runtime/doc/digraph.txt +++ b/runtime/doc/digraph.txt @@ -156,7 +156,7 @@ These are the RFC1345 digraphs for the one-byte characters. See the output of ":digraphs" for the others. EURO - + *euro* *euro-digraph* Exception: RFC1345 doesn't specify the euro sign. In Vim the digraph =e was added for this. Note the difference between latin1, where the digraph Cu is used for the currency sign, and latin9 (iso-8859-15), where the digraph =e is diff --git a/runtime/doc/editing.txt b/runtime/doc/editing.txt index dcb0bf8a2e..f77db5fab3 100644 --- a/runtime/doc/editing.txt +++ b/runtime/doc/editing.txt @@ -345,9 +345,9 @@ escaped with a backslash. Wildcards in {file} are expanded, but as with file completion, 'wildignore' and 'suffixes' apply. Which wildcards are supported depends on the system. These are the common ones: - ? matches one character - * matches anything, including nothing - ** matches anything, including nothing, recurses into directories + `?` matches one character + `*` matches anything, including nothing + `**` matches anything, including nothing, recurses into directories [abc] match 'a', 'b' or 'c' To avoid the special meaning of the wildcards prepend a backslash. However, @@ -406,7 +406,7 @@ external command, by putting an equal sign right after the first backtick, e.g.: > :e `=tempname()` The expression can contain just about anything, thus this can also be used to -avoid the special meaning of '"', '|', '%' and '#'. However, 'wildignore' +avoid the special meaning of '"', "|", '%' and '#'. However, 'wildignore' does apply like to other wildcards. Environment variables in the expression are expanded when evaluating the @@ -423,9 +423,8 @@ Note that such expressions are only supported in places where a filename is expected as an argument to an Ex-command. *++opt* *[++opt]* -The [++opt] argument can be used to force the value of 'fileformat', -'fileencoding' or 'binary' to a value for one command, and to specify the -behavior for bad characters. The form is: > +The [++opt] argument can be used to set some options for one command, and to +specify the behavior for bad characters. The form is: > ++{optname} Or: > ++{optname}={value} @@ -436,11 +435,11 @@ Where {optname} is one of: *++ff* *++enc* *++bin* *++nobin* *++edit* bin or binary sets 'binary' nobin or nobinary resets 'binary' bad specifies behavior for bad characters - edit for |:read| only: keep option values as if editing - a file + edit for |:read|: keeps options as if editing a file + p for |:write|: creates the file's parent directory -{value} cannot contain white space. It can be any valid value for these -options. Examples: > +{value} cannot contain whitespace. It can be any valid value for the options. +Examples: > :e ++ff=unix This edits the same file again with 'fileformat' set to "unix". > @@ -450,9 +449,24 @@ This writes the current buffer to "newfile" in latin1 format. The message given when writing a file will show "[converted]" when 'fileencoding' or the value specified with ++enc differs from 'encoding'. -There may be several ++opt arguments, separated by white space. They must all +There may be several ++opt arguments, separated by whitespace. They must all appear before any |+cmd| argument. + *++p* +The "++p" flag creates the parent directory of the file if it does not exist. +For example if you edit "foo/bar/file.txt", the ":write ++p" command creates +"foo/bar/" if necessary before writing the file. > + + :edit foo/bar/file.txt + :write ++p + +If you want :write (without "++p") to always create missing parent +directories, add this autocmd to your config: > + + " Auto-create parent directories (except for URIs "://"). + au BufWritePre,FileWritePre * if @% !~# '\(://\)' | call mkdir(expand('<afile>:p:h'), 'p') | endif +< + *++bad* The argument of "++bad=" specifies what happens with characters that can't be converted and illegal bytes. It can be one of three things: @@ -545,6 +559,44 @@ Before editing binary, executable or Vim script files you should set the option. This will avoid the use of 'fileformat'. Without this you risk that single <NL> characters are unexpectedly replaced with <CR><NL>. +END OF LINE AND END OF FILE *eol-and-eof* + +Vim has several options to control the file format: + 'fileformat' the <EOL> style: Unix, DOS, Mac + 'endofline' whether the last line ends with a <EOL> + 'endoffile' whether the file ends with a CTRL-Z + 'fixendofline' whether to fix eol and eof + +The first three values are normally detected automatically when reading the +file and are used when writing the text to a file. While editing the buffer +it looks like every line has a line ending and the CTRL-Z isn't there (an +exception is when 'binary' is set, it works differently then). + +The 'fixendofline' option can be used to choose what to write. You can also +change the option values to write the file differently than how it was read. + +Here are some examples how to use them. + +If you want files in Unix format (every line NL terminated): > + setl ff=unix fixeol +You should probably do this on any Unix-like system. Also modern MS-Windows +systems tend to work well with this. It is recommended to always use this +format for Vim scripts. + +If you want to use an old MS-DOS file in a modern environment, fixing line +endings and dropping CTRL-Z, but keeping the <CR><NL> style <EOL>: > + setl ff=dos fixeol +This is useful for many MS-Windows programs, they regularly expect the +<CR><NL> line endings. + +If you want to drop the final <EOL> and add a final CTRL-Z (e.g. for an old +system like CP/M): > + setl ff=dos nofixeol noeol eof + +If you want to preserve the fileformat exactly as-is, including any final +<EOL> and final CTRL-Z: > + setl nofixeol + ============================================================================== 3. The argument list *argument-list* *arglist* @@ -842,7 +894,7 @@ changed. This is done for all *.c files. Example: > :args *.[ch] :argdo %s/\<my_foo\>/My_Foo/ge | update -This changes the word "my_foo" to "My_Foo" in all *.c and *.h files. The "e" +This changes the word "my_foo" to "My_Foo" in all "*.c" and "*.h" files. The "e" flag is used for the ":substitute" command to avoid an error for files where "my_foo" isn't used. ":update" writes the file only if changes were made. @@ -855,11 +907,13 @@ Note: When the 'write' option is off, you are not able to write any file. *E502* *E503* *E504* *E505* *E512* *E514* *E667* *E949* :w[rite] [++opt] Write the whole buffer to the current file. This is - the normal way to save changes to a file. It fails - when the 'readonly' option is set or when there is - another reason why the file can't be written. - For ++opt see |++opt|, but only ++bin, ++nobin, ++ff - and ++enc are effective. + the normal way to save changes to a file. Fails when + 'readonly' is set or when there is another reason why + the file can't be written, such as when the parent + directory doesn't exist (use |++p| to avoid that). + For ++opt see |++opt|, but only ++p, ++bin, ++nobin, + ++ff and ++enc are effective. + :w[rite]! [++opt] Like ":write", but forcefully write when 'readonly' is set or there is another reason why writing was @@ -941,7 +995,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', @@ -1222,8 +1276,8 @@ unmodified. For MS-Windows you can modify the filters that are used in the browse dialog. By setting the g:browsefilter or b:browsefilter variables, you can change the filters globally or locally to the buffer. The variable is set to -a string in the format "{filter label}\t{pattern};{pattern}\n" where {filter -label} is the text that appears in the "Files of Type" comboBox, and {pattern} +a string in the format "{filter label}\t{pattern};{pattern}\n" where "{filter +label}" is the text that appears in the "Files of Type" comboBox, and {pattern} is the pattern which filters the filenames. Several patterns can be given, separated by ';'. @@ -1271,6 +1325,7 @@ exist, the next-higher scope in the hierarchy applies. :cd[!] {path} Change the current directory to {path}. If {path} is relative, it is searched for in the directories listed in |'cdpath'|. + Clear any window-local directory. Does not change the meaning of an already opened file, because its full path name is remembered. Files from the |arglist| may change though! @@ -1481,8 +1536,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)? @@ -1521,8 +1576,8 @@ which is slightly different. There are three different types of searching: 1) Downward search: *starstar* - Downward search uses the wildcards '*', '**' and possibly others - supported by your operating system. '*' and '**' are handled inside Vim, + Downward search uses the wildcards "*", "**" and possibly others + supported by your operating system. "*" and "**" are handled inside Vim, so they work on all operating systems. Note that "**" only acts as a special wildcard when it is at the start of a name. @@ -1530,12 +1585,12 @@ There are three different types of searching: search pattern this would be ".*". Note that the "." is not used for file searching. - '**' is more sophisticated: + "**" is more sophisticated: - It ONLY matches directories. - It matches up to 30 directories deep by default, so you can use it to search an entire directory tree - The maximum number of levels matched can be given by appending a number - to '**'. + to "**". Thus '/usr/**2' can match: > /usr /usr/include @@ -1546,14 +1601,14 @@ There are three different types of searching: .... < It does NOT match '/usr/include/g++/std' as this would be three levels. - The allowed number range is 0 ('**0' is removed) to 100 + The allowed number range is 0 ("**0" is removed) to 100 If the given number is smaller than 0 it defaults to 30, if it's bigger than 100 then 100 is used. The system also has a limit on the path length, usually 256 or 1024 bytes. - - '**' can only be at the end of the path or be followed by a path + - "**" can only be at the end of the path or be followed by a path separator or by a number and a path separator. - You can combine '*' and '**' in any order: > + You can combine "*" and "**" in any order: > /usr/**/sys/* /usr/*tory/sys/** /usr/**2/sys/* @@ -1610,4 +1665,32 @@ There are three different types of searching: currently work with 'path' items that contain a URL or use the double star with depth limiter (/usr/**2) or upward search (;) notations. +============================================================================== +12. Trusted Files *trust* + +Nvim has the ability to execute arbitrary code through the 'exrc' option. In +order to prevent executing code from untrusted sources, Nvim has the concept of +"trusted files". An untrusted file will not be executed without the user's +consent, and a user can permanently mark a file as trusted or untrusted using +the |:trust| command or the |vim.secure.read()| function. + + *:trust* *E5570* +:trust [++deny] [++remove] [{file}] + + Manage files in the trust database. Without any options + or arguments, :trust adds the file associated with the + current buffer to the trust database, along with the + SHA256 hash of its contents. + + [++deny] marks the file associated with the current + buffer (or {file}, if given) as denied; no prompts will + be displayed to the user and the file will never be + executed. + + [++remove] removes the file associated with the current + buffer (or {file}, if given) from the trust database. + Future attempts to read the file in a secure setting + (i.e. with 'exrc' or |vim.secure.read()|) will prompt + the user if the file is trusted. + vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/editorconfig.txt b/runtime/doc/editorconfig.txt new file mode 100644 index 0000000000..04a057e5ff --- /dev/null +++ b/runtime/doc/editorconfig.txt @@ -0,0 +1,91 @@ +*editorconfig.txt* Nvim + + + NVIM REFERENCE MANUAL + + +EditorConfig integration *editorconfig* + +Nvim natively supports EditorConfig. When a file is opened, Nvim searches +upward through all of the parent directories of that file looking for +".editorconfig" files. Each of these is parsed and any properties that match +the opened file are applied. + +For more information on EditorConfig, see https://editorconfig.org/. + + *g:editorconfig* *b:editorconfig* +EditorConfig integration can be disabled globally by adding >lua + + vim.g.editorconfig = false +< +to the user's |init.lua| file (or the Vimscript equivalent to |init.vim|). It +can also be disabled per-buffer by setting the |b:editorconfig| buffer-local +variable to `false`. + +When Nvim finds a valid .editorconfig file it will store the applied +properties in the buffer variable |b:editorconfig| if it was not already set to +`false` by the user. + + *editorconfig-properties* +The following properties are supported by default: + + *editorconfig_root* +root If "true", then stop searching for .editorconfig files + in parent directories. This property must be at the + top-level of the .editorconfig file (i.e. it must not + be within a glob section). + + *editorconfig_charset* +charset One of "utf-8", "utf-8-bom", "latin1", "utf-16be", or + "utf-16le". Sets the 'fileencoding' and 'bomb' + options. + + *editorconfig_end_of_line* +end_of_line One of "lf", "crlf", or "cr". These correspond to + setting 'fileformat' to "unix", "dos", or "mac", + respectively. + + *editorconfig_indent_style* +indent_style One of "tab" or "space". Sets the 'expandtab' option. + + *editorconfig_indent_size* +indent_size A number indicating the size of a single indent. + Alternatively, use the value "tab" to use the value of + the tab_width property. Sets the 'shiftwidth' and + 'softtabstop'. + + *editorconfig_insert_final_newline* +insert_final_newline "true" or "false" to ensure the file always has a + trailing newline as its last byte. Sets the + 'fixendofline' and 'endofline' options. + + *editorconfig_max_line_length* +max_line_length A number indicating the maximum length of a single + line. Sets the 'textwidth' option. + + *editorconfig_tab_width* +tab_width The display size of a single tab character. Sets the + 'tabstop' option. + + *editorconfig_trim_trailing_whitespace* +trim_trailing_whitespace + When "true", trailing whitespace is automatically + removed when the buffer is written. + + *editorconfig-custom-properties* +New properties can be added by adding a new entry to the "properties" table. +The table key is a property name and the value is a callback function which +accepts the number of the buffer to be modified, the value of the property +in the .editorconfig file, and (optionally) a table containing all of the +other properties and their values (useful for properties which depend on other +properties). The value is always a string and must be coerced if necessary. +Example: >lua + + require('editorconfig').properties.foo = function(bufnr, val, opts) + if opts.charset and opts.charset ~= "utf-8" then + error("foo can only be set when charset is utf-8", 0) + end + vim.b[bufnr].foo = val + end +< + vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt index 376adfec7f..58759a6053 100644 --- a/runtime/doc/eval.txt +++ b/runtime/doc/eval.txt @@ -4,7 +4,7 @@ VIM REFERENCE MANUAL by Bram Moolenaar -Expression evaluation *expression* *expr* *E15* *eval* +Expression evaluation *vimscript* *expression* *expr* *E15* *eval* Using expressions is introduced in chapter 41 of the user manual |usr_41.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| @@ -229,13 +229,13 @@ is not available it returns zero or the default value you specify: > List concatenation ~ - + *list-concatenation* Two lists can be concatenated with the "+" operator: > :let longlist = mylist + [5, 6] :let mylist += [7, 8] -To prepend or append an item turn the item into a list by putting [] around -it. To change a list in-place see |list-modification| below. +To prepend or append an item, turn the item into a list by putting [] around +it. To change a list in-place, refer to |list-modification| below. Sublist ~ @@ -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()|. @@ -840,8 +840,8 @@ Example: > All expressions within one level are parsed from left to right. +------------------------------------------------------------------------------ expr1 *expr1* *ternary* *E109* ------ expr2 ? expr1 : expr1 @@ -867,8 +867,8 @@ You should always put a space before the ':', otherwise it can be mistaken for use in a variable such as "a:1". +------------------------------------------------------------------------------ expr2 and expr3 *expr2* *expr3* ---------------- expr3 || expr3 .. logical OR *expr-barbar* expr4 && expr4 .. logical AND *expr-&&* @@ -906,8 +906,8 @@ This is valid whether "b" has been defined or not. The second clause will only be evaluated if "b" has been defined. +------------------------------------------------------------------------------ expr4 *expr4* ------ expr5 {cmp} expr5 @@ -1010,8 +1010,9 @@ can be matched like an ordinary character. Examples: "foo\nbar" =~ "\\n" evaluates to 0 +------------------------------------------------------------------------------ expr5 and expr6 *expr5* *expr6* ---------------- + expr6 + expr6 Number addition, |List| or |Blob| concatenation *expr-+* expr6 - expr6 Number subtraction *expr--* expr6 . expr6 String concatenation *expr-.* @@ -1064,8 +1065,9 @@ None of these work for |Funcref|s. . and % do not work for Float. *E804* +------------------------------------------------------------------------------ expr7 *expr7* ------ + ! expr7 logical NOT *expr-!* - expr7 unary minus *expr-unary--* + expr7 unary plus *expr-unary-+* @@ -1082,8 +1084,9 @@ These three can be repeated and mixed. Examples: --9 == 9 +------------------------------------------------------------------------------ expr8 *expr8* ------ + This expression is either |expr9| or a sequence of the alternatives below, in any order. E.g., these are all possible: expr8[expr1].name @@ -1228,11 +1231,15 @@ And NOT: > \ ->map(mapexpr) \ ->sort() \ ->join() -< + +When using the lambda form there must be no white space between the } and the +(. + *expr9* +------------------------------------------------------------------------------ number ------- + number number constant *expr-number* *0x* *hex-number* *0o* *octal-number* *binary-number* @@ -1294,9 +1301,9 @@ function. Example: > < 7.853981633974483e-01 - +------------------------------------------------------------------------------ string *string* *String* *expr-string* *E114* ------- + "string" string constant *expr-quote* Note that double quotes are used. @@ -1335,16 +1342,17 @@ encodings. Use "\u00ff" to store character 255 correctly as UTF-8. Note that "\000" and "\x00" force the end of the string. +------------------------------------------------------------------------------ blob-literal *blob-literal* *E973* ------------- Hexadecimal starting with 0z or 0Z, with an arbitrary number of bytes. The sequence must be an even number of hex characters. Example: > :let b = 0zFF00ED015DAF +------------------------------------------------------------------------------ literal-string *literal-string* *E115* ---------------- + 'string' string constant *expr-'* Note that single quotes are used. @@ -1358,8 +1366,9 @@ to be doubled. These two commands are equivalent: > if a =~ '\s*' +------------------------------------------------------------------------------ option *expr-option* *E112* *E113* ------- + &option option value, local value if possible &g:option global option value &l:option local option value @@ -1373,8 +1382,9 @@ and there is no buffer-local or window-local value, the global value is used anyway. +------------------------------------------------------------------------------ register *expr-register* *@r* --------- + @r contents of register 'r' The result is the contents of the named register, as a single string. @@ -1391,8 +1401,9 @@ nesting *expr-nesting* *E110* (expr1) nested expression +------------------------------------------------------------------------------ environment variable *expr-env* --------------------- + $VAR environment variable The String value of any environment variable. When it is not defined, the @@ -1417,20 +1428,23 @@ The first one probably doesn't echo anything, the second echoes the $shell variable (if your shell supports it). +------------------------------------------------------------------------------ internal variable *expr-variable* ------------------ + variable internal variable See below |internal-variables|. +------------------------------------------------------------------------------ function call *expr-function* *E116* *E118* *E119* *E120* -------------- + function(expr1, ...) function call See below |functions|. +------------------------------------------------------------------------------ lambda expression *expr-lambda* *lambda* ------------------ + {args -> expr1} lambda expression A lambda expression creates a new unnamed function which returns the result of @@ -1521,7 +1535,7 @@ specified by what is prepended: |tabpage-variable| t: Local to the current tab page. |global-variable| g: Global. |local-variable| l: Local to a function. -|script-variable| s: Local to a |:source|'ed Vim script. +|script-variable| s: Local to a |:source|d Vim script. |function-argument| a: Function argument (only inside a function). |vim-variable| v: Global, predefined by Vim. @@ -1704,17 +1718,13 @@ v:charconvert_to Only valid while evaluating the 'charconvert' option. *v:cmdarg* *cmdarg-variable* -v:cmdarg This variable is used for two purposes: - 1. The extra arguments given to a file read/write command. - Currently these are "++enc=" and "++ff=". This variable is - set before an autocommand event for a file read/write - command is triggered. There is a leading space to make it - possible to append this variable directly after the - read/write command. Note: The "+cmd" argument isn't - included here, because it will be executed anyway. - 2. When printing a PostScript file with ":hardcopy" this is - the argument for the ":hardcopy" command. This can be used - in 'printexpr'. +v:cmdarg + The extra arguments ("++p", "++enc=", "++ff=") given to a file + read/write command. This is set before an autocommand event + for a file read/write command is triggered. There is a + leading space to make it possible to append this variable + directly after the read/write command. Note: "+cmd" isn't + included here, because it will be executed anyway. *v:collate* *collate-variable* v:collate The current locale setting for collation order of the runtime @@ -1777,7 +1787,7 @@ v:exiting Exit code, or |v:null| before invoking the |VimLeavePre| and |VimLeave| autocmds. See |:q|, |:x| and |:cquit|. Example: > :au VimLeave * echo "Exit value is " .. v:exiting - +< *v:echospace* *echospace-variable* v:echospace Number of screen cells that can be used for an `:echo` message in the last screen line before causing the |hit-enter-prompt|. @@ -1912,17 +1922,16 @@ v:fname_in The name of the input file. Valid while evaluating: 'charconvert' file to be converted 'diffexpr' original file 'patchexpr' original file - 'printexpr' file to be printed And set to the swap file name for |SwapExists|. *v:fname_out* *fname_out-variable* v:fname_out The name of the output file. Only valid while evaluating: option used for ~ - 'charconvert' resulting converted file (*) + 'charconvert' resulting converted file [1] 'diffexpr' output of diff 'patchexpr' resulting patched file - (*) When doing conversion for a write command (e.g., ":w + [1] When doing conversion for a write command (e.g., ":w file") it will be equal to v:fname_in. When doing conversion for a read command (e.g., ":e file") it will be a temporary file and different from v:fname_in. @@ -1992,10 +2001,10 @@ v:lc_time The current locale setting for time messages of the runtime command. See |multi-lang|. *v:lnum* *lnum-variable* -v:lnum Line number for the 'foldexpr' |fold-expr|, 'formatexpr' and - 'indentexpr' expressions, tab page number for 'guitablabel' - and 'guitabtooltip'. Only valid while one of these - expressions is being evaluated. Read-only when in the +v:lnum Line number for the 'foldexpr' |fold-expr|, 'formatexpr', + 'indentexpr' and 'statuscolumn' expressions, tab page number + for 'guitablabel' and 'guitabtooltip'. Only valid while one of + these expressions is being evaluated. Read-only when in the |sandbox|. *v:lua* *lua-variable* @@ -2129,6 +2138,10 @@ v:register The name of the register in effect for the current normal mode '*' or '+'. Also see |getreg()| and |setreg()| + *v:relnum* *relnum-variable* +v:relnum Relative line number for the 'statuscolumn' expression. + Read-only. + *v:scrollstart* *scrollstart-variable* v:scrollstart String describing the script or function that caused the screen to scroll up. It's only set when it is empty, thus the @@ -2138,9 +2151,11 @@ v:scrollstart String describing the script or function that caused the hit-enter prompt. *v:servername* *servername-variable* -v:servername Primary listen-address of the current Nvim instance, the first - item returned by |serverlist()|. Can be set by |--listen| or - |$NVIM_LISTEN_ADDRESS| (deprecated) at startup. +v:servername Primary listen-address of Nvim, the first item returned by + |serverlist()|. Usually this is the named pipe created by Nvim + at |startup| or given by |--listen| (or the deprecated + |$NVIM_LISTEN_ADDRESS| env var). + See also |serverstart()| |serverstop()|. Read-only. @@ -2280,6 +2295,13 @@ v:version Vim version number: major version times 100 plus minor :if has("nvim-0.2.1") < + *v:virtnum* *virtnum-variable* +v:virtnum Virtual line number for the 'statuscolumn' expression. + Negative when drawing the status column for virtual lines, zero + when drawing an actual buffer line, and positive when drawing + the wrapped part of a buffer line. + Read-only. + *v:vim_did_enter* *vim_did_enter-variable* v:vim_did_enter 0 during startup, 1 just before |VimEnter|. Read-only. @@ -2309,397 +2331,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: > +functions. The function takes arguments, executes a sequence of Ex commands +and can return a value. - :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. - -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 +2550,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 @@ -3046,6 +2681,8 @@ text... [depth] is relevant when locking a |List| or |Dictionary|. It specifies how deep the locking goes: + 0 Lock the variable {name} but not its + value. 1 Lock the |List| or |Dictionary| itself, cannot add or remove items, but can still change their values. @@ -3059,7 +2696,14 @@ text... |Dictionary|, one level deeper. The default [depth] is 2, thus when {name} is a |List| or |Dictionary| the values cannot be changed. - *E743* + + Example with [depth] 0: > + let mylist = [1, 2, 3] + lockvar 0 mylist + let mylist[0] = 77 " OK + call add(mylist, 4] " OK + let mylist = [7, 8, 9] " Error! +< *E743* For unlimited depth use [!] and omit [depth]. However, there is a maximum depth of 100 to catch loops. @@ -3080,6 +2724,8 @@ text... Unlock the internal variable {name}. Does the opposite of |:lockvar|. + No error is given if {name} does not exist. + :if {expr1} *:if* *:end* *:endif* *:en* *E171* *E579* *E580* :en[dif] Execute the commands until the next matching `:else` or `:endif` if {expr1} evaluates to non-zero. @@ -3167,6 +2813,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 @@ -3556,7 +3205,7 @@ this pending exception or command is discarded. For examples see |throw-catch| and |try-finally|. -NESTING OF TRY CONDITIONALS *try-nesting* +NESTING OF TRY CONDITIONALS *try-nesting* Try conditionals can be nested arbitrarily. That is, a complete try conditional can be put into the try block, a catch clause, or the finally @@ -4500,7 +4149,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..a53c287d48 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -148,6 +148,7 @@ variables can be used to overrule the filetype used for certain extensions: *.fs g:filetype_fs |ft-forth-syntax| *.i g:filetype_i |ft-progress-syntax| *.inc g:filetype_inc + *.lsl g:filetype_lsl *.m g:filetype_m |ft-mathematica-syntax| *.mod g:filetype_mod *.p g:filetype_p |ft-pascal-syntax| @@ -175,15 +176,13 @@ This means that the contents of compressed files are not inspected. *new-filetype* 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 -|vim.filetype.add()|. +to add it. The recommended way is to use |vim.filetype.add()| to add it to +Nvim's builtin filetype detection mechanism. If you want to handle the +detection manually, proceed as follows: A. If you want to overrule all default file type checks. This works by writing one file for each filetype. The disadvantage is that - there can be many files. The advantage is that you can simply drop this + there can be many files. The advantage is that you can simply drop this file in the right directory to make it work. *ftdetect* 1. Create your user runtime directory. You would normally use the first @@ -273,28 +272,14 @@ D. If your filetype can only be detected by inspecting the contents of the means that your rules override the default rules in $VIMRUNTIME/scripts.vim. - *remove-filetype* -If a file type is detected that is wrong for you, install a filetype.lua, -filetype.vim or scripts.vim to catch it (see above). You can set 'filetype' to -a non-existing name to avoid that it will be set later anyway: > - :set filetype=ignored - -If you are setting up a system with many users, and you don't want each user -to add/remove the same filetypes, consider writing the filetype.vim and -scripts.vim files in a runtime directory that is used for everybody. Check -the 'runtimepath' for a directory to use. If there isn't one, set -'runtimepath' in the |system-vimrc|. Be careful to keep the default -directories! - - *g:do_legacy_filetype* -To disable Nvim's default filetype detection and revert to Vim's legacy -filetype detection, add the following to your |init.vim|: > - let g:do_legacy_filetype = 1 -< *g:did_load_filetypes* + *remove-filetype* +If a file type is detected that is wrong for you, you can set 'filetype' to +a non-existing name such as `ignored` to avoid that it will be set later anyway. + + *g:did_load_filetypes* The builtin filetype detection provided by Nvim can be disabled by setting -the `did_load_filetypes` global variable. If this variable exists, neither -the default `$VIMRUNTIME/filetype.lua` nor the legacy `$VIMRUNTIME/filetype.vim` -will run. +the `did_load_filetypes` global variable. If this variable exists, the default +`$VIMRUNTIME/filetype.lua` will not run. *plugin-details* The "plugin" directory can be in any of the directories in the 'runtimepath' @@ -549,7 +534,7 @@ used. For example, to set the dialect to a default of "fblite" but still allow for any #lang directive overrides, use the following command: > - let g:freebasic_lang = "fblite" + let g:freebasic_lang = "fblite" GIT COMMIT *ft-gitcommit-plugin* @@ -586,12 +571,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..35a3be35fb 100644 --- a/runtime/doc/fold.txt +++ b/runtime/doc/fold.txt @@ -116,6 +116,11 @@ method can be very slow! Try to avoid the "=", "a" and "s" return values, since Vim often has to search backwards for a line for which the fold level is defined. This can be slow. +If the 'foldexpr' expression starts with s: or |<SID>|, then it is replaced +with the script ID (|local-function|). Examples: > + set foldexpr=s:MyFoldExpr() + set foldexpr=<SID>SomeFoldExpr() +< An example of using "a1" and "s1": For a multi-line C comment, a line containing "/*" would return "a1" to start a fold, and a line containing "*/" would return "s1" to end the fold after that line: > @@ -491,7 +496,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() @@ -521,6 +526,11 @@ The resulting line is truncated to fit in the window, it never wraps. When there is room after the text, it is filled with the character specified by 'fillchars'. +If the 'foldtext' expression starts with s: or |<SID>|, then it is replaced +with the script ID (|local-function|). Examples: > + set foldtext=s:MyFoldText() + set foldtext=<SID>SomeFoldText() +< Note that backslashes need to be used for characters that the ":set" command handles differently: Space, backslash and double-quote. |option-backslash| @@ -576,6 +586,11 @@ line is folded, it cannot be displayed there. Many movement commands handle a sequence of folded lines like an empty line. For example, the "w" command stops once in the first column. +When starting a search in a closed fold it will not find a match in the +current fold. It's like a forward search always starts from the end of the +closed fold, while a backwards search starts from the start of the closed +fold. + When in Insert mode, the cursor line is never folded. That allows you to see what you type! diff --git a/runtime/doc/ft_ada.txt b/runtime/doc/ft_ada.txt index f6dfa708fb..3321228009 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()* @@ -486,25 +486,25 @@ You can optionally install the following extra plug-ins. They work well with Ada and enhance the ability of the Ada mode: backup.vim - http://www.vim.org/scripts/script.php?script_id=1537 + https://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 - http://www.vim.org/scripts/script.php?script_id=1561 +rainbow_parenthesis.vim + https://www.vim.org/scripts/script.php?script_id=1561 Very helpful since Ada uses only '(' and ')'. nerd_comments.vim - http://www.vim.org/scripts/script.php?script_id=1218 + https://www.vim.org/scripts/script.php?script_id=1218 Excellent commenting and uncommenting support for almost any programming language. matchit.vim - http://www.vim.org/scripts/script.php?script_id=39 + https://www.vim.org/scripts/script.php?script_id=39 '%' jumping for any language. The normal '%' jump only works for '{}' style languages. The Ada mode will set the needed search patterns. taglist.vim - http://www.vim.org/scripts/script.php?script_id=273 + https://www.vim.org/scripts/script.php?script_id=273 Source code explorer sidebar. There is a patch for Ada available. The GNU Ada Project distribution (http://gnuada.sourceforge.net) of Vim diff --git a/runtime/doc/ft_rust.txt b/runtime/doc/ft_rust.txt index 5c8782ec7a..a5d5b558dc 100644 --- a/runtime/doc/ft_rust.txt +++ b/runtime/doc/ft_rust.txt @@ -1,70 +1,70 @@ -*ft_rust.txt* For Vim version 8.1. Last change: 2017 Nov 02 +*ft_rust.txt* Nvim This is documentation for the Rust filetype plugin. ============================================================================== -CONTENTS *rust* +CONTENTS *rust* -1. Introduction |rust-intro| -2. Settings |rust-settings| -3. Commands |rust-commands| -4. Mappings |rust-mappings| +1. Introduction |rust-intro| +2. Settings |rust-settings| +3. Commands |rust-commands| +4. Mappings |rust-mappings| ============================================================================== -INTRODUCTION *rust-intro* +INTRODUCTION *rust-intro* This plugin provides syntax and supporting functionality for the Rust filetype. ============================================================================== -SETTINGS *rust-settings* +SETTINGS *rust-settings* This plugin has a few variables you can define in your vimrc that change the behavior of the plugin. - *g:rustc_path* + *g:rustc_path* g:rustc_path~ Set this option to the path to rustc for use in the |:RustRun| and |:RustExpand| commands. If unset, "rustc" will be located in $PATH: > let g:rustc_path = $HOME .. "/bin/rustc" < - *g:rustc_makeprg_no_percent* + *g:rustc_makeprg_no_percent* g:rustc_makeprg_no_percent~ Set this option to 1 to have 'makeprg' default to "rustc" instead of "rustc %": > let g:rustc_makeprg_no_percent = 1 < - *g:rust_conceal* + *g:rust_conceal* g:rust_conceal~ Set this option to turn on the basic |conceal| support: > let g:rust_conceal = 1 < - *g:rust_conceal_mod_path* + *g:rust_conceal_mod_path* g:rust_conceal_mod_path~ Set this option to turn on |conceal| for the path connecting token "::": > let g:rust_conceal_mod_path = 1 < - *g:rust_conceal_pub* + *g:rust_conceal_pub* g:rust_conceal_pub~ Set this option to turn on |conceal| for the "pub" token: > let g:rust_conceal_pub = 1 < - *g:rust_recommended_style* + *g:rust_recommended_style* g:rust_recommended_style~ - Set this option to enable vim indentation and textwidth settings to - conform to style conventions of the rust standard library (i.e. use 4 - spaces for indents and sets 'textwidth' to 99). This option is enabled + Set this option to enable vim indentation and textwidth settings to + conform to style conventions of the rust standard library (i.e. use 4 + spaces for indents and sets 'textwidth' to 99). This option is enabled by default. To disable it: > let g:rust_recommended_style = 0 < - *g:rust_fold* + *g:rust_fold* g:rust_fold~ Set this option to turn on |folding|: > let g:rust_fold = 1 @@ -76,53 +76,53 @@ g:rust_fold~ 2 Braced blocks are folded. 'foldlevel' is left at the global value (all folds are closed by default). - *g:rust_bang_comment_leader* + *g:rust_bang_comment_leader* g:rust_bang_comment_leader~ Set this option to 1 to preserve the leader on multi-line doc comments using the /*! syntax: > let g:rust_bang_comment_leader = 1 < - *g:ftplugin_rust_source_path* + *g:ftplugin_rust_source_path* g:ftplugin_rust_source_path~ Set this option to a path that should be prepended to 'path' for Rust source files: > let g:ftplugin_rust_source_path = $HOME .. '/dev/rust' < - *g:rustfmt_command* + *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* + *g:rustfmt_autosave* g:rustfmt_autosave~ Set this option to 1 to run |:RustFmt| automatically when saving a buffer. If not specified it defaults to 0 : > let g:rustfmt_autosave = 0 < - *g:rustfmt_fail_silently* + *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* 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 = '' < - *g:rust_playpen_url* + *g:rust_playpen_url* g:rust_playpen_url~ Set this option to override the URL for the playpen to use: > let g:rust_playpen_url = 'https://play.rust-lang.org/' < - *g:rust_shortener_url* + *g:rust_shortener_url* g:rust_shortener_url~ Set this option to override the URL for the URL shortener: > let g:rust_shortener_url = 'https://is.gd/' @@ -130,9 +130,9 @@ g:rust_shortener_url~ ============================================================================== -COMMANDS *rust-commands* +COMMANDS *rust-commands* -:RustRun [args] *:RustRun* +:RustRun [args] *:RustRun* :RustRun! [rustc-args] [--] [args] Compiles and runs the current file. If it has unsaved changes, it will be saved first using |:update|. If the current file is @@ -150,7 +150,7 @@ COMMANDS *rust-commands* If |g:rustc_path| is defined, it is used as the path to rustc. Otherwise it is assumed rustc can be found in $PATH. -:RustExpand [args] *:RustExpand* +:RustExpand [args] *:RustExpand* :RustExpand! [TYPE] [args] Expands the current file using --pretty and displays the results in a new split. If the current file has unsaved @@ -169,7 +169,7 @@ COMMANDS *rust-commands* If |g:rustc_path| is defined, it is used as the path to rustc. Otherwise it is assumed rustc can be found in $PATH. -:RustEmitIr [args] *:RustEmitIr* +:RustEmitIr [args] *:RustEmitIr* Compiles the current file to LLVM IR and displays the results in a new split. If the current file has unsaved changes, it will be saved first using |:update|. If the current file is an @@ -180,7 +180,7 @@ COMMANDS *rust-commands* If |g:rustc_path| is defined, it is used as the path to rustc. Otherwise it is assumed rustc can be found in $PATH. -:RustEmitAsm [args] *:RustEmitAsm* +:RustEmitAsm [args] *:RustEmitAsm* Compiles the current file to assembly and displays the results in a new split. If the current file has unsaved changes, it will be saved first using |:update|. If the current file is an @@ -191,7 +191,7 @@ COMMANDS *rust-commands* If |g:rustc_path| is defined, it is used as the path to rustc. Otherwise it is assumed rustc can be found in $PATH. -:RustPlay *:RustPlay* +:RustPlay *:RustPlay* This command will only work if you have web-api.vim installed (available at https://github.com/mattn/webapi-vim). It sends the current selection, or if nothing is selected, the entirety of the @@ -204,7 +204,7 @@ COMMANDS *rust-commands* |g:rust_shortener_url| is the base URL for the shortener, by default "https://is.gd/" -:RustFmt *:RustFmt* +:RustFmt *:RustFmt* Runs |g:rustfmt_command| on the current buffer. If |g:rustfmt_options| is set then those will be passed to the executable. @@ -214,12 +214,12 @@ COMMANDS *rust-commands* |g:rustfmt_command|. If |g:rustfmt_fail_silently| is set to 1 then it will not populate the |location-list|. -:RustFmtRange *:RustFmtRange* +:RustFmtRange *:RustFmtRange* Runs |g:rustfmt_command| with selected range. See |:RustFmt| for any other information. ============================================================================== -MAPPINGS *rust-mappings* +MAPPINGS *rust-mappings* This plugin defines mappings for |[[| and |]]| to support hanging indents. diff --git a/runtime/doc/ft_sql.txt b/runtime/doc/ft_sql.txt index 335faf266e..21a244e67a 100644 --- a/runtime/doc/ft_sql.txt +++ b/runtime/doc/ft_sql.txt @@ -37,9 +37,10 @@ The SQL ftplugin provides a number of options to assist with file navigation. +------------------------------------------------------------------------------ 1.1 Matchit *sql-matchit* ------------ -The matchit plugin (http://www.vim.org/scripts/script.php?script_id=39) + +The matchit plugin (https://www.vim.org/scripts/script.php?script_id=39) provides many additional features and can be customized for different languages. The matchit plugin is configured by defining a local buffer variable, b:match_words. Pressing the % key while on various @@ -85,8 +86,9 @@ The following keywords are supported: > returns +------------------------------------------------------------------------------ 1.2 Text Object Motions *sql-object-motions* ------------------------ + Vim has a number of predefined keys for working with text |object-motions|. This filetype plugin attempts to translate these keys to maps which make sense for the SQL language. @@ -99,8 +101,9 @@ file): > [] move backwards to the previous 'end' +------------------------------------------------------------------------------ 1.3 Predefined Object Motions *sql-predefined-objects* ------------------------------ + Most relational databases support various standard features, tables, indices, triggers and stored procedures. Each vendor also has a variety of proprietary objects. The next set of maps have been created to help move between these @@ -166,8 +169,9 @@ with comments: > +------------------------------------------------------------------------------ 1.4 Macros *sql-macros* ----------- + Vim's feature to find macro definitions, |'define'|, is supported using this regular expression: > \c\<\(VARIABLE\|DECLARE\|IN\|OUT\|INOUT\)\> @@ -230,8 +234,9 @@ The majority of people work with only one vendor's database product, it would be nice to specify a default in your |init.vim|. +------------------------------------------------------------------------------ 2.1 SQLSetType *sqlsettype* *SQLSetType* --------------- + For the people that work with many different databases, it is nice to be able to flip between the various vendors rules (indent, syntax) on a per buffer basis, at any time. The ftplugin/sql.vim file defines this function: > @@ -244,7 +249,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 @@ -259,8 +264,9 @@ of available Vim script names: > :SQL<Tab><space><Tab> +------------------------------------------------------------------------------ 2.2 SQLGetType *sqlgettype* *SQLGetType* --------------- + At anytime you can determine which SQL dialect you are using by calling the SQLGetType command. The ftplugin/sql.vim file defines this function: > SQLGetType @@ -269,8 +275,9 @@ This will echo: > Current SQL dialect in use:sqlanywhere +------------------------------------------------------------------------------ 2.3 SQL Dialect Default *sql-type-default* ------------------------ + As mentioned earlier, the default syntax rules for Vim is based on Oracle (PL/SQL). You can override this default by placing one of the following in your |init.vim|: > @@ -296,7 +303,7 @@ exist. 3. Adding new SQL Dialects *sql-adding-dialects* If you begin working with a SQL dialect which does not have any customizations -available with the default Vim distribution you can check http://www.vim.org +available with the default Vim distribution you can check https://www.vim.org to see if any customization currently exist. If not, you can begin by cloning an existing script. Read |filetype-plugins| for more details. @@ -325,8 +332,9 @@ highlight rules. The dynamic mode populates the popups with data retrieved directly from a database. This includes, table lists, column lists, procedures names and more. +------------------------------------------------------------------------------ 4.1 Static Mode *sql-completion-static* ---------------- + The static popups created contain items defined by the active syntax rules while editing a file with a filetype of SQL. The plugin defines (by default) various maps to help the user refine the list of items to be displayed. @@ -399,11 +407,12 @@ Here are some examples of the entries which are pulled from the syntax files: > - Integer, Char, Varchar, Date, DateTime, Timestamp, ... +------------------------------------------------------------------------------ 4.2 Dynamic Mode *sql-completion-dynamic* ----------------- + Dynamic mode populates the popups with data directly from a database. In order for the dynamic feature to be enabled you must have the dbext.vim -plugin installed, (http://vim.sourceforge.net/script.php?script_id=356). +plugin installed, (https://vim.sourceforge.net/script.php?script_id=356). Dynamic mode is used by several features of the SQL completion plugin. After installing the dbext plugin see the dbext-tutorial for additional @@ -448,8 +457,8 @@ necessary to clear the plugins cache. The default map for this is: > imap <buffer> <C-C>R <C-\><C-O>:call sqlcomplete#Map('ResetCache')<CR><C-X><C-O> +------------------------------------------------------------------------------ 4.3 SQL Tutorial *sql-completion-tutorial* ----------------- This tutorial is designed to take you through the common features of the SQL completion plugin so that: > @@ -462,8 +471,8 @@ First, create a new buffer: > :e tutorial.sql -Static features ---------------- +Static features ~ + To take you through the various lists, simply enter insert mode, hit: <C-C>s (show SQL statements) At this point, you can page down through the list until you find "select". @@ -484,10 +493,10 @@ depending on the syntax file you are using. The SQL Anywhere syntax file DECLARE customer_id <C-C>T <-- Choose a type from the list -Dynamic features ----------------- +Dynamic features ~ + To take advantage of the dynamic features you must first install the -dbext.vim plugin (http://vim.sourceforge.net/script.php?script_id=356). It +dbext.vim plugin (https://vim.sourceforge.net/script.php?script_id=356). It also comes with a tutorial. From the SQL completion plugin's perspective, the main feature dbext provides is a connection to a database. dbext connection profiles are the most efficient mechanism to define connection @@ -597,8 +606,8 @@ Similar to the table list, <C-C>v, will display a list of views in the database. +------------------------------------------------------------------------------ 4.4 Completion Customization *sql-completion-customization* ----------------------------- The SQL completion plugin can be customized through various options set in your |init.vim|: > @@ -657,14 +666,14 @@ your |init.vim|: > option. > +------------------------------------------------------------------------------ 4.5 SQL Maps *sql-completion-maps* ------------- The default SQL maps have been described in other sections of this document in greater detail. Here is a list of the maps with a brief description of each. -Static Maps ------------ +Static Maps ~ + These are maps which use populate the completion list using Vim's syntax highlighting rules. > <C-C>a @@ -680,8 +689,8 @@ highlighting rules. > <C-C>s < - Displays all SQL syntax items defined as 'sqlStatement'. > -Dynamic Maps ------------- +Dynamic Maps ~ + These are maps which use populate the completion list using the dbext.vim plugin. > <C-C>t @@ -713,8 +722,8 @@ plugin. > < - This maps removes all cached items and forces the SQL completion to regenerate the list of items. -Customizing Maps ----------------- +Customizing Maps ~ + You can create as many additional key maps as you like. Generally, the maps will be specifying different syntax highlight groups. @@ -733,8 +742,8 @@ chosen since it will work on both Windows and *nix platforms. On the windows platform you can also use <C-Space> or ALT keys. +------------------------------------------------------------------------------ 4.6 Using with other filetypes *sql-completion-filetypes* ------------------------------- Many times SQL can be used with different filetypes. For example Perl, Java, PHP, Javascript can all interact with a database. Often you need both the SQL @@ -746,8 +755,8 @@ This can be enabled easily with the following steps (assuming a Perl file): > 2. :set filetype=sql 3. :set ft=perl -Step 1 ------- +Step 1 ~ + Begins by editing a Perl file. Vim automatically sets the filetype to "perl". By default, Vim runs the appropriate filetype file ftplugin/perl.vim. If you are using the syntax completion plugin by following @@ -755,9 +764,9 @@ the directions at |ft-syntax-omni| then the |'omnifunc'| option has been set to "syntax#Complete". Pressing <C-X><C-O> will display the omni popup containing the syntax items for Perl. -Step 2 ------- -Manually setting the filetype to 'sql' will also fire the appropriate filetype +Step 2 ~ + +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 @@ -767,8 +776,8 @@ begin with <C-C>, the maps will toggle the |'omnifunc'| when in use. So you can use <C-X><C-O> to continue using the completion for Perl (using the syntax completion plugin) and <C-C> to use the SQL completion features. -Step 3 ------- +Step 3 ~ + Setting the filetype back to Perl sets all the usual "perl" related items back as they were. diff --git a/runtime/doc/gui.txt b/runtime/doc/gui.txt index 8f09e5225f..1fce9fa491 100644 --- a/runtime/doc/gui.txt +++ b/runtime/doc/gui.txt @@ -44,8 +44,8 @@ Scrollbars *gui-scrollbars* There are vertical scrollbars and a horizontal scrollbar. You may configure which ones appear with the 'guioptions' option. -The interface looks like this (with ":set guioptions=mlrb"): - +The interface looks like this (with `:set guioptions=mlrb`): +> +------------------------------+ ` | File Edit Help | <- Menu bar (m) ` +-+--------------------------+-+ ` @@ -66,7 +66,7 @@ The interface looks like this (with ":set guioptions=mlrb"): +-+--------------------------+-+ ` | |< #### >| | <- Bottom ` +-+--------------------------+-+ scrollbar (b) ` - +< Any of the scrollbar or menu components may be turned off by not putting the appropriate letter in the 'guioptions' string. The bottom scrollbar is only useful when 'nowrap' is set. @@ -123,7 +123,7 @@ message). Keep Shift pressed to change to the directory instead. If Vim happens to be editing a command line, the names of the dropped files and directories will be inserted at the cursor. This allows you to use these names with any Ex command. Special characters (space, tab, double quote and -'|'; backslash on non-MS-Windows systems) will be escaped. +"|"; backslash on non-MS-Windows systems) will be escaped. ============================================================================== Menus *menus* @@ -450,8 +450,8 @@ The default "PopUp" menu is: > anoremenu PopUp.Paste "+gP vnoremenu PopUp.Paste "+P vnoremenu PopUp.Delete "_x - nnoremenu PopUp.Select\ All> ggVG - vnoremenu PopUp.Select\ All> gg0oG$ + nnoremenu PopUp.Select\ All ggVG + vnoremenu PopUp.Select\ All gg0oG$ inoremenu PopUp.Select\ All <C-Home><C-O>VG anoremenu PopUp.-1- <Nop> anoremenu PopUp.How-to\ disable\ mouse <Cmd>help disable-mouse<CR> @@ -569,14 +569,14 @@ Tooltips & Menu tips See section |42.4| in the user manual. *:tmenu* -:tm[enu] {menupath} {rhs} Define a tip for a menu or tool. {only in - X11 and Win32 GUI} +:tm[enu] {menupath} {rhs} Define a tip for a menu or tool. (only in + X11 and Win32 GUI) -:tm[enu] [menupath] List menu tips. {only in X11 and Win32 GUI} +:tm[enu] [menupath] List menu tips. (only in X11 and Win32 GUI) *:tunmenu* :tu[nmenu] {menupath} Remove a tip for a menu or tool. - {only in X11 and Win32 GUI} + (only in X11 and Win32 GUI) Note: To create menus for terminal mode, use |:tlmenu| instead. diff --git a/runtime/doc/hebrew.txt b/runtime/doc/hebrew.txt index 2f4b137bd3..76266d777f 100644 --- a/runtime/doc/hebrew.txt +++ b/runtime/doc/hebrew.txt @@ -11,8 +11,9 @@ Lottem. <alottem at gmail dot com> Ron Aaron <ron at ronware dot org> is currently helping support these features. +------------------------------------------------------------------------------ Introduction ------------- + Hebrew-specific options are 'hkmap', 'hkmapp' 'keymap'=hebrew and 'aleph'. Hebrew-useful options are 'delcombine', 'allowrevins', 'revins', 'rightleft' and 'rightleftcmd'. @@ -22,8 +23,9 @@ from right to left instead of the usual left to right. This is useful primarily when editing Hebrew or other Middle-Eastern languages. See |rileft.txt| for further details. +------------------------------------------------------------------------------ Details --------------- + + Options: + 'rightleft' ('rl') sets window orientation to right-to-left. This means that the logical text 'ABC' will be displayed as 'CBA', and will start @@ -31,7 +33,7 @@ Details + 'hkmap' ('hk') sets keyboard mapping to Hebrew, in insert/replace modes. + 'aleph' ('al'), numeric, holds the decimal code of Aleph, for keyboard mapping. - + 'hkmapp' ('hkp') sets keyboard mapping to 'phonetic hebrew' + + 'hkmapp' ('hkp') sets keyboard mapping to "phonetic hebrew" NOTE: these three ('hkmap', 'hkmapp' and 'aleph') are obsolete. You should use ":set keymap=hebrewp" instead. @@ -51,7 +53,7 @@ Details ('deco' does nothing if UTF8 encoding is not active). + Vim arguments: - + 'vim -H file' starts editing a Hebrew file, i.e. 'rightleft' and 'hkmap' + + `vim -H file` starts editing a Hebrew file, i.e. 'rightleft' and 'hkmap' are set. + Keyboard: @@ -116,8 +118,9 @@ when exiting 'revins' via CTRL-_, the cursor moves to the end of the typed text (if possible). +------------------------------------------------------------------------------ Pasting when in a rightleft window ----------------------------------- + When cutting text with the mouse and pasting it in a rightleft window the text will be reversed, because the characters come from the cut buffer from the left to the right, while inserted in the file from the right to @@ -125,8 +128,9 @@ the left. In order to avoid it, toggle 'revins' (by typing CTRL-? or CTRL-_) before pasting. +------------------------------------------------------------------------------ Hebrew characters and the 'isprint' variable --------------------------------------------- + Sometimes Hebrew character codes are in the non-printable range defined by the 'isprint' variable. For example in the Linux console, the Hebrew font encoding starts from 128, while the default 'isprint' variable is @,161-255. diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt index 04e31e0680..07f898f99c 100644 --- a/runtime/doc/help.txt +++ b/runtime/doc/help.txt @@ -1,6 +1,6 @@ *help.txt* Nvim - VIM - main help file + NVIM - help k Move around: Use the cursor keys, or "h" to go left, h l "j" to go down, "k" to go up, "l" to go right. j @@ -37,169 +37,149 @@ Get specific help: It is possible to go directly to whatever you want help Vim stands for Vi IMproved. Most of Vim was made by Bram Moolenaar, but only through the help of many others. See |credits|. + +============================================================================== +NVIM DOCUMENTATION + +------------------------------------------------------------------------------ +ABOUT NVIM *reference_toc* *doc-file-list* *Q_ct* + +|news| News since the previous release +|nvim| Transitioning from Vim +|vim-differences| Nvim compared to Vim +|user-manual| User manual: How to accomplish editing tasks. +|quickref| Overview of common commands +|tutor| 30-minute interactive course for beginners +|copying| About copyrights +|iccf| Helping poor children in Uganda +|sponsor| Sponsor Vim development, become a registered Vim user +|www| Vim on the World Wide Web +|bugs| Where to send bug reports +|support| Supported platforms + +------------------------------------------------------------------------------ +GENERAL + +|intro| Introduction to Vim; notation used in help files +|helphelp| Using the :help files +|index| Index of all commands +|tips| Various tips on using Vim +|message.txt| (Error) messages and explanations +|uganda.txt| Vim distribution and what to do with your money + +------------------------------------------------------------------------------ +BASIC EDITING + +|starting| Starting Vim, Vim command arguments, initialisation +|edit-files| Editing and writing files +|motion.txt| Commands for moving around +|scrolling| Scrolling the text in the window +|insert.txt| Insert and Replace mode +|change.txt| Deleting and replacing text +|undo-redo| Undo and Redo +|repeat.txt| Repeating commands, Vim scripts and debugging +|visual-mode| Using Visual mode (selecting text) +|various| Various other commands +|crash-recovery| Recovering from a crash + +------------------------------------------------------------------------------ +ADVANCED EDITING + +|cmdline| Command-line editing +|options| Description of all options +|pattern-searches| Vim regexp patterns and search commands +|key-mapping| Key mapping (shortcuts), abbreviations +|tags| Tags and special searches +|windows| Commands for using windows and buffers +|tabpage| Commands for using tabpages +|spell| Spell checking +|diff| Comparing files +|folding| Hide (fold) ranges of lines +|terminal| Embedded terminal emulator + +------------------------------------------------------------------------------ +API (EXTENSIBILITY/SCRIPTING/PLUGINS) + +|api| Nvim API via RPC, Lua and VimL +|ui| Nvim UI protocol +|lua-guide| Nvim Lua guide +|lua| Lua API +|luaref| Lua reference manual +|luvref| Luv (|vim.loop|) reference manual +|autocmd| Event handlers +|job-control| Spawn and control multiple processes +|channel| Nvim asynchronous IO +|vimscript| Vimscript reference +|vimscript-functions| Vimscript functions +|testing.txt| Vimscript testing functions +|remote-plugin| Nvim remote plugins + +------------------------------------------------------------------------------ +PROGRAMMING LANGUAGE SUPPORT + +|lsp| Language Server Protocol (LSP) +|diagnostic-api| Diagnostic framework +|treesitter| Incremental syntax parsing +|indent.txt| automatic indenting for C and other languages +|syntax| syntax highlighting +|filetype| Settings for specific types of files +|quickfix| Commands for a quick edit-compile-fix cycle +|ft_ada.txt| Ada filetype plugin +|ft_ps1.txt| PowerShell filetype plugin +|ft_raku.txt| Raku filetype plugin +|ft_rust.txt| Rust filetype plugin +|ft_sql.txt| SQL filetype plugin + +------------------------------------------------------------------------------ +UI + +|tui| Builtin UI +|gui| External (graphical) UIs +|signs| Signs displayed as window decorations (the "gutter") + +------------------------------------------------------------------------------ +LANGUAGE SUPPORT + +|digraph| List of available digraphs +|mbyte.txt| Multibyte text support +|mlang.txt| Non-English language support +|rileft.txt| Right-to-left editing mode +|arabic.txt| Arabic language support and editing +|hebrew.txt| Hebrew language support and editing +|russian.txt| Russian language support and editing + ------------------------------------------------------------------------------ - *doc-file-list* *Q_ct* -BASIC: -|quickref| Overview of the most common commands you will use -|tutor| 30-minute interactive course for beginners -|copying| About copyrights -|iccf| Helping poor children in Uganda -|sponsor| Sponsor Vim development, become a registered Vim user -|www| Vim on the World Wide Web -|bugs| Where to send bug reports - -USER MANUAL: These files explain how to accomplish an editing task. - -|usr_toc.txt| Table Of Contents - -Getting Started ~ -|usr_01.txt| About the manuals -|usr_02.txt| The first steps in Vim -|usr_03.txt| Moving around -|usr_04.txt| Making small changes -|usr_05.txt| Set your settings -|usr_06.txt| Using syntax highlighting -|usr_07.txt| Editing more than one file -|usr_08.txt| Splitting windows -|usr_09.txt| Using the GUI -|usr_10.txt| Making big changes -|usr_11.txt| Recovering from a crash -|usr_12.txt| Clever tricks - -Editing Effectively ~ -|usr_20.txt| Typing command-line commands quickly -|usr_21.txt| Go away and come back -|usr_22.txt| Finding the file to edit -|usr_23.txt| Editing other files -|usr_24.txt| Inserting quickly -|usr_25.txt| Editing formatted text -|usr_26.txt| Repeating -|usr_27.txt| Search commands and patterns -|usr_28.txt| Folding -|usr_29.txt| Moving through programs -|usr_30.txt| Editing programs -|usr_31.txt| Exploiting the GUI -|usr_32.txt| The undo tree - -Tuning Vim ~ -|usr_40.txt| Make new commands -|usr_41.txt| Write a Vim script -|usr_42.txt| Add new menus -|usr_43.txt| Using filetypes -|usr_44.txt| Your own syntax highlighted -|usr_45.txt| Select your language - - -REFERENCE MANUAL: These files explain every detail of Vim. *reference_toc* - -General subjects ~ -|intro.txt| general introduction to Vim; notation used in help files -|nvim.txt| Transitioning from Vim -|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 -|debug.txt| debugging Vim itself -|uganda.txt| Vim distribution conditions and what to do with your money - -Basic editing ~ -|starting.txt| starting Vim, Vim command arguments, initialisation -|editing.txt| editing and writing files -|motion.txt| commands for moving around -|scroll.txt| scrolling the text in the window -|insert.txt| Insert and Replace mode -|change.txt| deleting and replacing text -|undo.txt| Undo and Redo -|repeat.txt| repeating commands, Vim scripts and debugging -|visual.txt| using the Visual mode (selecting a text area) -|various.txt| various remaining commands -|recover.txt| recovering from a crash - -Advanced editing ~ -|cmdline.txt| Command-line editing -|options.txt| description of all options -|pattern.txt| regexp patterns and search commands -|map.txt| key mapping and abbreviations -|tagsrch.txt| tags and special searches -|windows.txt| commands for using multiple windows and buffers -|tabpage.txt| commands for using multiple tab pages -|spell.txt| spell checking -|diff.txt| working with two to eight versions of the same file -|autocmd.txt| automatically executing commands on an event -|eval.txt| expression evaluation, conditional commands -|builtin.txt| builtin functions -|fold.txt| hide (fold) ranges of lines -|lua.txt| Lua API -|api.txt| Nvim API via RPC, Lua and VimL - -Special issues ~ -|testing.txt| testing Vim and Vim scripts -|print.txt| printing -|remote_plugin.txt| Nvim support for remote plugins - -Programming language support ~ -|indent.txt| automatic indenting for C and other languages -|lsp.txt| Language Server Protocol (LSP) -|treesitter.txt| tree-sitter library for incremental parsing of buffers -|diagnostic.txt| Diagnostic framework -|syntax.txt| syntax highlighting -|filetype.txt| settings done specifically for a type of file -|quickfix.txt| commands for a quick edit-compile-fix cycle -|provider.txt| Built-in remote plugin hosts -|ft_ada.txt| Ada (the programming language) support -|ft_ps1.txt| Filetype plugin for Windows PowerShell -|ft_raku.txt| Filetype plugin for Raku -|ft_rust.txt| Filetype plugin for Rust -|ft_sql.txt| about the SQL filetype plugin - -Language support ~ -|digraph.txt| list of available digraphs -|mbyte.txt| multibyte text support -|mlang.txt| non-English language support -|rileft.txt| right-to-left editing mode -|arabic.txt| Arabic language support and editing -|hebrew.txt| Hebrew language support and editing -|russian.txt| Russian language support and editing - -GUI ~ -|gui.txt| Graphical User Interface (GUI) - -Interfaces ~ -|if_cscop.txt| using Cscope with Vim -|if_perl.txt| Perl interface -|if_pyth.txt| Python interface -|if_ruby.txt| Ruby interface -|sign.txt| debugging signs - -Versions ~ -|vim_diff.txt| Main differences between Nvim and Vim -|vi_diff.txt| Main differences between Vim and Vi -|deprecated.txt| Deprecated items that have been or will be removed - -Other ~ -|terminal_emulator.txt| Terminal buffers -|term.txt| Terminal UI -|ui.txt| Nvim UI protocol -|channel.txt| Nvim asynchronous IO -|dev_style.txt| Nvim style guide -|job_control.txt| Spawn and control multiple processes -|luaref.txt| Lua reference manual -|luvref.txt| Luv (|vim.loop|) reference manual +INTEROP + +|provider| Builtin remote plugin hosts +|if_perl| Perl interface +|if_pyth| Python interface +|if_ruby| Ruby interface + +------------------------------------------------------------------------------ +VERSIONS + +|deprecated| Deprecated features that will be removed +|vi-differences| Differences between Vim and Vi + +------------------------------------------------------------------------------ +DEVELOPING NVIM + +|dev| Development of Nvim +|dev-style| Development style guidelines +|debug.txt| Debugging Vim itself *standard-plugin-list* Standard plugins ~ -|matchit.txt| Extended |%| matching -|pi_gzip.txt| Reading and writing compressed files -|pi_health.txt| Healthcheck framework -|pi_msgpack.txt| msgpack utilities -|pi_netrw.txt| Reading and writing files over a network -|pi_paren.txt| Highlight matching parens -|pi_spec.txt| Filetype plugin to work with rpm spec files -|pi_tar.txt| Tar file explorer -|pi_zip.txt| Zip archive explorer +|matchit.txt| Extended |%| matching +|pi_gzip.txt| Reading and writing compressed files +|pi_health.txt| Healthcheck framework +|pi_msgpack.txt| msgpack utilities +|pi_netrw.txt| Reading and writing files over a network +|pi_paren.txt| Highlight matching parens +|pi_spec.txt| Filetype plugin to work with rpm spec files +|pi_tar.txt| Tar file explorer +|pi_zip.txt| Zip archive explorer LOCAL ADDITIONS: *local-additions* @@ -212,8 +192,8 @@ CTRL-T, CTRL-O, g<RightMouse>, or <C-RightMouse> to go back to where you were. Note that tags are within | characters, but when highlighting is enabled these characters are hidden. That makes it easier to read a command. -Anyway, you can use CTRL-] on any word, also when it is not within |, and Vim -will try to find help for it. Especially for options in single quotes, e.g. +You can use CTRL-] on any word (even if it is not within "|") and Nvim will +try to find help for it. Especially for options in single quotes, e.g. 'hlsearch'. ------------------------------------------------------------------------------ diff --git a/runtime/doc/helphelp.txt b/runtime/doc/helphelp.txt index 569995d319..da307dd241 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} @@ -257,7 +251,7 @@ At this moment translations are available for: Japanese - multiple authors Polish - translated by Mikolaj Machowski Russian - translated by Vassily Ragosin -See the Vim website to find them: http://www.vim.org/translations.php +See the Vim website to find them: https://www.vim.org/translations.php A set of translated help files consists of these files: @@ -348,7 +342,7 @@ should begin with the name of the Vim plugin. The tag name is usually right aligned on a line. When referring to an existing help tag and to create a hot-link, place the -name between two bars (|) eg. |help-writing|. +name between two bars ("|") eg. |help-writing|. When referring to a Vim command and to create a hot-link, place the name between two backticks, eg. inside `:filetype`. You will see this is @@ -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/if_cscop.txt b/runtime/doc/if_cscop.txt deleted file mode 100644 index 8947aefc1b..0000000000 --- a/runtime/doc/if_cscop.txt +++ /dev/null @@ -1,374 +0,0 @@ -*if_cscop.txt* Nvim - - - VIM REFERENCE MANUAL by Andy Kahn - - *cscope* *Cscope* -Cscope is a "code intelligence" tool that helps you navigate C programs. It -can also perform some refactoring tasks, such as renaming a global variable in -all source files. Think of it as "ctags on steroids". - -See |cscope-usage| for a quickstart. - - Type |gO| to see the table of contents. - -============================================================================== -Cscope introduction *cscope-intro* - - -Cscope is designed to answer questions like: - Where is this symbol used? - Where is it defined? - Where did this variable get its value? - What is this global symbol's definition? - Where is this function in the source files? - What functions call this function? - What functions are called by this function? - Where does the message "out of space" come from? - Where is this source file in the directory structure? - What files include this header file? - -Cscope answers these questions from a symbol database that it builds the first -time it is used on the source files. On a subsequent call, cscope rebuilds -the database only if a source file has changed or the list of source files is -different. When the database is rebuilt the data for the unchanged files is -copied from the old database, which makes rebuilding much faster than the -initial build. - -See |cscope-usage| to get started. - -============================================================================== -Cscope commands *cscope-commands* - - *:cscope* *:cs* *:scs* *:scscope* *E259* *E262* *E560* *E561* -All cscope commands are accessed through suboptions to the cscope commands. - `:cscope` or `:cs` is the main command - `:scscope` or `:scs` does the same and splits the window - `:lcscope` or `:lcs` uses the location list, see |:lcscope| - -The available subcommands are: - - *E563* *E564* *E566* *E568* *E622* *E623* *E625* - *E626* *E609* - add : Add a new cscope database/connection. - - USAGE :cs add {file|dir} [pre-path] [flags] - - [pre-path] is the pathname used with the -P command to cscope. - - [flags] are any additional flags you want to pass to cscope. - - EXAMPLES > - :cscope add /usr/local/cdb/cscope.out - :cscope add /projects/vim/cscope.out /usr/local/vim - :cscope add cscope.out /usr/local/vim -C -< - *cscope-find* *cs-find* *E567* - find : Query cscope. All cscope query options are available - except option #5 ("Change this grep pattern"). - - USAGE :cs find {querytype} {name} - - {querytype} corresponds to the actual cscope line - interface numbers as well as default nvi commands: - - 0 or s: Find this C symbol - 1 or g: Find this definition - 2 or d: Find functions called by this function - 3 or c: Find functions calling this function - 4 or t: Find this text string - 6 or e: Find this egrep pattern - 7 or f: Find this file - 8 or i: Find files #including this file - 9 or a: Find places where this symbol is assigned a value - - For all types, except 4 and 6, leading white space for {name} is - removed. For 4 and 6 there is exactly one space between {querytype} - and {name}. Further white space is included in {name}. - - EXAMPLES > - :cscope find c vim_free - :cscope find 3 vim_free -< - These two examples perform the same query: functions calling - "vim_free". > - - :cscope find t initOnce - :cscope find t initOnce -< - The first one searches for the text "initOnce", the second one for - " initOnce". > - - :cscope find 0 DEFAULT_TERM -< - Executing this example on the source code for Vim 5.1 produces the - following output: - - Cscope tag: DEFAULT_TERM - # line filename / context / line - 1 1009 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"amiga" - 2 1013 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"win32" - 3 1017 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"pcterm" - 4 1021 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"ansi" - 5 1025 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"vt52" - 6 1029 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"os2ansi" - 7 1033 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"ansi" - 8 1037 vim-5.1-gtk/src/term.c <<GLOBAL>> - # undef DEFAULT_TERM - 9 1038 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"beos-ansi" - 10 1042 vim-5.1-gtk/src/term.c <<GLOBAL>> - #define DEFAULT_TERM (char_u *)"mac-ansi" - 11 1335 vim-5.1-gtk/src/term.c <<set_termname>> - term = DEFAULT_TERM; - 12 1459 vim-5.1-gtk/src/term.c <<set_termname>> - if (STRCMP(term, DEFAULT_TERM)) - 13 1826 vim-5.1-gtk/src/term.c <<termcapinit>> - term = DEFAULT_TERM; - 14 1833 vim-5.1-gtk/src/term.c <<termcapinit>> - term = DEFAULT_TERM; - 15 3635 vim-5.1-gtk/src/term.c <<update_tcap>> - p = find_builtin_term(DEFAULT_TERM); - Enter nr of choice (<CR> to abort): - - The output shows several pieces of information: - 1. The tag number (there are 15 in this example). - 2. The line number where the tag occurs. - 3. The filename where the tag occurs. - 4. The context of the tag (e.g., global, or the function name). - 5. The line from the file itself. - - help : Show a brief synopsis. - - USAGE :cs help - - *E261* - kill : Kill a cscope connection (or kill all cscope connections). - - USAGE :cs kill {num|partial_name} - - To kill a cscope connection, the connection number or a partial - name must be specified. The partial name is simply any part of - the pathname of the cscope database. Kill a cscope connection - using the partial name with caution! - - If the specified connection number is -1, then _ALL_ cscope - connections will be killed. - - reset : Reinit all cscope connections. - - USAGE :cs reset - - show : Show cscope connections. - - USAGE :cs show - - *:lcscope* *:lcs* -This command is same as the ":cscope" command, except when the -'cscopequickfix' option is set, the location list for the current window is -used instead of the quickfix list to show the cscope results. - - *:cstag* *E257* *E562* -If you use cscope as well as ctags, |:cstag| allows you to search one or -the other before making a jump. For example, you can choose to first -search your cscope database(s) for a match, and if one is not found, then -your tags file(s) will be searched. The order in which this happens -is determined by the value of |csto|. See |cscope-options| for more -details. - -|:cstag| performs the equivalent of ":cs find g" on the identifier when -searching through the cscope database(s). - -|:cstag| performs the equivalent of |:tjump| on the identifier when searching -through your tags file(s). - - -============================================================================== -Cscope options *cscope-options* - -Use the |:set| command to set all cscope options. Ideally, you would do -this in one of your startup files (e.g., vimrc). Some cscope related -variables are only valid within |init.vim|. Setting them after vim has -started will have no effect! - - *cscopeprg* *csprg* -'cscopeprg' specifies the command to execute cscope. The default is -"cscope". For example: > - :set csprg=/usr/local/bin/cscope -< - *cscopequickfix* *csqf* *E469* -'cscopequickfix' specifies whether to use quickfix window to show cscope -results. This is a list of comma-separated values. Each item consists of -|cscope-find| command (s, g, d, c, t, e, f, i or a) and flag (+, - or 0). -'+' indicates that results must be appended to quickfix window, -'-' implies previous results clearance, '0' or command absence - don't use -quickfix. Search is performed from start until first command occurrence. -The default value is "" (don't use quickfix anyway). The following value -seems to be useful: > - :set cscopequickfix=s-,c-,d-,i-,t-,e-,a- -< - *cscopetag* *cst* -If 'cscopetag' is set, the commands ":tag" and CTRL-] as well as "vim -t" -will always use |:cstag| instead of the default :tag behavior. Effectively, -by setting 'cst', you will always search your cscope databases as well as -your tag files. The default is off. - - *cscoperelative* *csre* -If 'cscoperelative' is set, then in absence of a prefix given to cscope -(prefix is the argument of -P option of cscope), basename of cscope.out -location (usually the project root directory) will be used as the prefix -to construct an absolute path. The default is off. Note: This option is -only effective when cscope (cscopeprg) is initialized without a prefix -path (-P). - - *cscopetagorder* *csto* -The value of 'csto' determines the order in which |:cstag| performs a search. -If 'csto' is set to zero, cscope database(s) are searched first, followed -by tag file(s) if cscope did not return any matches. If 'csto' is set to -one, tag file(s) are searched before cscope database(s). The default is zero. - - *cscopepathcomp* *cspc* -'cscopepathcomp' determines how many components of a file's path to display. -With the default value of zero the entire path will be displayed. -The value one will display only the filename with no path. Other values -display that many components. For example: > - :set cscopepathcomp=3 -will display the last 3 components of the file's path, including the file -name itself. - -============================================================================== -Using cscope in Nvim *cscope-usage* *cscope-howtouse* - -To get started, build the cscope database in your project root directory: > - cscope -bcqR - -See the cscope manpage for details: > - :Man cscope - -By default the cscope database file is named "cscope.out". After building the -database, connect to it from Nvim: > - :cscope add cscope.out - -That establishes a cscope connection for Nvim to use. You can check the -result with ":cs show". It will show something like: - - # pid database name prepend path - 0 28806 cscope.out <none> - -Once a cscope connection is established, you can make queries to cscope and -the results will be printed. Queries are made using the command ":cs find". -For example: > - :cs find g ALIGN_SIZE - -To make this easier you can configure mappings, see |cscope-suggestions|. - -If the results return only one match, you will automatically be taken to it. -If there is more than one match, you will be given a selection screen to pick -the match you want to go to. After you have jumped to the new location, -simply hit Ctrl-T to get back to the previous one. - - -============================================================================== -Limitations *cscope-limitations* - -Hard-coded limitation: doing a |:tjump| when |:cstag| searches the tag files -is not configurable (e.g., you can't do a tselect instead). - - -============================================================================== -Sample config *cscope-suggestions* - -Copy this into your init.vim (adjust paths for your system): > - - if has("cscope") - set csprg=/usr/local/bin/cscope - set csto=0 - set cst - " add any database in current directory - if filereadable("cscope.out") - silent cs add cscope.out - " else add database pointed to by environment - elseif $CSCOPE_DB != "" - silent cs add $CSCOPE_DB - endif - endif - -By setting 'cscopetag', we have effectively replaced all instances of the :tag -command with :cstag. This includes :tag, Ctrl-], and "vim -t". In doing -this, the regular tag command not only searches your ctags generated tag -files, but your cscope databases as well. - -Some users may want to keep the regular tag behavior and have a different -shortcut to access :cstag. For example, one could map Ctrl-_ (underscore) -to :cstag with the following command: > - - map <C-_> :cstag <C-R>=expand("<cword>")<CR><CR> - -A couple of very commonly used cscope queries (using ":cs find") is to -find all functions calling a certain function and to find all occurrences -of a particular C symbol. To do this, you can use these mappings as an -example: > - - map g<C-]> :cs find 3 <C-R>=expand("<cword>")<CR><CR> - map g<C-\> :cs find 0 <C-R>=expand("<cword>")<CR><CR> - -These mappings for Ctrl-] (right bracket) and Ctrl-\ (backslash) allow you to -place your cursor over the function name or C symbol and quickly query cscope -for any matches. - -Or you may use the following scheme, inspired by Vim/Cscope tutorial from -Cscope Home Page (http://cscope.sourceforge.net/): > - - nmap <C-_>s :cs find s <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>g :cs find g <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>c :cs find c <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>t :cs find t <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>e :cs find e <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>f :cs find f <C-R>=expand("<cfile>")<CR><CR> - nmap <C-_>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR> - nmap <C-_>d :cs find d <C-R>=expand("<cword>")<CR><CR> - nmap <C-_>a :cs find a <C-R>=expand("<cword>")<CR><CR> - - " Using 'CTRL-spacebar' then a search type makes the vim window - " split horizontally, with search result displayed in - " the new window. - - nmap <C-Space>s :scs find s <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>g :scs find g <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>c :scs find c <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>t :scs find t <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>e :scs find e <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>f :scs find f <C-R>=expand("<cfile>")<CR><CR> - nmap <C-Space>i :scs find i ^<C-R>=expand("<cfile>")<CR>$<CR> - nmap <C-Space>d :scs find d <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space>a :scs find a <C-R>=expand("<cword>")<CR><CR> - - " Hitting CTRL-space *twice* before the search type does a vertical - " split instead of a horizontal one - - nmap <C-Space><C-Space>s - \:vert scs find s <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>g - \:vert scs find g <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>c - \:vert scs find c <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>t - \:vert scs find t <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>e - \:vert scs find e <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>i - \:vert scs find i ^<C-R>=expand("<cfile>")<CR>$<CR> - nmap <C-Space><C-Space>d - \:vert scs find d <C-R>=expand("<cword>")<CR><CR> - nmap <C-Space><C-Space>a - \:vert scs find a <C-R>=expand("<cword>")<CR><CR> -< - - vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/if_pyth.txt b/runtime/doc/if_pyth.txt index 9b434e61d7..4c184ddf94 100644 --- a/runtime/doc/if_pyth.txt +++ b/runtime/doc/if_pyth.txt @@ -16,7 +16,7 @@ Commands *python-commands* *:python* *:py* *E263* *E264* *E887* :[range]py[thon] {stmt} Execute Python statement {stmt}. A simple check if - the `:python` command is working: > + the `:python` command is working: >vim :python print "Hello" :[range]py[thon] << [endmarker] @@ -31,7 +31,7 @@ The {endmarker} below the {script} must NOT be preceded by any white space. If [endmarker] is omitted from after the "<<", a dot '.' must be used after {script}, like for the |:append| and |:insert| commands. -Example: > +Example: >vim function! IcecreamInitialize() python << EOF class StrawberryIcecream: @@ -40,7 +40,7 @@ Example: > EOF endfunction -To see what version of Python you have: > +To see what version of Python you have: >vim :python print(sys.version) There is no need to "import sys", it's done by default. @@ -64,12 +64,12 @@ Note: Python is very sensitive to indenting. Make sure the "class" line and is the whole file: "1,$". Examples: -> +>vim :pydo return "%s\t%d" % (line[::-1], len(line)) :pydo if line: return "%4d: %s" % (linenr, line) < One can use `:pydo` in possible conjunction with `:py` to filter a range using -python. For example: > +python. For example: >vim :py3 << EOF needle = vim.eval('@a') @@ -94,12 +94,13 @@ In the case of :pyfile, the code to execute is the contents of the given file. Python commands cannot be used in the |sandbox|. -To pass arguments you need to set sys.argv[] explicitly. Example: > +To pass arguments you need to set sys.argv[] explicitly. Example: >vim :python sys.argv = ["foo", "bar"] :pyfile myscript.py -Here are some examples *python-examples* > +Here are some examples *python-examples* +>vim :python from vim import * :python from string import upper @@ -113,7 +114,7 @@ to the next, just like the Python REPL. *script-here* When using a script language in-line, you might want to skip this when the language isn't supported. Note that this mechanism doesn't work: -> +>vim if has('python') python << EOF this will NOT work! @@ -121,7 +122,7 @@ language isn't supported. Note that this mechanism doesn't work: endif Instead, put the Python command in a function and call that function: -> +>vim if has('python') function DefPython() python << EOF @@ -139,10 +140,10 @@ The vim module *python-vim* Python code gets all of its access to vim (with one exception - see |python-output| below) via the "vim" module. The vim module implements two methods, three constants, and one error object. You need to import the vim -module before using it: > +module before using it: >vim :python import vim -Overview > +Overview >vim :py print "Hello" # displays a message :py vim.command(cmd) # execute an Ex command :py w = vim.windows[n] # gets window "n" @@ -166,10 +167,10 @@ Methods of the "vim" module vim.command(str) *python-command* Executes the vim (ex-mode) command str. Returns None. - Examples: > + Examples: >vim :py vim.command("set tw=72") :py vim.command("%s/aaa/bbb/g") -< The following definition executes Normal mode commands: > +< The following definition executes Normal mode commands: >python def normal(str): vim.command("normal "+str) # Note the use of single quotes to delimit a string containing @@ -177,7 +178,7 @@ vim.command(str) *python-command* normal('"a2dd"aP') < *E659* The ":python" command cannot be used recursively with Python 2.2 and - older. This only works with Python 2.3 and later: > + older. This only works with Python 2.3 and later: >vim :py vim.command("python print 'Hello again Python'") vim.eval(str) *python-eval* @@ -187,7 +188,7 @@ vim.eval(str) *python-eval* - a list if the Vim expression evaluates to a Vim list - a dictionary if the Vim expression evaluates to a Vim dictionary Dictionaries and lists are recursively expanded. - Examples: > + Examples: >vim :py text_width = vim.eval("&tw") :py str = vim.eval("12+12") # NB result is a string! Use # string.atoi() to convert to @@ -215,7 +216,7 @@ Error object of the "vim" module vim.error *python-error* Upon encountering a Vim error, Python raises an exception of type vim.error. - Example: > + Example: >python try: vim.command("put a") except vim.error: @@ -229,7 +230,7 @@ Constants of the "vim" module vim.buffers *python-buffers* A mapping object providing access to the list of vim buffers. The - object supports the following operations: > + object supports the following operations: >vim :py b = vim.buffers[i] # Indexing (read-only) :py b in vim.buffers # Membership test :py n = len(vim.buffers) # Number of elements @@ -237,7 +238,7 @@ vim.buffers *python-buffers* < vim.windows *python-windows* A sequence object providing access to the list of vim windows. The - object supports the following operations: > + object supports the following operations: >vim :py w = vim.windows[i] # Indexing (read-only) :py w in vim.windows # Membership test :py n = len(vim.windows) # Number of elements @@ -251,7 +252,7 @@ vim.windows *python-windows* vim.tabpages *python-tabpages* A sequence object providing access to the list of vim tab pages. The - object supports the following operations: > + object supports the following operations: >vim :py t = vim.tabpages[i] # Indexing (read-only) :py t in vim.tabpages # Membership test :py n = len(vim.tabpages) # Number of elements @@ -277,7 +278,7 @@ vim.current *python-current* switching to given buffer, window or tab page. It is the only way to switch UI objects in python: you can't assign to |python-tabpage|.window attribute. To switch without triggering - autocommands use > + autocommands use >vim py << EOF saved_eventignore = vim.options['eventignore'] vim.options['eventignore'] = 'all' @@ -330,7 +331,7 @@ the list of paths found in 'runtimepath': with this directory in sys.path and vim.path_hooks in sys.path_hooks python will try to load module from {rtp}/python3 and {rtp}/pythonx for each {rtp} found in 'runtimepath'. -Implementation is similar to the following, but written in C: > +Implementation is similar to the following, but written in C: >python from imp import find_module, load_module import vim @@ -461,12 +462,12 @@ The buffer object methods are: numbers s and e |inclusive|. Note that when adding a line it must not contain a line break character '\n'. -A trailing '\n' is allowed and ignored, so that you can do: > +A trailing '\n' is allowed and ignored, so that you can do: >vim :py b.append(f.readlines()) Buffer object type is available using "Buffer" attribute of vim module. -Examples (assume b is the current buffer) > +Examples (assume b is the current buffer) >vim :py print b.name # write the buffer file name :py b[0] = "hello!!!" # replace the top line :py b[:] = None # delete the whole buffer @@ -605,10 +606,10 @@ variants explicitly if Python 3 is required. {script} {endmarker} The `:py3` and `:python3` commands work similar to `:python`. A - simple check if the `:py3` command is working: > + simple check if the `:py3` command is working: >vim :py3 print("Hello") < - To see what version of Python you have: > + To see what version of Python you have: >vim :py3 import sys :py3 print(sys.version) < *:py3file* @@ -619,11 +620,12 @@ variants explicitly if Python 3 is required. The `:py3do` command works similar to `:pydo`. *E880* -Raising SystemExit exception in python isn't endorsed way to quit vim, use: > +Raising SystemExit exception in python isn't endorsed way to quit vim, use: +>vim :py vim.command("qall!") < *has-python* -You can test if Python is available with: > +You can test if Python is available with: >vim if has('pythonx') echo 'there is Python' endif @@ -642,10 +644,10 @@ works with Python 2.6+ and Python 3. As Nvim only supports Python 3, all these commands are now synonymous to their "python3" equivalents. *:pyx* *:pythonx* -`:pyx` and `:pythonx` work the same as `:python3`. To check if `:pyx` works: > +`:pyx` and `:pythonx` work the same as `:python3`. To check if `:pyx` works: >vim :pyx print("Hello") -To see what version of Python is being used: > +To see what version of Python is being used: >vim :pyx import sys :pyx print(sys.version) < @@ -656,7 +658,7 @@ To see what version of Python is being used: > `:pyxdo` works the same as `:py3do`. *has-pythonx* -To check if `pyx*` functions and commands are available: > +To check if `pyx*` functions and commands are available: >vim if has('pythonx') echo 'pyx* commands are available. (Python ' .. &pyx .. ')' endif diff --git a/runtime/doc/if_ruby.txt b/runtime/doc/if_ruby.txt index 47305c65fb..d88f59eb73 100644 --- a/runtime/doc/if_ruby.txt +++ b/runtime/doc/if_ruby.txt @@ -7,7 +7,7 @@ The Ruby Interface to Vim *if_ruby* *ruby* *Ruby* *E266* *E267* *E268* *E269* *E270* *E271* *E272* *E273* -The home page for ruby is http://www.ruby-lang.org/. You can find links for +The home page for ruby is https://www.ruby-lang.org/. You can find links for downloading Ruby there. Type |gO| to see the table of contents. diff --git a/runtime/doc/indent.txt b/runtime/doc/indent.txt index 1a1d8e30b0..f3e196b426 100644 --- a/runtime/doc/indent.txt +++ b/runtime/doc/indent.txt @@ -35,7 +35,7 @@ The rest of this section describes the 'cindent' option. Note that 'cindent' indenting does not work for every code scenario. Vim is not a C compiler: it does not recognize all syntax. One requirement is -that toplevel functions have a '{' in the first column. Otherwise they are +that toplevel functions have a "{" in the first column. Otherwise they are easily confused with declarations. These five options control C program indenting: @@ -60,12 +60,12 @@ used instead. The format of 'cinkeys' and 'indentkeys' is equal. The default is "0{,0},0),0],:,0#,!^F,o,O,e" which specifies that indenting occurs as follows: - "0{" if you type '{' as the first character in a line - "0}" if you type '}' as the first character in a line - "0)" if you type ')' as the first character in a line - "0]" if you type ']' as the first character in a line - ":" if you type ':' after a label or case statement - "0#" if you type '#' as the first character in a line + "0{" if you type "{" as the first character in a line + "0}" if you type "}" as the first character in a line + "0)" if you type ")" as the first character in a line + "0]" if you type "]" as the first character in a line + ":" if you type ":" after a label or case statement + "0#" if you type "#" as the first character in a line "!^F" if you type CTRL-F (which is not inserted) "o" if you type a <CR> anywhere or use the "o" command (not in insert mode!) @@ -74,21 +74,21 @@ occurs as follows: line Characters that can precede each key: *i_CTRL-F* -! When a '!' precedes the key, Vim will not insert the key but will +! When a "!" precedes the key, Vim will not insert the key but will instead reindent the current line. This allows you to define a command key for reindenting the current line. CTRL-F is the default key for this. Be careful if you define CTRL-I for this because CTRL-I is the ASCII code for <Tab>. -* When a '*' precedes the key, Vim will reindent the line before +* When a "*" precedes the key, Vim will reindent the line before inserting the key. If 'cinkeys' contains "*<Return>", Vim reindents the current line before opening a new line. -0 When a zero precedes the key (but appears after '!' or '*') Vim will +0 When a zero precedes the key (but appears after "!" or "*") Vim will reindent the line only if the key is the first character you type in the line. When used before "=" Vim will only reindent the line if there is only white space before the word. -When neither '!' nor '*' precedes the key, Vim reindents the line after you -type the key. So ';' sets the indentation of a line which includes the ';'. +When neither "!" nor "*" precedes the key, Vim reindents the line after you +type the key. So ";" sets the indentation of a line which includes the ";". Special key names: <> Angle brackets mean spelled-out names of keys. For example: "<Up>", @@ -154,8 +154,8 @@ The examples below assume a 'shiftwidth' of 4. eN Add N to the prevailing indent inside a set of braces if the opening brace at the End of the line (more precise: is not the first character in a line). This is useful if you want a - different indent when the '{' is at the start of the line from - when '{' is at the end of the line. (default 0). + different indent when the "{" is at the start of the line from + when "{" is at the end of the line. (default 0). cino= cino=e2 cino=e-2 > if (cond) { if (cond) { if (cond) { @@ -169,8 +169,8 @@ The examples below assume a 'shiftwidth' of 4. *cino-n* nN Add N to the prevailing indent for a statement after an "if", "while", etc., if it is NOT inside a set of braces. This is - useful if you want a different indent when there is no '{' - before the statement from when there is a '{' before it. + useful if you want a different indent when there is no "{" + before the statement from when there is a "{" before it. (default 0). cino= cino=n2 cino=n-2 > @@ -193,7 +193,7 @@ The examples below assume a 'shiftwidth' of 4. int foo; int foo; int foo; < *cino-{* - {N Place opening braces N characters from the prevailing indent. + `{N` Place opening braces N characters from the prevailing indent. This applies only for opening braces that are inside other braces. (default 0). @@ -203,7 +203,7 @@ The examples below assume a 'shiftwidth' of 4. foo; foo; foo; < *cino-}* - }N Place closing braces N characters from the matching opening + `}N` Place closing braces N characters from the matching opening brace. (default 0). cino= cino={2,}-0.5s cino=}2 > @@ -724,7 +724,7 @@ Fortran with (possibly multiple) loops ending on a labelled executable statement of almost arbitrary type. Correct indentation requires compiler-quality parsing. Old code with do loops ending on labelled statements of arbitrary type can be indented with elaborate programs such as Tidy -(http://www.unb.ca/chem/ajit/f_tidy.htm). Structured do/continue loops are +(https://www.unb.ca/chem/ajit/f_tidy.htm). Structured do/continue loops are also left unindented because continue statements are also used for purposes other than ending a do loop. Programs such as Tidy can convert structured do/continue loops to the do/enddo form. Do loops of the do/enddo variety can @@ -846,7 +846,7 @@ own 'formatoptions'): > Else, 't' will be removed from the 'formatoptions' string and "qrowcb" will be added, see |fo-table| for more information. -------------- + *PHP_outdentSLComments* To add extra indentation to single-line comments: > @@ -858,7 +858,7 @@ Only single-line comments will be affected such as: > # Comment // Comment /* Comment */ -------------- +< *PHP_default_indenting* To add extra indentation to every PHP lines with N being the number of @@ -878,18 +878,17 @@ For example, with N = 1, this will give: $command_hist = TRUE; ?> (Notice the extra indentation between the PHP container markers and the code) -------------- *PHP_outdentphpescape* To indent PHP escape tags as the surrounding non-PHP code (only affects the PHP escape tags): > :let g:PHP_outdentphpescape = 0 -------------- +< *PHP_removeCRwhenUnix* To automatically remove '\r' characters when the 'fileformat' is set to Unix: > :let g:PHP_removeCRwhenUnix = 1 -------------- +< *PHP_BracesAtCodeLevel* To indent braces at the same level than the code they contain: > @@ -908,7 +907,6 @@ Instead of: > NOTE: Indenting will be a bit slower if this option is used because some optimizations won't be available. -------------- *PHP_vintage_case_default_indent* To indent 'case:' and 'default:' statements in switch() blocks: > @@ -918,7 +916,6 @@ In PHP braces are not required inside 'case/default' blocks therefore 'case:' and 'default:' are indented at the same level than the 'switch()' to avoid meaningless indentation. You can use the above option to return to the traditional way. -------------- *PHP_noArrowMatching* By default the indent script will indent multi-line chained calls by matching @@ -927,17 +924,16 @@ the position of the '->': > $user_name_very_long->name() ->age() ->info(); - +< You can revert to the classic way of indenting by setting this option to 1: > :let g:PHP_noArrowMatching = 1 - +< You will obtain the following result: > $user_name_very_long->name() ->age() ->info(); - -------------- +< *PHP_IndentFunctionCallParameters* Extra indentation levels to add to parameters in multi-line function calls. > @@ -954,14 +950,13 @@ Function call arguments will indent 1 extra level. For two-space indentation: > $and_that ); } - -------------- +< *PHP_IndentFunctionDeclarationParameters* Extra indentation levels to add to arguments in multi-line function definitions. > let g:PHP_IndentFunctionDeclarationParameters = 1 - +< Function arguments in declarations will indent 1 extra level. For two-space indentation: > @@ -974,30 +969,46 @@ indentation: > $and_that ); } - +< 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. +The amount of indent can be set with the `g:python_indent` |Dictionary|, which +needs to be created before adding the items: > + let g:python_indent = {} +The examples given are the defaults. Note that the dictionary values are set +to an expression, so that you can change the value of 'shiftwidth' later +without having to update these values. 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* @@ -1129,7 +1140,6 @@ to the vimrc file, which causes the previous alignment example to change: > ); END ENTITY sync; ----------------------------------------- Alignment of right-hand side assignment "<=" statements are performed by default. This causes the following alignment example: > @@ -1148,7 +1158,6 @@ to the vimrc file, which causes the previous alignment example to change: > (sig_b OR sig_c)) OR (bus_a(0) AND sig_d); ----------------------------------------- Full-line comments (lines that begin with "--") are indented to be aligned with the very previous line's comment, PROVIDED that a whitespace follows after diff --git a/runtime/doc/index.txt b/runtime/doc/index.txt index 7f3ef20762..a6aa036b55 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. @@ -21,7 +20,7 @@ For a complete listing of all help items see |help-tags|. 1. Insert mode *insert-index* 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 +60,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 +78,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 @@ -184,7 +183,7 @@ SECTION a section that possibly starts with '}' instead of '{' 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 +453,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* @@ -469,7 +468,7 @@ tag char note action in Normal mode ~ 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 @@ -511,7 +510,7 @@ tag command action in op-pending and Visual mode ~ 2.2 Window commands *CTRL-W* 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" @@ -609,7 +608,7 @@ tag command action in Normal mode ~ 2.3 Square bracket commands *[* *]* 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 @@ -699,8 +698,8 @@ tag char note action in Normal mode ~ 2.4 Commands starting with 'g' *g* 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 @@ -802,7 +801,7 @@ tag char note action in Normal mode ~ 2.5 Commands starting with 'z' *z* 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 @@ -876,7 +875,7 @@ tag char note action in Normal mode ~ 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 @@ -888,7 +887,7 @@ Most commands in Visual mode are the same as in Normal mode. The ones listed 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 @@ -1008,7 +1007,7 @@ Normal characters are inserted at the current cursor position. 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,23 +1110,23 @@ 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 []. 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 |:!!| :!! repeat last ":!" command |:#| :# same as ":number" |:&| :& repeat last ":substitute" -|:star| :* execute contents of a register +|:star| :* use the last Visual area, like :'<,'> |:<| :< shift lines one 'shiftwidth' left -|:=| := print the cursor line number +|:=| := print the last line number |:>| :> shift lines one 'shiftwidth' right |:@| :@ execute contents of a register |:@@| :@@ repeat the previous ":@" @@ -1209,8 +1208,8 @@ tag command action ~ |:cgetfile| :cg[etfile] read file with error messages |:changes| :changes print the change list |:chdir| :chd[ir] change directory -|:checkhealth| :checkh[ealth] run healthchecks -|:checkpath| :che[ckpath] list included files +|:checkhealth| :che[ckhealth] run healthchecks +|:checkpath| :checkp[ath] list included files |:checktime| :checkt[ime] check timestamp of loaded buffers |:chistory| :chi[story] list the error lists |:clast| :cla[st] go to the specified error, default last one @@ -1240,8 +1239,6 @@ tag command action ~ |:cpfile| :cpf[ile] go to last error in previous file |:cquit| :cq[uit] quit Vim with an error code |:crewind| :cr[ewind] go to the specified error, default first one -|:cscope| :cs[cope] execute cscope command -|:cstag| :cst[ag] use cscope to jump to a tag |:cunmap| :cu[nmap] like ":unmap" but for Command-line mode |:cunabbrev| :cuna[bbrev] like ":unabbrev" but for Command-line mode |:cunmenu| :cunme[nu] remove menu for Command-line mode @@ -1313,7 +1310,6 @@ tag command action ~ |:grepadd| :grepa[dd] like :grep, but append to current list |:gui| :gu[i] start the GUI |:gvim| :gv[im] start the GUI -|:hardcopy| :ha[rdcopy] send text to the printer |:help| :h[elp] open a help window |:helpclose| :helpc[lose] close one help window |:helpgrep| :helpg[rep] like ":grep" but searches help files @@ -1321,6 +1317,7 @@ tag command action ~ |:highlight| :hi[ghlight] specify highlighting methods |:hide| :hid[e] hide current buffer for a command |:history| :his[tory] print a history list +|:horizontal| :hor[izontal] following window command work horizontally |:insert| :i[nsert] insert text |:iabbrev| :ia[bbrev] like ":abbrev" but for Insert mode |:iabclear| :iabc[lear] like ":abclear" but for Insert mode @@ -1365,7 +1362,6 @@ tag command action ~ |:lcd| :lc[d] change directory locally |:lchdir| :lch[dir] change directory locally |:lclose| :lcl[ose] close location window -|:lcscope| :lcs[cope] like ":cscope" but uses location list |:ldo| :ld[o] execute command in valid location list entries |:lfdo| :lfd[o] execute command in each file in location list |:left| :le[ft] left align lines @@ -1546,7 +1542,6 @@ tag command action ~ buffer list |:scriptnames| :scr[iptnames] list names of all sourced Vim scripts |:scriptencoding| :scripte[ncoding] encoding used in sourced Vim script -|:scscope| :scs[cope] split window and execute cscope command |:set| :se[t] show or set options |:setfiletype| :setf[iletype] set 'filetype', unless it was set already |:setglobal| :setg[lobal] show global values of options @@ -1637,6 +1632,7 @@ tag command action ~ |:topleft| :to[pleft] make split window appear at top or far left |:tprevious| :tp[revious] jump to previous matching tag |:trewind| :tr[ewind] jump to first matching tag +|:trust| :trust add or remove file from trust database |:try| :try execute commands, abort on error or exception |:tselect| :ts[elect] list matching tags and select one |:tunmap| :tunma[p] like ":unmap" but for |Terminal-mode| diff --git a/runtime/doc/insert.txt b/runtime/doc/insert.txt index 6b0899334b..e608b431f2 100644 --- a/runtime/doc/insert.txt +++ b/runtime/doc/insert.txt @@ -257,8 +257,8 @@ CTRL-] Trigger abbreviation, without inserting a character. *i_<Insert>* <Insert> Toggle between Insert and Replace mode. ------------------------------------------------------------------------ +----------------------------------------------------------------------- *i_backspacing* The effect of the <BS>, CTRL-W, and CTRL-U depend on the 'backspace' option (unless 'revins' is set). This is a comma-separated list of items: @@ -378,6 +378,7 @@ CTRL-G u close undo sequence, start new change *i_CTRL-G_u* CTRL-G U don't start a new undo block with the next *i_CTRL-G_U* left/right cursor movement, if the cursor stays within the same line + ----------------------------------------------------------------------- The CTRL-O command sometimes has a side effect: If the cursor was beyond the @@ -650,9 +651,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 +662,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 @@ -857,29 +858,27 @@ invoked and what it should return. Here is an example that uses the "aiksaurus" command (provided by Magnus Groß): > - func Thesaur(findstart, base) - if a:findstart - let line = getline('.') - let start = col('.') - 1 - while start > 0 && line[start - 1] =~ '\a' - let start -= 1 - endwhile - return start - else - let res = [] - let h = '' - for l in split(system('aiksaurus ' .. shellescape(a:base)), '\n') - if l[:3] == '=== ' - let h = substitute(l[4:], ' =*$', '', '') - elseif l[0] =~ '\a' - call extend(res, map(split(l, ', '), {_, val -> {'word': val, 'menu': '('.h.')'}})) - endif - endfor - return res - endif - endfunc - - set thesaurusfunc=Thesaur + func Thesaur(findstart, base) + if a:findstart + return searchpos('\<', 'bnW', line('.'))[1] - 1 + endif + let res = [] + let h = '' + for l in systemlist('aiksaurus ' .. shellescape(a:base)) + if l[:3] == '=== ' + let h = '(' .. substitute(l[4:], ' =*$', ')', '') + elseif l ==# 'Alphabetically similar known words are: ' + let h = "\U0001f52e" + elseif l[0] =~ '\a' || (h ==# "\U0001f52e" && l[0] ==# "\t") + call extend(res, map(split(substitute(l, '^\t', '', ''), ', '), {_, val -> {'word': val, 'menu': h}})) + endif + endfor + return res + endfunc + + if exists('+thesaurusfunc') + set thesaurusfunc=Thesaur + endif Completing keywords in the current and included files *compl-keyword* @@ -1126,7 +1125,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 ... @@ -1349,16 +1349,8 @@ Completion of C code requires a tags file. You should use Universal/ Exuberant ctags, because it adds extra information that is needed for completion. You can find it here: Universal Ctags: https://ctags.io - Exuberant Ctags: http://ctags.sourceforge.net - -Universal Ctags is preferred, Exuberant Ctags is no longer being developed. -For Exuberant ctags, version 5.6 or later is recommended. For version 5.5.4 -you should add a patch that adds the "typename:" field: - ftp://ftp.vim.org/pub/vim/unstable/patches/ctags-5.5.4.patch -A compiled .exe for MS-Windows can be found at: - http://ctags.sourceforge.net/ - https://github.com/universal-ctags/ctags-win32 +Universal Ctags is preferred, Exuberant Ctags is no longer maintained. If you want to complete system functions you can do something like this. Use ctags to generate a tags file for all the system header files: > @@ -1458,14 +1450,14 @@ DOM compatibility At the moment (beginning of 2006) there are two main browsers - MS Internet Explorer and Mozilla Firefox. These two applications are covering over 90% of market. Theoretically standards are created by W3C organisation -(http://www.w3c.org) but they are not always followed/implemented. - +(https://www.w3.org/) but they are not always followed/implemented. +> IE FF W3C Omni completion ~ +/- +/- + + ~ + + - + ~ + - - - ~ - + - - ~ - +< Regardless from state of implementation in browsers but if element is defined in standards, completion plugin will place element in suggestion list. When both major engines implemented element, even if this is not in standards it @@ -1479,7 +1471,6 @@ external files and for class aware completion. You should use Universal/ Exuberant ctags version 5.5.4 or newer. You can find it here: Universal Ctags: https://ctags.io - Exuberant Ctags: http://ctags.sourceforge.net Script completes: @@ -1519,7 +1510,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 +1524,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 +1750,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. @@ -1778,12 +1769,12 @@ DTD -> Vim *dtd2vim* On |www| is the script |dtd2vim| which parses DTD and creates an XML data file for Vim XML omni completion. - dtd2vim: http://www.vim.org/scripts/script.php?script_id=1462 + dtd2vim: https://www.vim.org/scripts/script.php?script_id=1462 Check the beginning of that file for usage details. The script requires perl and: - perlSGML: http://savannah.nongnu.org/projects/perlsgml + perlSGML: https://savannah.nongnu.org/projects/perlsgml Commands diff --git a/runtime/doc/intro.txt b/runtime/doc/intro.txt index ae80935032..6bf6850ccf 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* @@ -373,7 +373,7 @@ notation meaning equivalent decimal value(s) ~ <M-…> alt-key or meta-key *META* *ALT* *<M-* <A-…> same as <M-…> *<A-* <D-…> command-key or "super" key *<D-* ------------------------------------------------------------------------ +----------------------------------------------------------------------- ~ Note: @@ -408,14 +408,18 @@ the ":map" command. The rules are: The <> notation uses <lt> to escape the special meaning of key names. Using a backslash also works, but only when 'cpoptions' does not include the 'B' flag. -Examples for mapping CTRL-H to the six characters "<Home>": > +Examples for mapping CTRL-H to the six characters "<Home>": >vim :imap <C-H> \<Home> :imap <C-H> <lt>Home> The first one only works when the 'B' flag is not in 'cpoptions'. The second one always works. -To get a literal "<lt>" in a mapping: > +To get a literal "<lt>" in a mapping: >vim :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* @@ -516,39 +520,39 @@ CTRL-O in Insert mode you get a beep but you are still in Insert mode, type TO mode ~ Normal Visual Select Insert Replace Cmd-line Ex ~ FROM mode ~ -Normal v V ^V *4 *1 R gR : / ? ! Q -Visual *2 ^G c C -- : -- -Select *5 ^O ^G *6 -- -- -- +Normal v V ^V `*4` *1 R gR : / ? ! Q +Visual `*2` ^G c C -- : -- +Select `*5` ^O ^G `*6` -- -- -- Insert <Esc> -- -- <Insert> -- -- Replace <Esc> -- -- <Insert> -- -- -Command-line *3 -- -- :start -- -- +Command-line `*3` -- -- :start -- -- 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* @@ -585,26 +589,26 @@ Lines longer than the window width will wrap, unless the 'wrap' option is off If the window has room after the last line of the buffer, Vim will show '~' in the first column of the last lines in the window, like this: - +> +-----------------------+ |some line | |last line | |~ | |~ | +-----------------------+ - +< Thus the '~' lines indicate that the end of the buffer was reached. If the last line in a window doesn't fit, Vim will indicate this with a '@' in the first column of the last lines in the window, like this: - +> +-----------------------+ |first line | |second line | |@ | |@ | +-----------------------+ - +< Thus the '@' lines indicate that there is a line that doesn't fit in the window. @@ -612,14 +616,14 @@ When the "lastline" flag is present in the 'display' option, you will not see '@' characters at the left side of window. If the last line doesn't fit completely, only the part that fits is shown, and the last three characters of the last line are replaced with "@@@", like this: - +> +-----------------------+ |first line | |second line | |a very long line that d| |oesn't fit in the wi@@@| +-----------------------+ - +< If there is a single line that is too long to fit in the window, this is a special situation. Vim will show only part of the line, around where the cursor is. There are no special characters shown, so that you can edit all @@ -700,9 +704,9 @@ Definitions *definitions* *jargon* A screen contains one or more windows, separated by status lines and with the command line at the bottom. - +> +-------------------------------+ -screen | window 1 | window 2 | + screen | window 1 | window 2 | | | | | | | |= status line =|= status line =| @@ -712,7 +716,7 @@ screen | window 1 | window 2 | |==== status line ==============| |command line | +-------------------------------+ - +< The command line is also used for messages. It scrolls up the screen when there is not enough room in the command line. diff --git a/runtime/doc/job_control.txt b/runtime/doc/job_control.txt index 6a9d865c40..37a4e2ebb1 100644 --- a/runtime/doc/job_control.txt +++ b/runtime/doc/job_control.txt @@ -30,7 +30,7 @@ Usage *job-control-usage* To control jobs, use the "job…" family of functions: |jobstart()|, |jobstop()|, etc. -Example: > +Example: >vim function! s:OnEvent(job_id, data, event) dict if a:event == 'stdout' @@ -51,7 +51,7 @@ Example: > let job1 = jobstart(['bash'], extend({'shell': 'shell 1'}, s:callbacks)) let job2 = jobstart(['bash', '-c', 'for i in {1..10}; do echo hello $i!; sleep 1; done'], extend({'shell': 'shell 2'}, s:callbacks)) -To test the above script, copy it to a file ~/foo.vim and run it: > +To test the above script, copy it to a file ~/foo.vim and run it: >bash nvim -u ~/foo.vim < Description of what happens: @@ -75,7 +75,7 @@ Arguments passed to on_exit callback: will not trigger the on_stdout/on_stderr callback (but if the process ends, the on_exit callback will be invoked). For example, "ruby -e" buffers output, so small strings will be - buffered unless "auto-flushing" ($stdout.sync=true) is enabled. > + buffered unless "auto-flushing" ($stdout.sync=true) is enabled. >vim function! Receive(job_id, data, event) echom printf('%s: %s',a:event,string(a:data)) endfunction @@ -92,7 +92,7 @@ Arguments passed to on_exit callback: - `abc\nefg` may arrive as `['abc', '']`, `['efg']` or `['abc']`, `['','efg']`, or even `['ab']`, `['c','efg']`. Easy way to deal with this: initialize a list as `['']`, then append - to it as follows: > + to it as follows: >vim let s:chunks = [''] func! s:on_stdout(job_id, data, event) dict let s:chunks[-1] .= a:data[0] @@ -101,7 +101,7 @@ Arguments passed to on_exit callback: < The |jobstart-options| dictionary is passed as |self| to the callback. -The above example could be written in this "object-oriented" style: > +The above example could be written in this "object-oriented" style: >vim let Shell = {} @@ -129,16 +129,16 @@ The above example could be written in this "object-oriented" style: > let instance = Shell.new('bomb', \ 'for i in $(seq 9 -1 1); do echo $i 1>&$((i % 2 + 1)); sleep 1; done') < -To send data to the job's stdin, use |chansend()|: > +To send data to the job's stdin, use |chansend()|: >vim :call chansend(job1, "ls\n") :call chansend(job1, "invalid-command\n") :call chansend(job1, "exit\n") < -A job may be killed with |jobstop()|: > +A job may be killed with |jobstop()|: >vim :call jobstop(job1) < A job may be killed at any time with the |jobstop()| function: -> +>vim :call jobstop(job1) < Individual streams can be closed without killing the job, see |chanclose()|. diff --git a/runtime/doc/lsp-extension.txt b/runtime/doc/lsp-extension.txt index 6e9ad940c7..fe72e9eb18 100644 --- a/runtime/doc/lsp-extension.txt +++ b/runtime/doc/lsp-extension.txt @@ -6,7 +6,7 @@ The `vim.lsp` Lua module is a framework for building LSP plugins. 1. Start with |vim.lsp.start_client()| and |vim.lsp.buf_attach_client()|. - 2. Peek at the API: > + 2. Peek at the API: >vim :lua print(vim.inspect(vim.lsp)) < 3. See |lsp-extension-example| for a full example. @@ -30,7 +30,7 @@ The example will: 3. Create a new LSP for that root directory if one doesn't exist. 4. Attach the buffer to the client for that root directory. -> +>lua -- Some path manipulation utilities local function is_dir(filename) local stat = vim.loop.fs_stat(filename) diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 7fc0daa0ca..215515a2d9 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -33,40 +33,40 @@ Follow these steps to get LSP features: 2. Configure the LSP client per language server. A minimal example: -> +>lua vim.lsp.start({ name = 'my-server-name', cmd = {'name-of-language-server-executable'}, 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|. -< + *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 additional keymaps. It's recommended to setup them in a |LspAttach| autocmd to ensure they're only active if there is a LSP client running. An example: -> +>lua vim.api.nvim_create_autocmd('LspAttach', { callback = function(args) vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = args.buf }) @@ -86,7 +86,7 @@ The most used functions are: Not all language servers provide the same capabilities. To ensure you only set keymaps if the language server supports a feature, you can guard the keymap calls behind capability checks: -> +>lua vim.api.nvim_create_autocmd('LspAttach', { callback = function(args) local client = vim.lsp.get_client_by_id(args.data.client_id) @@ -100,7 +100,7 @@ calls behind capability checks: To learn what capabilities are available you can run the following command in a buffer with a started LSP client: -> +>vim :lua =vim.lsp.get_active_clients()[1].server_capabilities < @@ -110,14 +110,14 @@ Full list of features provided by default can be found in |lsp-buf|. FAQ *lsp-faq* - Q: How to force-reload LSP? - A: Stop all clients, then reload the buffer. > + A: Stop all clients, then reload the buffer. >vim :lua vim.lsp.stop_client(vim.lsp.get_active_clients()) :edit - Q: Why isn't completion working? A: In the buffer where you want to use LSP, check that 'omnifunc' is set to - "v:lua.vim.lsp.omnifunc": > + "v:lua.vim.lsp.omnifunc": >vim :verbose set omnifunc? @@ -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: > + E.g. code formatting: >vim " 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* @@ -161,7 +162,7 @@ to the given buffer. |lsp-buf| LSP request/response handlers are implemented as Lua functions (see |lsp-handler|). The |vim.lsp.handlers| table defines default handlers used -when creating a new client. Keys are LSP method names: > +when creating a new client. Keys are LSP method names: >vim :lua print(vim.inspect(vim.tbl_keys(vim.lsp.handlers))) < @@ -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: > @@ -289,7 +291,7 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method To configure the behavior of |vim.lsp.diagnostic.on_publish_diagnostics()|, consider the following example, where a new |lsp-handler| is created using - |vim.lsp.with()| that no longer generates signs for the diagnostics: > + |vim.lsp.with()| that no longer generates signs for the diagnostics: >lua vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { @@ -299,7 +301,7 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method ) < To enable signs, use |vim.lsp.with()| again to create and assign a new - |lsp-handler| to |vim.lsp.handlers| for the associated method: > + |lsp-handler| to |vim.lsp.handlers| for the associated method: >lua vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { @@ -309,7 +311,7 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method ) < To configure a handler on a per-server basis, you can use the {handlers} key - for |vim.lsp.start_client()| > + for |vim.lsp.start_client()| >lua vim.lsp.start_client { ..., -- Other configuration omitted. @@ -323,7 +325,8 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method }, } < - or if using 'nvim-lspconfig', you can use the {handlers} key of `setup()`: > + or if using "nvim-lspconfig", you can use the {handlers} key of `setup()`: + >lua require('lspconfig').rust_analyzer.setup { handlers = { @@ -337,8 +340,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: >lua local on_references = vim.lsp.handlers["textDocument/references"] vim.lsp.handlers["textDocument/references"] = vim.lsp.with( @@ -355,14 +358,14 @@ Handlers can be set by: vim.lsp.handlers is a global table that contains the default mapping of |lsp-method| names to |lsp-handlers|. - To override the handler for the `"textDocument/definition"` method: > + To override the handler for the `"textDocument/definition"` method: >lua 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: > + For example: >lua vim.lsp.start_client { ..., -- Other configuration omitted. @@ -374,7 +377,7 @@ Handlers can be set by: - The {handler} parameter for |vim.lsp.buf_request()|. This will set the |lsp-handler| ONLY for the current request. - For example: > + For example: >lua vim.lsp.buf_request( 0, @@ -401,7 +404,7 @@ and helper functions for creating protocol-related objects. https://github.com/microsoft/language-server-protocol/raw/gh-pages/_specifications/specification-3-14.md For example `vim.lsp.protocol.ErrorCodes` allows reverse lookup by number or -name: > +name: >lua vim.lsp.protocol.TextDocumentSyncKind.Full == 1 vim.lsp.protocol.TextDocumentSyncKind[1] == "Full" @@ -424,7 +427,7 @@ For the format of the notification message, see: - `context` table|nil. `ctx` from |lsp-handler| This table can be used with vim.fn.setqflist or vim.fn.setloclist. E.g.: -> +>lua local function on_list(options) vim.fn.setqflist({}, ' ', options) vim.api.nvim_command('cfirst') @@ -434,7 +437,7 @@ This table can be used with vim.fn.setqflist or vim.fn.setloclist. E.g.: vim.lsp.buf.references(nil, {on_list=on_list}) < If you prefer loclist do something like this: -> +>lua local function on_list(options) vim.fn.setloclist(0, {}, ' ', options) vim.api.nvim_command('lopen') @@ -468,7 +471,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* @@ -485,7 +488,7 @@ EVENTS *lsp-events* *LspAttach* After an LSP client attaches to a buffer. The |autocmd-pattern| is the name of the buffer. When used from Lua, the client ID is passed to the -callback in the "data" table. Example: > +callback in the "data" table. Example: >lua vim.api.nvim_create_autocmd("LspAttach", { callback = function(args) @@ -503,7 +506,7 @@ callback in the "data" table. Example: > *LspDetach* Just before an LSP client detaches from a buffer. The |autocmd-pattern| is the name of the buffer. When used from Lua, the client ID is passed to the -callback in the "data" table. Example: > +callback in the "data" table. Example: >lua vim.api.nvim_create_autocmd("LspDetach", { callback = function(args) @@ -513,7 +516,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 @@ -523,7 +526,7 @@ LspRequest *LspRequest* After a change to the active set of pending LSP requests. See {requests} in |vim.lsp.client|. -Example: > +Example: >vim autocmd User LspProgressUpdate redrawstatus autocmd User LspRequest redrawstatus < @@ -538,8 +541,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 +550,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|nil) The number of the buffer + • {method} (string) Name of the request method + • {params} (any) Arguments to send to the server Return: ~ true if any client returns true; false otherwise @@ -575,10 +578,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} (table|nil) Parameters to send to the server + • {callback} (function) The callback to call when all requests are finished. Return: ~ @@ -594,11 +597,11 @@ 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 - milliseconds to wait for a result. + • {bufnr} (number) Buffer handle, or 0 for current. + • {method} (string) LSP method name + • {params} (table|nil) Parameters to send to the server + • {timeout_ms} (number|nil) Maximum time in milliseconds to wait for a + result. Defaults to 1000 Return: ~ Map of client_id:request_result. On timeout, cancel or error, returns @@ -665,7 +668,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,10 +678,10 @@ 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: > + number as arguments. Example: >lua vim.lsp.for_each_buffer_client(0, function(client, client_id, bufnr) print(vim.inspect(client)) @@ -695,7 +698,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 +707,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 +722,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 +747,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} (number) 0 or 1, decides behavior + • {base} (number) findstart=0, text to match against Return: ~ (number) Decided by {findstart}: @@ -767,7 +770,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| @@ -777,173 +780,170 @@ start({config}, {opts}) *vim.lsp.start()* running client if one is found matching `name` and `root_dir`. Attaches the current buffer to the client. - Example: -> + Example: >lua - vim.lsp.start({ - name = 'my-server-name', - cmd = {'name-of-language-server-executable'}, - root_dir = vim.fs.dirname(vim.fs.find({'pyproject.toml', 'setup.py'}, { upward = true })[1]), - }) + vim.lsp.start({ + name = 'my-server-name', + cmd = {'name-of-language-server-executable'}, + root_dir = vim.fs.dirname(vim.fs.find({'pyproject.toml', 'setup.py'}, { upward = true })[1]), + }) < - See |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. - - `cmd` the command as list - used to start the language server. The command must - be present in the `$PATH` environment variable or an absolute path to the executable. Shell - 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 - `pyproject.toml` or `setup.py` file is found. - - `workspace_folders` a list of { uri:string, name: string } tables. The - project root folders used by the language server. If `nil` the property is - derived from the `root_dir` for convenience. + See |vim.lsp.start_client()| for all available options. The most important + are: + + • `name` arbitrary name for the LSP client. Should be unique per language + server. + • `cmd` command (in list form) used to start the language server. Must be + absolute, or found on `$PATH`. Shell 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 `pyproject.toml` or `setup.py` file is found. + • `workspace_folders` list of `{ uri:string, name: string }` tables + specifying the project root folders used by the language server. If + `nil` the property is derived from `root_dir` for convenience. Language servers use this information to discover metadata like the dependencies of your project and they tend to index the contents within 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. - Parameter `cmd` is required. - - 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 - the `cmd` process. Not related to `root_dir`. - {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"; } + Field `cmd` in {config} is required. + + Parameters: ~ + • {config} (table) Configuration for the server: + • 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 + 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 - 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 - 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 - by |vim.lsp.protocol.make_client_capabilities()|, - passed to the language server on initialization. - Hint: use make_client_capabilities() and modify - its result. - • 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 - |lsp-handler| - {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 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 - `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 - string. Defaults to the filetype. - {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 - 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. - Use `vim.lsp.rpc.client_errors[code]` to get - human-friendly name. - {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 - after LSP "initialize", where `result` is a table - of `capabilities` and anything else the server - may send. For example, clangd sends - `initialize_result.offsetEncoding` if - `capabilities.offsetEncoding` was sent to it. You - can only modify the `client.offset_encoding` here - before any notifications are sent. Most language - servers expect to be sent client specified - settings after initialization. Neovim does not - 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 - 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 - attaches to a buffer. - {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 - (experimental) flags are: - • allow_incremental_sync (bool, default true): - Allow using incremental sync for buffer edits - • debounce_text_changes (number, default 150): - Debounce didChange 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. - {root_dir} (string) Directory where the LSP server will base - its workspaceFolders, rootUri, and rootPath on - initialization. + • 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 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 by |vim.lsp.protocol.make_client_capabilities()|, + passed to the language server on initialization. Hint: use + make_client_capabilities() and modify its result. + • 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 + |lsp-handler| + • 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 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 `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 string. Defaults to the filetype. + • 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 + 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. Use + `vim.lsp.rpc.client_errors[code]` to get human-friendly + name. + • 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 + after LSP "initialize", where `result` is a table of + `capabilities` and anything else the server may send. For + example, clangd sends `initialize_result.offsetEncoding` + if `capabilities.offsetEncoding` was sent to it. You can + only modify the `client.offset_encoding` here before any + notifications are sent. Most language servers expect to be + sent client specified settings after initialization. + Neovim does not 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 + 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 + attaches to a buffer. + • 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 + (experimental) flags are: + • allow_incremental_sync (bool, default true): Allow using + incremental sync for buffer edits + • debounce_text_changes (number, default 150): Debounce + didChange 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. + + • root_dir: (string) Directory where the LSP server will + base its workspaceFolders, rootUri, and rootPath on + initialization. Return: ~ Client id. |vim.lsp.get_client_by_id()| Note: client may not be fully @@ -953,19 +953,18 @@ start_client({config}) *vim.lsp.start_client()* stop_client({client_id}, {force}) *vim.lsp.stop_client()* Stops a client(s). - You can also use the `stop()` function on a |vim.lsp.client| object. To - stop all clients: -> + You can also use the `stop()` function on a |vim.lsp.client| object. To stop all clients: >lua - vim.lsp.stop_client(vim.lsp.get_active_clients()) + vim.lsp.stop_client(vim.lsp.get_active_clients()) < By default asks the server to shutdown, unless stop was requested already 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} number|table id or |vim.lsp.client| object, or list + thereof + • {force} (boolean|nil) shutdown forcefully tagfunc({...}) *vim.lsp.tagfunc()* Provides an interface between the built-in client and 'tagfunc'. @@ -976,8 +975,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} (string) Pattern used to find a workspace symbol + • {flags} (string) See |tag-function| Return: ~ A list of matching tags @@ -986,8 +985,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,13 +1005,15 @@ 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. • only (table|nil): List of LSP `CodeActionKind`s used to filter the code actions. Most language servers support values like `refactor` or `quickfix`. + • triggerKind (number|nil): The reason why code actions + were requested. • filter: (function|nil) Predicate taking an `CodeAction` and returning a boolean. @@ -1027,19 +1028,20 @@ code_action({options}) *vim.lsp.buf.code_action()* See also: ~ https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction + vim.lsp.protocol.constants.CodeActionTriggerKind completion({context}) *vim.lsp.buf.completion()* Retrieves the completion items at the current cursor position. Can only be 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 +1050,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 +1060,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 @@ -1067,22 +1069,22 @@ definition({options}) *vim.lsp.buf.definition()* document_highlight() *vim.lsp.buf.document_highlight()* Send request to the server to resolve document highlights for the current text document position. This request can be triggered by a key mapping or - by events such as `CursorHold`, e.g.: -> - autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() - autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() - autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() + by events such as `CursorHold` , e.g.: >vim + autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() + autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() + autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() < 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 +1092,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 +1102,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 @@ -1114,12 +1116,12 @@ format({options}) *vim.lsp.buf.format()* buffer (0). • filter (function|nil): Predicate used to filter clients. Receives a client as argument and must return a boolean. - Clients matching the predicate are included. Example: • > + Clients matching the predicate are included. Example: • >lua - -- Never request typescript-language-server for formatting - vim.lsp.buf.format { - filter = function(client) return client.name ~= "tsserver" end - } + -- Never request typescript-language-server for formatting + vim.lsp.buf.format { + filter = function(client) return client.name ~= "tsserver" end + } < • async boolean|nil If true the method won't block. Defaults to false. Editing the buffer while formatting @@ -1128,59 +1130,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 +1145,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 +1160,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|nil) Context for the request + • {options} (table|nil) additional options • on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -1256,9 +1184,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 +1208,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 +1222,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,14 +1236,14 @@ 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}) |lsp-handler| for the method "textDocument/publishDiagnostics" See |vim.diagnostic.config()| for configuration options. Handler-specific - configuration can be set using |vim.lsp.with()|: > + configuration can be set using |vim.lsp.with()|: >lua vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { @@ -1337,25 +1265,32 @@ on_publish_diagnostics({_}, {result}, {ctx}, {config}) < Parameters: ~ - {config} (table) Configuration table (see |vim.diagnostic.config()|). + • {config} (table) Configuration table (see |vim.diagnostic.config()|). ============================================================================== Lua module: vim.lsp.codelens *lsp-codelens* +clear({client_id}, {bufnr}) *vim.lsp.codelens.clear()* + Clear the lenses + + Parameters: ~ + • {client_id} (number|nil) filter by client_id. All clients if nil + • {bufnr} (number|nil) filter by buffer. All buffers if nil + 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[]`) @@ -1368,8 +1303,9 @@ refresh() *vim.lsp.codelens.refresh()* Refresh the codelens for the current buffer It is recommended to trigger this using an autocmd or via keymap. -> - autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() + + Example: >vim + autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() < run() *vim.lsp.codelens.run()* @@ -1379,27 +1315,89 @@ 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) + + +============================================================================== +Lua module: vim.lsp.semantic_tokens *lsp-semantic_tokens* + +force_refresh({bufnr}) *vim.lsp.semantic_tokens.force_refresh()* + Force a refresh of all semantic tokens + + Only has an effect if the buffer is currently active for semantic token + highlighting (|vim.lsp.semantic_tokens.start()| has been called for it) + + Parameters: ~ + • {bufnr} (nil|number) default: current buffer + + *vim.lsp.semantic_tokens.get_at_pos()* +get_at_pos({bufnr}, {row}, {col}) + Return the semantic token(s) at the given position. If called without + arguments, returns the token under the cursor. + + Parameters: ~ + • {bufnr} (number|nil) Buffer number (0 for current buffer, default) + • {row} (number|nil) Position row (default cursor position) + • {col} (number|nil) Position column (default cursor position) + + Return: ~ + (table|nil) List of tokens at position + +start({bufnr}, {client_id}, {opts}) *vim.lsp.semantic_tokens.start()* + Start the semantic token highlighting engine for the given buffer with the + given client. The client must already be attached to the buffer. + + NOTE: This is currently called automatically by + |vim.lsp.buf_attach_client()|. To opt-out of semantic highlighting with a + server that supports it, you can delete the semanticTokensProvider table + from the {server_capabilities} of your client in your |LspAttach| callback + or your configuration's `on_attach` callback: >lua + + client.server_capabilities.semanticTokensProvider = nil +< + + Parameters: ~ + • {bufnr} (number) + • {client_id} (number) + • {opts} (nil|table) Optional keyword arguments + • debounce (number, default: 200): Debounce token + requests to the server by the given number in + milliseconds + +stop({bufnr}, {client_id}) *vim.lsp.semantic_tokens.stop()* + Stop the semantic token highlighting engine for the given buffer with the + given client. + + NOTE: This is automatically called by a |LspDetach| autocmd that is set up + as part of `start()`, so you should only need this function to manually + disengage the semantic token engine without fully detaching the LSP client + from the buffer. + + Parameters: ~ + • {bufnr} (number) + • {client_id} (number) ============================================================================== Lua module: vim.lsp.handlers *lsp-handlers* hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()* - |lsp-handler| for the method "textDocument/hover" > - - vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( - vim.lsp.handlers.hover, { - -- Use a sharp border with `FloatBorder` highlights - border = "single" - } - ) + |lsp-handler| for the method "textDocument/hover" >lua + + vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( + vim.lsp.handlers.hover, { + -- Use a sharp border with `FloatBorder` highlights + border = "single", + -- add the title in hover float window + title = "hover" + } + ) < Parameters: ~ - {config} (table) Configuration table. + • {config} (table) Configuration table. • border: (default=nil) • Add borders to the floating window • See |nvim_open_win()| @@ -1407,21 +1405,21 @@ hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()* *vim.lsp.handlers.signature_help()* signature_help({_}, {result}, {ctx}, {config}) |lsp-handler| for the method "textDocument/signatureHelp". The active - parameter is highlighted with |hl-LspSignatureActiveParameter|. > - - vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( - vim.lsp.handlers.signature_help, { - -- Use a sharp border with `FloatBorder` highlights - border = "single" - } - ) + parameter is highlighted with |hl-LspSignatureActiveParameter|. >lua + + vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( + vim.lsp.handlers.signature_help, { + -- Use a sharp border with `FloatBorder` highlights + border = "single" + } + ) < 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 +1431,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 +1443,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,37 +1455,37 @@ 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 + https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent *vim.lsp.util.character_offset()* 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,9 +1500,9 @@ 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 - with converted lines + • {input} (`MarkedString` | `MarkedString[]` | `MarkupContent`) + • {contents} (table|nil) List of strings to extend with converted + lines. Defaults to {}. Return: ~ {contents}, extended with lines of converted markdown. @@ -1517,14 +1515,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 +1532,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 +1544,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|nil) 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 +1574,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 +1585,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,14 +1597,15 @@ 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` • focusable (string or table) override `focusable` • zindex (string or table) override `zindex`, defaults to 50 + • relative ("mouse"|"cursor") defaults to "cursor" Return: ~ (table) Options @@ -1617,7 +1616,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 +1630,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 +1649,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|nil) utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` @@ -1670,9 +1669,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 +1684,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 +1697,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 +1736,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 +1750,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 +1759,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 +1767,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|nil) 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 +1804,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 +1822,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 +1830,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 +1845,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 +1858,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 +1883,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|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 +1905,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 +1929,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 +1940,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 +1956,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 +1990,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,17 +2002,17 @@ 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 + (table) TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent ============================================================================== @@ -2003,7 +2028,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-guide.txt b/runtime/doc/lua-guide.txt new file mode 100644 index 0000000000..b971a7d2ad --- /dev/null +++ b/runtime/doc/lua-guide.txt @@ -0,0 +1,757 @@ +*lua-guide.txt* Nvim + + NVIM REFERENCE MANUAL + + Guide to using Lua in Nvim + + + Type |gO| to see the table of contents. + +============================================================================== +Introduction *lua-guide* + +This guide will go through the basics of using Lua in Neovim. It is not meant +to be a comprehensive encyclopedia of all available features, nor will it +detail all intricacies. Think of it as a survival kit -- the bare minimum +needed to know to comfortably get started on using Lua in Neovim. + +An important thing to note is that this isn't a guide to the Lua language +itself. Rather, this is a guide on how to configure and modify Neovim through +the Lua language and the functions we provide to help with this. Take a look +at |luaref| and |lua-concepts| if you'd like to learn more about Lua itself. +Similarly, this guide assumes some familiarity with the basics of Neovim +(commands, options, mappings, autocommands), which are covered in the +|user-manual|. + +------------------------------------------------------------------------------ +Some words on the API *lua-guide-api* + +The purpose of this guide is to introduce the different ways of interacting +with Neovim through Lua (the "API"). This API consists of three different +layers: + +1. The "Vim API" inherited from Vim: |ex-commands| and |builtin-functions| as +well as |user-function|s in Vimscript. These are accessed through |vim.cmd()| +and |vim.fn| respectively, which are discussed under |lua-guide-vimscript| +below. + +2. The "Neovim API" written in C for use in remote plugins and GUIs; see |api|. +These functions are accessed through |vim.api|. + +3. The "Lua API" written in and specifically for Lua. These are any other +functions accessible through `vim.*` not mentioned already; see |lua-stdlib|. + +This distinction is important, as API functions inherit behavior from their +original layer: For example, Neovim API functions always need all arguments to +be specified even if Lua itself allows omitting arguments (which are then +passed as `nil`); and Vim API functions can use 0-based indexing even if Lua +arrays are 1-indexed by default. + +Through this, any possible interaction can be done through Lua without writing +a complete new API from scratch. For this reason, functions are usually not +duplicated between layers unless there is a significant benefit in +functionality or performance (e.g., you can map Lua functions directly through +|nvim_create_autocmd()| but not through |:autocmd|). In case there are multiple +ways of achieving the same thing, this guide will only cover what is most +convenient to use from Lua. + +============================================================================== +Using Lua *lua-guide-using-Lua* + +To run Lua code from the Neovim command line, use the |:lua| command: +>vim + :lua print("Hello!") +< +Note: each |:lua| command has its own scope and variables declared with the +local keyword are not accessible outside of the command. This won't work: +>vim + :lua local foo = 1 + :lua print(foo) + " prints "nil" instead of "1" +< +You can also use `:lua=`, which is the same as `:lua vim.pretty_print(...)`, +to conveniently check the value of a variable or a table: +>lua + :lua=package +< +To run a Lua script in an external file, you can use the |:source| command +exactly like for a Vimscript file: +>vim + :source ~/programs/baz/myluafile.lua +< +Finally, you can include Lua code in a Vimscript file by putting it inside a +|lua-heredoc| block: +>vim + lua << EOF + local tbl = {1, 2, 3} + for k, v in ipairs(tbl) do + print(v) + end + EOF +< +------------------------------------------------------------------------------ +Using Lua files on startup *lua-guide-config* + +Neovim supports using `init.vim` or `init.lua` as the configuration file, but +not both at the same time. This should be placed in your |config| directory, +which is typically `~/.config/nvim` for Linux, BSD, or macOS, and +`~/AppData/Local/nvim/` for Windows. Note that you can use Lua in `init.vim` +and Vimscript in `init.lua`, which will be covered below. + +If you'd like to run any other Lua script on |startup| automatically, then you +can simply put it in `plugin/` in your |'runtimepath'|. + +------------------------------------------------------------------------------ +Lua modules *lua-guide-modules* + +If you want to load Lua files on demand, you can place them in the `lua/` +directory in your |'runtimepath'| and load them with `require`. (This is the +Lua equivalent of Vimscript's |autoload| mechanism.) + +Let's assume you have the following directory structure: +> + ~/.config/nvim + |-- after/ + |-- ftplugin/ + |-- lua/ + | |-- myluamodule.lua + | |-- other_modules/ + | |-- anothermodule.lua + | |-- init.lua + |-- plugin/ + |-- syntax/ + |-- init.vim +< + +Then the following Lua code will load `myluamodule.lua`: +>lua + require("myluamodule") +< +Note the absence of a `.lua` extension. + +Similarly, loading `other_modules/anothermodule.lua` is done via +>lua + require('other_modules/anothermodule') + -- or + require('other_modules.anothermodule') +< + +Note how "submodules" are just subdirectories; the `.` is equivalent to the +path separator `/` (even on Windows). + +A folder containing an |init.lua| file can be required directly, without +having to specify the name of the file: +>lua + require('other_modules') -- loads other_modules/init.lua +< +Requiring a nonexistent module or a module which contains syntax errors aborts +the currently executing script. `pcall()` may be used to catch such errors. The +following example tries to load the `module_with_error` and only calls one of +its functions if this succeeds and prints an error message otherwise: +>lua + local ok, mymod = pcall(require, 'module_with_error') + if not ok then + print("Module had an error") + else + mymod.function() + end +< +In contrast to |:source|, |require()| not only searches through all `lua/` directories +under |'runtimepath'|, it also cache the module on first use. Calling +`require()` a second time will therefore _not_ execute the script again and +instead return the cached file. To rerun the file, you need to remove it from +the cache manually first: +>lua + package.loaded['myluamodule'] = nil + require('myluamodule') -- read and execute the module again from disk +< +------------------------------------------------------------------------------ +See also: +• |lua-require| +• |luaref-pcall()| + +============================================================================== +Using Vim commands and functions from Lua *lua-guide-vimscript* + +All Vim commands and functions are accessible from Lua. + +------------------------------------------------------------------------------ +Vim commands *lua-guide-vim-commands* + +To run an arbitrary Vim command from Lua, pass it as a string to |vim.cmd()|: +>lua + vim.cmd("colorscheme habamax") +< +Note that special characters will need to be escaped with backslashes: +>lua + vim.cmd("%s/\\Vfoo/bar/g") +< +An alternative is to use a literal string (see |luaref-literal|) delimited by +double brackets `[[ ]]` as in +>lua + vim.cmd([[%s/\Vfoo/bar/g]]) +< +Another benefit of using literal strings is that they can be multiple lines; +this allows you to pass multiple commands to a single call of |vim.cmd()|: +>lua + vim.cmd([[ + highlight Error guibg=red + highlight link Warning Error + ]]) +< +This is the converse of |lua-heredoc| and allows you to include Vimscript code in +your `init.lua`. + +If you want to build your Vim command programmatically, the following form can +be useful (all these are equivalent to the corresponding line above): +>lua + vim.cmd.colorscheme("habamax") + vim.cmd.highlight({ "Error", "guibg=red" }) + vim.cmd.highlight({ "link", "Warning", "Error" }) +< +------------------------------------------------------------------------------ +Vimscript functions *lua-guide-vim-functions* + +Use |vim.fn| to call Vimscript functions from Lua. Data types between Lua and +Vimscript are automatically converted: +>lua + print(vim.fn.printf('Hello from %s', 'Lua')) + + local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' }) + print(vim.inspect(reversed_list)) -- { "c", "b", "a" } + + local function print_stdout(chan_id, data, name) + print(data[1]) + end + + vim.fn.jobstart('ls', { on_stdout = print_stdout }) + print(vim.fn.printf('Hello from %s', 'Lua')) +< +This works for both |builtin-functions| and |user-function|s. + +Note that hashes (`#`) are not valid characters for identifiers in Lua, so, +e.g., |autoload| functions have to be called with this syntax: +>lua + vim.fn['my#autoload#function']() +< +------------------------------------------------------------------------------ +See also: +• |builtin-functions|: alphabetic list of all Vimscript functions +• |function-list|: list of all Vimscript functions grouped by topic +• |:runtime|: run all Lua scripts matching a pattern in |'runtimepath'| +• |package.path|: list of all paths searched by `require()` + +============================================================================== +Variables *lua-guide-variables* + +Variables can be set and read using the following wrappers, which directly +correspond to their |variable-scope|: + +• |vim.g|: global variables (|g:|) +• |vim.b|: variables for the current buffer (|b:|) +• |vim.w|: variables for the current window (|w:|) +• |vim.t|: variables for the current tabpage (|t:|) +• |vim.v|: predefined Vim variables (|v:|) +• |vim.env|: environment variables defined in the editor session + +Data types are converted automatically. For example: +>lua + vim.g.some_global_variable = { + key1 = "value", + key2 = 300 + } + + print(vim.inspect(vim.g.some_global_variable)) + --> { key1 = "value", key2 = 300 } +< +You can target specific buffers (via number), windows (via |window-ID|), or +tabpages by indexing the wrappers: +>lua + vim.b[2].myvar = 1 -- set myvar for buffer number 2 + vim.w[1005].myothervar = true -- set myothervar for window ID 1005 +< +Some variable names may contain characters that cannot be used for identifiers +in Lua. You can still manipulate these variables by using the syntax +>lua + vim.g['my#variable'] = 1 +< +Note that you cannot directly change fields of array variables. This won't +work: +>lua + vim.g.some_global_variable.key2 = 400 + vim.pretty_print(vim.g.some_global_variable) + --> { key1 = "value", key2 = 300 } +< +Instead, you need to create an intermediate Lua table and change this: +>lua + local temp_table = vim.g.some_global_variable + temp_table.key2 = 400 + vim.g.some_global_variable = temp_table + vim.pretty_print(vim.g.some_global_variable) + --> { key1 = "value", key2 = 400 } +< +To delete a variable, simply set it to `nil`: +>lua + vim.g.myvar = nil +< +------------------------------------------------------------------------------ +See also: +• |lua-vim-variables| + +============================================================================== +Options *lua-guide-options* + +There are two complementary ways of setting |options| via Lua. + +------------------------------------------------------------------------------ +vim.opt + +The most convenient way for setting global and local options, e.g., in `init.lua`, +is through `vim.opt` and friends: + +• |vim.opt|: behaves like |:set| +• |vim.opt_global|: behaves like |:setglobal| +• |vim.opt_local|: behaves like |:setlocal| + +For example, the Vimscript commands +>vim + set smarttab + set nosmarttab +< +are equivalent to +>lua + vim.opt.smarttab = true + vim.opt.smarttab = false +< +In particular, they allow an easy way to working with list-like, map-like, and +set-like options through Lua tables: Instead of +>vim + set wildignore=*.o,*.a,__pycache__ + set listchars=space:_,tab:>~ + set formatoptions=njt +< +you can use +>lua + vim.opt.wildignore = { '*.o', '*.a', '__pycache__' } + vim.opt.listchars = { space = '_', tab = '>~' } + vim.opt.formatoptions = { n = true, j = true, t = true } +< +These wrappers also come with methods that work similarly to their |:set+=|, +|:set^=| and |:set-=| counterparts in Vimscript: +>lua + vim.opt.shortmess:append({ I = true }) + vim.opt.wildignore:prepend('*.o') + vim.opt.whichwrap:remove({ 'b', 's' }) +< +The price to pay is that you cannot access the option values directly but must +use |vim.opt:get()|: +>lua + print(vim.opt.smarttab) + --> {...} (big table) + print(vim.opt.smarttab:get()) + --> false + vim.pretty_print(vim.opt.listchars:get()) + --> { space = '_', tab = '>~' } +< +------------------------------------------------------------------------------ +vim.o + +For this reason, there exists a more direct variable-like access using `vim.o` +and friends, similarly to how you can get and set options via `:echo &number` +and `:let &listchars='space:_,tab:>~'`: + +• |vim.o|: behaves like |:set| +• |vim.go|: behaves like |:setglobal| +• |vim.bo|: for buffer-scoped options +• |vim.wo|: for window-scoped options + +For example: +>lua + vim.o.smarttab = false -- :set nosmarttab + print(vim.o.smarttab) + --> false + vim.o.listchars = 'space:_,tab:>~' -- :set listchars='space:_,tab:>~' + print(vim.o.listchars) + --> 'space:_,tab:>~' + vim.o.isfname = vim.o.isfname .. ',@-@' -- :set isfname+=@-@ + print(vim.o.isfname) + --> '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@' + vim.bo.shiftwidth = 4 -- :setlocal shiftwidth=4 + print(vim.bo.shiftwidth) + --> 4 +< +Just like variables, you can specify a buffer number or |window-ID| for buffer +and window options, respectively. If no number is given, the current buffer or +window is used: +>lua + vim.bo[4].expandtab = true -- sets expandtab to true in buffer 4 + vim.wo.number = true -- sets number to true in current window + print(vim.wo[0].number) --> true +< +------------------------------------------------------------------------------ +See also: +• |lua-options| + +============================================================================== +Mappings *lua-guide-mappings* + +You can map either Vim commands or Lua functions to key sequences. + +------------------------------------------------------------------------------ +Creating mappings *lua-guide-mappings-set* + +Mappings can be created using |vim.keymap.set()|. This function takes three +mandatory arguments: +• {mode} is a string or a table of strings containing the mode + prefix for which the mapping will take effect. The prefixes are the ones + listed in |:map-modes|, or "!" for |:map!|, or empty string for |:map|. +• {lhs} is a string with the key sequences that should trigger the mapping. +• {rhs} is either a string with a Vim command or a Lua function that should + be executed when the {lhs} is entered. + An empty string is equivalent to |<Nop>|, which disables a key. + +Examples: +>lua + -- Normal mode mapping for Vim command + vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>') + -- Normal and Command-line mode mapping for Vim command + vim.keymap.set({'n', 'c'}, '<Leader>ex2', '<cmd>echo "Example 2"<cr>') + -- Normal mode mapping for Lua function + vim.keymap.set('n', '<Leader>ex3', vim.treesitter.start) + -- Normal mode mapping for Lua function with arguments + vim.keymap.set('n', '<Leader>ex4', function() print('Example 4') end) +< +You can map functions from Lua modules via +>lua + vim.keymap.set('n', '<Leader>pl1', require('plugin').action) +< +Note that this loads the plugin at the time the mapping is defined. If you +want to defer the loading to the time when the mapping is executed (as for +|autoload| functions), wrap it in `function() end`: +>lua + vim.keymap.set('n', '<Leader>pl2', function() require('plugin').action() end) +< +The fourth, optional, argument is a table with keys that modify the behavior +of the mapping such as those from |:map-arguments|. The following are the most +useful options: +• `buffer`: If given, only set the mapping for the buffer with the specified + number; `0` or `true` means the current buffer. >lua + -- set mapping for the current buffer + vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = true }) + -- set mapping for the buffer number 4 + vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = 4 }) +< +• `silent`: If set to `true`, suppress output such as error messages. >lua + vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { silent = true }) +< +• `expr`: If set to `true`, do not execute the {rhs} but use the return value + as input. Special |keycodes| are converted automatically. For example, the following + mapping replaces <down> with <c-n> in the popupmenu only: >lua + vim.keymap.set('c', '<down>', function() + if vim.fn.pumvisible() == 1 then return '<c-n>' end + return '<down>' + end, { expr = true }) +< +• `desc`: A string that is shown when listing mappings with, e.g., |:map|. + This is useful since Lua functions as {rhs} are otherwise only listed as + `Lua: <number> <source file>:<line>`. Plugins should therefore always use this + for mappings they create. >lua + vim.keymap.set('n', '<Leader>pl1', require('plugin').action, + { desc = 'Execute action from plugin' }) +< +• `remap`: By default, all mappings are nonrecursive by default (i.e., + |vim.keymap.set()| behaves like |:noremap|). If the {rhs} is itself a mapping + that should be executed, set `remap = true`: >lua + vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>') + -- add a shorter mapping + vim.keymap.set('n', 'e', '<Leader>ex1', { remap = true }) +< + Note: |<Plug>| mappings are always expanded even with the default `remap = false`: >lua + vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)') +< +------------------------------------------------------------------------------ +Removing mappings *lua-guide-mappings-del* + +A specific mapping can be removed with |vim.keymap.del()|: +>lua + vim.keymap.del('n', '<Leader>ex1') + vim.keymap.del({'n', 'c'}, '<Leader>ex2', {buffer = true}) +< +------------------------------------------------------------------------------ +See also: +• `vim.api.`|nvim_get_keymap()|: return all global mapping +• `vim.api.`|nvim_buf_get_keymap()|: return all mappings for buffer + +============================================================================== +Autocommands *lua-guide-autocommands* + +An |autocommand| is a Vim command or a Lua function that is automatically +executed whenever one or more |events| are triggered, e.g., when a file is +read or written, or when a window is created. These are accessible from Lua +through the Neovim API. + +------------------------------------------------------------------------------ +Creating autocommands *lua-guide-autocommand-create* + +Autocommands are created using `vim.api.`|nvim_create_autocmd()|, which takes +two mandatory arguments: +• {event}: a string or table of strings containing the event(s) which should + trigger the command or function. +• {opts}: a table with keys that control what should happen when the event(s) + are triggered. + +The most important options are: + +• `pattern`: A string or table of strings containing the |autocmd-pattern|. + Note: Environment variable like `$HOME` and `~` are not automatically + expanded; you need to explicitly use `vim.fn.`|expand()| for this. +• `command`: A string containing a Vim command. +• `callback`: A Lua function. + +You must specify one and only one of `command` and `callback`. If `pattern` is +omitted, it defaults to `pattern = '*'`. +Examples: +>lua + vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { + pattern = {"*.c", "*.h"}, + command = "echo 'Entering a C or C++ file'", + }) + + -- Same autocommand written with a Lua function instead + vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { + pattern = {"*.c", "*.h"}, + callback = function() print("Entering a C or C++ file") end, + }) + + -- User event triggered by MyPlugin + vim.api.nvim_create_autocmd("User", { + pattern = "MyPlugin", + callback = function() print("My Plugin Works!") end, + }) +< + +Neovim will always call a Lua function with a single table containing information +about the triggered autocommand. The most useful keys are +• `match`: a string that matched the `pattern` (see |<amatch>|) +• `buf`: the number of the buffer the event was triggered in (see |<abuf>|) +• `file`: the file name of the buffer the event was triggered in (see |<afile>|) +• `data`: a table with other relevant data that is passed for some events + +For example, this allows you to set buffer-local mappings for some filetypes: +>lua + vim.api.nvim.create_autocmd("FileType", { + pattern = "lua", + callback = function(args) + vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = args.buf }) + end + }) +< +This means that if your callback itself takes an (even optional) argument, you +must wrap it in `function() end` to avoid an error: +>lua + vim.api.nvim_create_autocmd('TextYankPost', { + callback = function() vim.highlight.on_yank() end + }) +< +(Since unused arguments can be omitted in Lua function definitions, this is +equivalent to `function(args) ... end`.) + +Instead of using a pattern, you can create a buffer-local autocommand (see +|autocmd-buflocal|) with `buffer`; in this case, `pattern` cannot be used: +>lua + -- set autocommand for current buffer + vim.api.nvim_create_autocmd("CursorHold", { + buffer = 0, + callback = function() print("hold") end, + }) + + -- set autocommand for buffer number 33 + vim.api.nvim_create_autocmd("CursorHold", { + buffer = 33, + callback = function() print("hold") end, + }) +< +Similarly to mappings, you can (and should) add a description using `desc`: +>lua + vim.api.nvim_create_autocmd('TextYankPost', { + callback = function() vim.highlight.on_yank() end, + desc = "Briefly highlight yanked text" + }) +< +Finally, you can group autocommands using the `group` key; this will be +covered in detail in the next section. + +------------------------------------------------------------------------------ +Grouping autocommands *lua-guide-autocommands-group* + +Autocommand groups can be used to group related autocommands together; see +|autocmd-groups|. This is useful for organizing autocommands and especially +for preventing autocommands to be set multiple times. + +Groups can be created with `vim.api.`|nvim_create_augroup()|. This function +takes two mandatory arguments: a string with the name of a group and a table +determining whether the group should be cleared (i.e., all grouped +autocommands removed) if it already exists. The function returns a number that +is the internal identifier of the group. Groups can be specified either by +this identifier or by the name (but only if the group has been created first). + +For example, a common Vimscript pattern for autocommands defined in files that +may be reloaded is +>vim + augroup vimrc + " Remove all vimrc autocommands + autocmd! + au BufNewFile,BufRead *.html set shiftwidth=4 + au BufNewFile,BufRead *.html set expandtab + augroup END +< +This is equivalent to the following Lua code: +>lua + local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = true }) + vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, { + pattern = '*.html', + group = mygroup, + command = 'set shiftwidth=4', + }) + vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, { + pattern = '*.html', + group = 'vimrc', -- equivalent to group=mygroup + command = 'set expandtab', + }) +< +Autocommand groups are unique for a given name, so you can reuse them, e.g., +in a different file: +>lua + local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = false }) + vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, { + pattern = '*.html', + group = mygroup, + command = 'set shiftwidth=4', + }) +< +------------------------------------------------------------------------------ +Deleting autocommands *lua-guide-autocommands-delete* + +You can use `vim.api.`|nvim_clear_autocmds()| to remove autocommands. This +function takes a single mandatory argument that is a table of keys describing +the autocommands that are to be removed: +>lua + -- Delete all BufEnter and InsertLeave autocommands + vim.api.nvim_clear_autocmds({event = {"BufEnter", "InsertLeave"}}) + + -- Delete all autocommands that uses "*.py" pattern + vim.api.nvim_clear_autocmds({pattern = "*.py"}) + + -- Delete all autocommands in group "scala" + vim.api.nvim_clear_autocmds({group = "scala"}) + + -- Delete all ColorScheme autocommands in current buffer + vim.api.nvim_clear_autocmds({event = "ColorScheme", buffer = 0 }) +< +Note: Autocommands in groups will only be removed if the `group` key is +specified, even if another option matches it. + +------------------------------------------------------------------------------ +See also +• |nvim_get_autocmds()|: return all matching autocommands +• |nvim_exec_autocmds()|: execute all matching autocommands + +============================================================================== +User commands *lua-guide-usercommands* + +|user-commands| are custom Vim commands that call a Vimscript or Lua function. +Just like built-in commands, they can have arguments, act on ranges, or have +custom completion of arguments. As these are most useful for plugins, we will +cover only the basics of this advanced topic. + +------------------------------------------------------------------------------ +Creating user commands *lua-guide-usercommands-create* + +User commands can be created through the Neovim API with +`vim.api.`|nvim_create_user_command()|. This function takes three mandatory +arguments: +• a string that is the name of the command (which must start with an uppercase + letter to distinguish it from builtin commands); +• a string containing Vim commands or a Lua function that is executed when the + command is invoked; +• a table with |command-attributes|; in addition, it can contain the keys + `desc` (a string describing the command); `force` (set to `false` to avoid + replacing an already existing command with the same name), and `preview` (a + Lua function that is used for |:command-preview|). + +Example: +>lua + vim.api.nvim_create_user_command('Test', 'echo "It works!"', {}) + vim.cmd.Test() + --> It works! +< +(Note that the third argument is mandatory even if no attributes are given.) + +Lua functions are called with a single table argument containing arguments and +modifiers. The most important are: +• `name`: a string with the command name +• `fargs`: a table containing the command arguments split by whitespace (see |<f-args>|) +• `bang`: `true` if the command was executed with a `!` modifier (see |<bang>|) +• `line1`: the starting line number of the command range (see |<line1>|) +• `line2`: the final line number of the command range (see |<line2>|) +• `range`: the number of items in the command range: 0, 1, or 2 (see |<range>|) +• `count`: any count supplied (see |<count>|) +• `smods`: a table containing the command modifiers (see |<mods>|) + +For example: +>lua + vim.api.nvim_create_user_command('Upper', + function(opts) + print(string.upper(opts.fargs[1])) + end, + { nargs = 1 }) + + vim.cmd.Upper('foo') + --> FOO +< +The `complete` attribute can take a Lua function in addition to the +attributes listed in |:command-complete|. >lua + + vim.api.nvim_create_user_command('Upper', + function(opts) + print(string.upper(opts.fargs[1])) + end, + { nargs = 1, + complete = function(ArgLead, CmdLine, CursorPos) + -- return completion candidates as a list-like table + return { "foo", "bar", "baz" } + end, + }) +< +Buffer-local user commands are created with `vim.api.`|nvim_buf_create_user_command()|. +Here the first argument is the buffer number (`0` being the current buffer); +the remaining arguments are the same as for |nvim_create_user_command()|: +>lua + vim.api.nvim_buf_create_user_command(0, 'Upper', + function(opts) + print(string.upper(opts.fargs[1])) + end, + { nargs = 1 }) +< +------------------------------------------------------------------------------ +Deleting user commands *lua-guide-usercommands-delete* + +User commands can be deleted with `vim.api.`|nvim_del_user_command()|. The only +argument is the name of the command: +>lua + vim.api.nvim_del_user_command('Upper') +< +To delete buffer-local user commands use `vim.api.`|nvim_buf_del_user_command()|. +Here the first argument is the buffer number (`0` being the current buffer), +and second is command name: +>lua + vim.api.nvim_buf_del_user_command(4, 'Upper') +< +============================================================================== +Credits *lua-guide-credits* +This guide is in large part taken from nanotee's Lua guide: +https://github.com/nanotee/nvim-lua-guide + +Thank you @nanotee! + +vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 42f3a5e432..47249a484b 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -11,30 +11,119 @@ 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: >vim :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. + +Lua plugins and user config are automatically discovered and loaded, just like +Vimscript. See |lua-guide| for practical guidance. + +You can also run Lua scripts from your shell using the |-l| argument: > + nvim -l foo.lua [args...] +< + *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: >lua + local foo = function(a, b) + print("A: ", a) + print("B: ", b) + end + +The first way to call this function is: >lua + 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: >lua + foo(1) + -- ==== Result ==== + -- A: 1 + -- B: nil + +Furthermore it is not an error if extra parameters are passed, they are just +discarded. + + *kwargs* +When calling a function, you can omit the parentheses if the function takes +exactly one string literal (`"foo"`) or table literal (`{1,2,3}`). The latter +is often used to approximate "named parameters" ("kwargs" or "keyword args") +as in languages like Python and C#. Example: >lua + 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's 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. + +It is of course also valid to call the function with parentheses: >lua + func_with_opts({ foo = true, filename = "hello.world" }) +< +Nvim tends to prefer the keyword args style. + +------------------------------------------------------------------------------ +LUA PATTERNS *lua-patterns* -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. +Lua intentionally does not support regular expressions, instead it has limited +"patterns" |luaref-patterns| which avoid the performance pitfalls of extended +regex. Lua scripts can also use Vim regex via |vim.regex()|. -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. +These examples use |string.match()| to demonstrate Lua patterns: >lua + + 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 ============================================================================== -IMPORTING LUA MODULES *lua-require* +IMPORTING LUA MODULES *require()* *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 @@ -43,13 +132,11 @@ back to Lua's default search mechanism. The first script found is run and The return value is cached after the first call to `require()` for each module, with subsequent calls returning the cached value without searching for, or -executing any script. For further details on `require()`, see the Lua -documentation at https://www.lua.org/manual/5.1/manual.html#pdf-require. +executing any script. For further details on `require()`, see |luaref-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 +145,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 +158,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: @@ -113,7 +197,7 @@ Note: - Although adjustments happen automatically, Nvim does not track current values of |package.path| or |package.cpath|. If you happen to delete some - paths from there you can set 'runtimepath' to trigger an update: > + paths from there you can set 'runtimepath' to trigger an update: >vim let &runtimepath = &runtimepath - Skipping paths from 'runtimepath' which contain semicolons applies both to @@ -122,170 +206,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). @@ -296,11 +223,11 @@ arguments separated by " " (space) instead of "\t" (tab). chunk is evaluated as an expression and printed. `:lua =expr` is equivalent to `:lua print(vim.inspect(expr))` - Examples: > + Examples: >vim :lua vim.api.nvim_command('echo "Hello, Nvim!"') -< To see the Lua version: > +< To see the Lua version: >vim :lua print(_VERSION) -< To see the LuaJIT version: > +< To see the LuaJIT version: >vim :lua =jit.version < *:lua-heredoc* @@ -311,7 +238,7 @@ arguments separated by " " (space) instead of "\t" (tab). be preceded by whitespace. You can omit [endmarker] after the "<<" and use a dot "." after {script} (similar to |:append|, |:insert|). - Example: > + Example: >vim function! CurrentLineInfo() lua << EOF local linenr = vim.api.nvim_win_get_cursor(0)[1] @@ -333,13 +260,13 @@ arguments separated by " " (space) instead of "\t" (tab). that becomes the text of the corresponding buffer line. Default [range] is the whole file: "1,$". - Examples: > + Examples: >vim :luado return string.format("%s\t%d", line:reverse(), #line) :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} @@ -347,7 +274,7 @@ arguments separated by " " (space) instead of "\t" (tab). The whole argument is used as the filename (like |:edit|), spaces do not need to be escaped. Alternatively you can |:source| Lua files. - Examples: > + Examples: >vim :luafile script.lua :luafile % < @@ -358,7 +285,7 @@ luaeval() *lua-eval* *luaeval()* The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is "luaeval". "luaeval" takes an expression string and an optional argument used for _A inside expression and returns the result of the expression. It is -semantically equivalent in Lua to: > +semantically equivalent in Lua to: >lua local chunkheader = "local _A = select(1, ...) return " function luaeval (expstr, arg) @@ -372,11 +299,11 @@ converted to a |Blob|. Conversion of other Lua types is an error. The magic global "_A" contains the second argument to luaeval(). -Example: > +Example: >vim :echo luaeval('_A[1] + _A[2]', [40, 2]) - 42 + " 42 :echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123') - foo + " foo < Lua tables are used as both dictionaries and lists, so it is impossible to determine whether empty table is meant to be empty list or empty dictionary. @@ -408,7 +335,7 @@ cases there is the following agreement: form a 1-step sequence from 1 to N are ignored, as well as all non-integral keys. -Examples: > +Examples: >vim :echo luaeval('math.pi') :function Rand(x,y) " random uniform between x and y @@ -425,29 +352,29 @@ treated specially. Vimscript v:lua interface *v:lua-call* From Vimscript the special `v:lua` prefix can be used to call Lua functions -which are global or accessible from global tables. The expression > - v:lua.func(arg1, arg2) -is equivalent to the Lua chunk > +which are global or accessible from global tables. The expression >vim + call v:lua.func(arg1, arg2) +is equivalent to the Lua chunk >lua return func(...) -where the args are converted to Lua values. The expression > - v:lua.somemod.func(args) -is equivalent to the Lua chunk > +where the args are converted to Lua values. The expression >vim + call v:lua.somemod.func(args) +is equivalent to the Lua chunk >lua return somemod.func(...) -In addition, functions of packages can be accessed like > - v:lua.require'mypack'.func(arg1, arg2) - v:lua.require'mypack.submod'.func(arg1, arg2) +In addition, functions of packages can be accessed like >vim + call v:lua.require'mypack'.func(arg1, arg2) + call v:lua.require'mypack.submod'.func(arg1, arg2) Note: Only single quote form without parens is allowed. Using `require"mypack"` or `require('mypack')` as prefixes do NOT work (the latter is still valid as a function call of itself, in case require returns a useful value). The `v:lua` prefix may be used to call Lua functions as |method|s. For -example: > - arg1->v:lua.somemod.func(arg2) +example: >vim + :eval arg1->v:lua.somemod.func(arg2) < You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc. -For example consider the following Lua omnifunc handler: > +For example consider the following Lua omnifunc handler: >lua function mymod.omnifunc(findstart, base) if findstart == 1 then @@ -459,10 +386,10 @@ For example consider the following Lua omnifunc handler: > vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.mymod.omnifunc') Note: The module ("mymod" in the above example) must either be a Lua global, -or use the require syntax as specified above to access it from a package. +or use require() as shown above to access it from a package. Note: `v:lua` without a call is not allowed in a Vimscript expression: -|Funcref|s cannot represent Lua functions. The following are errors: > +|Funcref|s cannot represent Lua functions. The following are errors: >vim let g:Myvar = v:lua.myfunc " Error call SomeFunc(v:lua.mycallback) " Error @@ -476,7 +403,7 @@ The Nvim Lua "standard library" (stdlib) is the `vim` module, which exposes various functions and sub-modules. It is always loaded, thus `require("vim")` is unnecessary. -You can peek at the module properties: > +You can peek at the module properties: >vim :lua print(vim.inspect(vim)) @@ -496,7 +423,7 @@ Result is something like this: > ... } -To find documentation on e.g. the "deepcopy" function: > +To find documentation on e.g. the "deepcopy" function: >vim :help vim.deepcopy() @@ -508,7 +435,7 @@ VIM.LOOP *lua-loop* *vim.loop* `vim.loop` exposes all features of the Nvim event-loop. This is a low-level API that provides functionality for networking, filesystem, and process -management. Try this command to see available functions: > +management. Try this command to see available functions: >vim :lua print(vim.inspect(vim.loop)) < @@ -517,14 +444,14 @@ see |luv-intro| for a full reference manual. *E5560* *lua-loop-callbacks* It is an error to directly invoke `vim.api` functions (except |api-fast|) in -`vim.loop` callbacks. For example, this is an error: > +`vim.loop` callbacks. For example, this is an error: >lua local timer = vim.loop.new_timer() timer:start(1000, 0, function() vim.api.nvim_command('echomsg "test"') end) < -To avoid the error use |vim.schedule_wrap()| to defer the callback: > +To avoid the error use |vim.schedule_wrap()| to defer the callback: >lua local timer = vim.loop.new_timer() timer:start(1000, 0, vim.schedule_wrap(function() @@ -536,7 +463,7 @@ wrapping.) Example: repeating timer 1. Save this code to a file. - 2. Execute it with ":luafile %". > + 2. Execute it with ":luafile %". >lua -- Create a timer handle (implementation detail: uv_timer_t). local timer = vim.loop.new_timer() @@ -557,7 +484,7 @@ Example: File-change detection *watch-file* 3. Use ":Watch %" to watch any file. 4. Try editing the file from another text editor. 5. Observe that the file reloads in Nvim (because on_change() calls - |:checktime|). > + |:checktime|). >lua local w = vim.loop.new_fs_event() local function on_change(err, fname, status) @@ -580,7 +507,7 @@ Example: TCP echo-server *tcp-server* 1. Save this code to a file. 2. Execute it with ":luafile %". 3. Note the port number. - 4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): > + 4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): >lua local function create_server(host, port, on_connect) local server = vim.loop.new_tcp() @@ -617,7 +544,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 @@ -629,16 +556,16 @@ VIM.HIGHLIGHT *lua-highlight* Nvim includes a function for highlighting a selection on yank (see for example https://github.com/machakann/vim-highlightedyank). To enable it, add -> +>vim au TextYankPost * silent! lua vim.highlight.on_yank() < to your `init.vim`. You can customize the highlight group and the duration of the highlight via -> +>vim au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} < If you want to exclude visual selections from highlighting on yank, use -> +>vim au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} < vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* @@ -656,14 +583,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 @@ -674,6 +601,7 @@ vim.highlight.priorities *vim.highlight.priorities* Table with default priorities used for highlighting: • `syntax`: `50`, used for standard syntax highlighting • `treesitter`: `100`, used for tree-sitter-based highlighting + • `semantic_tokens`: `125`, used for LSP semantic token highlighting • `diagnostics`: `150`, used for code analysis such as diagnostics • `user`: `200`, used for user-triggered highlights such as LSP document symbols or `on_yank` autocommands @@ -711,25 +639,24 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* Run diff on strings {a} and {b}. Any indices returned by this function, either directly or via callback arguments, are 1-based. - Examples: > - + Examples: >lua vim.diff('a\n', 'b\nc\n') - --> - @@ -1 +1,2 @@ - -a - +b - +c + -- => + -- @@ -1 +1,2 @@ + -- -a + -- +b + -- +c vim.diff('a\n', 'b\nc\n', {result_type = 'indices'}) - --> - { - {1, 1, 1, 2} - } + -- => + -- { + -- {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. @@ -742,6 +669,9 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* • "unified": (default) String in unified format. • "indices": Array of hunk locations. Note: This option is ignored if `on_hunk` is used. + • `linematch` (boolean): Run linematch on the resulting hunks + from xdiff. Requires `result_type = indices`, ignored + otherwise. • `algorithm` (string): Diff algorithm to use. Values: • "myers" the default algorithm @@ -782,6 +712,22 @@ vim.mpack.decode({str}) *vim.mpack.decode* Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object. ------------------------------------------------------------------------------ +VIM.JSON *lua-json* + +The *vim.json* module provides encoding and decoding of Lua objects to and +from JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. + +vim.json.encode({obj}) *vim.json.encode* + Encodes (or "packs") Lua object {obj} as JSON in a Lua string. + +vim.json.decode({str}[, {opts}]) *vim.json.decode* + Decodes (or "unpacks") the JSON-encoded {str} to a Lua object. + + {opts} is a table with the key `luanil = { object: bool, array: bool }` + that controls whether `null` in JSON objects or arrays should be converted + to Lua `nil` instead of `vim.NIL`. + +------------------------------------------------------------------------------ VIM.SPELL *lua-spell* vim.spell.check({str}) *vim.spell.check()* @@ -792,16 +738,15 @@ vim.spell.check({str}) *vim.spell.check()* 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to the buffer. Consider calling this with |nvim_buf_call()|. - Example: > - + Example: >lua vim.spell.check("the quik brown fox") - --> - { - {'quik', 'bad', 4} - } + -- => + -- { + -- {'quik', 'bad', 5} + -- } < Parameters: ~ - {str} String to spell check. + • {str} String to spell check. Return: ~ List of tuples with three items: @@ -818,7 +763,7 @@ VIM *lua-builtin* vim.api.{func}({...}) *vim.api* Invokes Nvim |API| function {func} with arguments {...}. - Example: call the "nvim_get_current_line()" API function: > + Example: call the "nvim_get_current_line()" API function: >lua print(tostring(vim.api.nvim_get_current_line())) vim.version() *vim.version* @@ -881,6 +826,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 +851,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 +869,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`. @@ -927,7 +888,7 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* If {callback} errors, the error is raised. - Examples: > + Examples: >lua --- -- Wait for 100 ms, allowing other events to process @@ -951,6 +912,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): >lua + + 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 @@ -959,7 +957,7 @@ vim.type_idx *vim.type_idx* vim.val_idx *vim.val_idx* Value index for tables representing |Float|s. A table representing - floating-point value 1.0 looks like this: > + floating-point value 1.0 looks like this: >lua { [vim.type_idx] = vim.types.float, [vim.val_idx] = 1.0, @@ -1000,12 +998,13 @@ 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()* Invokes |vim-function| or |user-function| {func} with arguments {...}. See also |vim.fn|. - Equivalent to: > + Equivalent to: >lua vim.fn[func]({...}) vim.cmd({command}) @@ -1013,7 +1012,7 @@ vim.cmd({command}) vim.fn.{func}({...}) *vim.fn* Invokes |vim-function| or |user-function| {func} with arguments {...}. - To call autoload functions, use the syntax: > + To call autoload functions, use the syntax: >lua vim.fn['some#function']({...}) < Unlike vim.api.|nvim_call_function()| this converts directly between Vim @@ -1036,13 +1035,27 @@ from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables described below. In this way you can easily read and modify global Vimscript variables from Lua. -Example: > +Example: >lua vim.g.foo = 5 -- Set the g:foo Vimscript variable. print(vim.g.foo) -- Get and print the g:foo Vimscript variable. 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: >lua + + 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`. @@ -1070,86 +1083,153 @@ vim.env *vim.env* Environment variables defined in the editor session. See |expand-env| and |:let-environment| for the Vimscript behavior. Invalid or unset key returns `nil`. - Example: > + Example: >lua vim.env.FOO = 'bar' 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` - In Lua: - `vim.opt.number = true` + To set a string value: + Vimscript: `set wildignore=*.o,*.a,__pycache__` + Lua: `vim.o.wildignore = '*.o,*.a,__pycache__'` - To set an array of values: - In Vimscript: - `set 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|. - 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__'` +vim.o *vim.o* + Get or set |options|. Like `:set`. Invalid key is an error. - However, vim.opt also supports a more elegent way of setting - list-style options by using lua tables: - `vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }` + Note: this works on both buffer-scoped and window-scoped options using the + current buffer and window. - To replicate the behavior of |:set+=|, use: > + Example: >lua + 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. - -- vim.opt supports appending options via the "+" operator - vim.opt.wildignore = vim.opt.wildignore + { "*.pyc", "node_modules" } + 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. - -- or using the `:append(...)` method - vim.opt.wildignore:append { "*.pyc", "node_modules" } + Example: >lua + vim.go.cmdheight = 4 + print(vim.go.columns) + print(vim.go.bar) -- error: invalid key < - To replicate the behavior of |:set^=|, use: > +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. - -- vim.opt supports prepending options via the "^" operator - vim.opt.wildignore = vim.opt.wildignore ^ { "new_first_value" } + Note: this is equivalent to both `:set` and `:setlocal`. - -- or using the `:prepend(...)` method - vim.opt.wildignore:prepend { "new_first_value" } + Example: >lua + 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 < - To replicate the behavior of |:set-=|, use: > +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. - -- vim.opt supports removing options via the "-" operator - vim.opt.wildignore = vim.opt.wildignore - { "node_modules" } + Note: this does not access |local-options| (`:setlocal`) instead use: >lua + nvim_get_option_value(OPTION, { scope = 'local', win = winid }) + nvim_set_option_value(OPTION, VALUE, { scope = 'local', win = winid } +< + Example: >lua + 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 +< - -- or using the `:remove(...)` method - vim.opt.wildignore:remove { "node_modules" } + + + *vim.opt_local* + *vim.opt_global* + *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: >vim + set wildignore=*.o,*.a,__pycache__ +< + In Lua using `vim.o`: >lua + vim.o.wildignore = '*.o,*.a,__pycache__' +< + In Lua using `vim.opt`: >lua + vim.opt.wildignore = { '*.o', '*.a', '__pycache__' } +< + To replicate the behavior of |:set+=|, use: >lua + + vim.opt.wildignore:append { "*.pyc", "node_modules" } < - To set a map of values: - In Vimscript: - `set listchars=space:_,tab:>~` + To replicate the behavior of |:set^=|, use: >lua - In Lua: - `vim.opt.listchars = { space = '_', tab = '>~' }` + vim.opt.wildignore:prepend { "new_first_value" } +< + To replicate the behavior of |:set-=|, use: >lua + vim.opt.wildignore:remove { "node_modules" } +< + The following methods of setting a map-style option are equivalent: + In Vimscript: >vim + set listchars=space:_,tab:>~ +< + In Lua using `vim.o`: >lua + vim.o.listchars = 'space:_,tab:>~' +< + In Lua using `vim.opt`: >lua + 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: >vim + echo wildignore +< + In Lua using `vim.o`: >lua + print(vim.o.wildignore) +< + In Lua using `vim.opt`: >lua + 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()* @@ -1159,10 +1239,10 @@ Option:get() values will be returned in exactly the same fashion. For values that are comma-separated lists, an array will be returned with - the values as entries in the array: > + the values as entries in the array: >lua 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 @@ -1172,21 +1252,21 @@ Option:get() -- Will ignore: *.o < For values that are comma-separated maps, a table will be returned with - the names as keys and the values as entries: > + the names as keys and the values as entries: >lua 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. > + as keys and `true` as entries. >lua 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() @@ -1199,94 +1279,29 @@ Option:append(value) Append a value to string-style options. See |:set+=| - These are equivalent: - `vim.opt.formatoptions:append('j')` - `vim.opt.formatoptions = vim.opt.formatoptions + 'j'` - + These are equivalent: >lua + vim.opt.formatoptions:append('j') + vim.opt.formatoptions = vim.opt.formatoptions + 'j' +< *vim.opt:prepend()* Option:prepend(value) Prepend a value to string-style options. See |:set^=| - These are equivalent: - `vim.opt.wildignore:prepend('*.o')` - `vim.opt.wildignore = vim.opt.wildignore ^ '*.o'` - + These are equivalent: >lua + vim.opt.wildignore:prepend('*.o') + vim.opt.wildignore = vim.opt.wildignore ^ '*.o' +< *vim.opt:remove()* Option:remove(value) Remove a value from string-style options. See |:set-=| - These are equivalent: - `vim.opt.wildignore:remove('*.pyc')` - `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 + These are equivalent: >lua + vim.opt.wildignore:remove('*.pyc') + vim.opt.wildignore = vim.opt.wildignore - '*.pyc' < -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* @@ -1296,7 +1311,7 @@ cmd({command}) *vim.cmd()* Note that `vim.cmd` can be indexed with a command name to return a callable function to the command. - Example: > + Example: >lua vim.cmd('echo 42') vim.cmd([[ @@ -1325,7 +1340,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 +1357,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 +1395,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 +1406,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 +1427,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: ~ @@ -1430,7 +1445,7 @@ paste({lines}, {phase}) *vim.paste()* Paste handler, invoked by |nvim_paste()| when a conforming UI (such as the |TUI|) pastes text into the editor. - Example: To remove ANSI color codes when pasting: > + Example: To remove ANSI color codes when pasting: >lua vim.paste = (function(overridden) return function(lines, phase) @@ -1444,27 +1459,28 @@ 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: > + Prints given arguments in human-readable format. Example: >lua -- Print highlight group Normal and store it's contents in a variable. local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true)) < Return: ~ - given arguments. + any # given arguments. See also: ~ |vim.inspect()| @@ -1474,25 +1490,82 @@ 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) region 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()| |vim.in_fast_event()| +============================================================================== +Lua module: inspector *lua-inspector* + +inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()* + Get all the items at a given buffer position. + + Can also be pretty-printed with `:Inspect!`. *:Inspect!* + + Parameters: ~ + • {bufnr} (number|nil) defaults to the current buffer + • {row} (number|nil) row to inspect, 0-based. Defaults to the row of + the current cursor + • {col} (number|nil) col to inspect, 0-based. Defaults to the col of + the current cursor + • {filter} (table|nil) a table with key-value pairs to filter the items + • syntax (boolean): include syntax based highlight groups + (defaults to true) + • treesitter (boolean): include treesitter based highlight + groups (defaults to true) + • extmarks (boolean|"all"): include extmarks. When `all`, + then extmarks without a `hl_group` will also be included + (defaults to true) + • semantic_tokens (boolean): include semantic tokens + (defaults to true) + + Return: ~ + (table) a table with the following key-value pairs. Items are in + "traversal order": + • treesitter: a list of treesitter captures + • syntax: a list of syntax groups + • semantic_tokens: a list of semantic tokens + • extmarks: a list of extmarks + • buffer: the buffer used to get the items + • row: the row used to get the items + • col: the col used to get the items + +show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()* + Show all the items at a given buffer position. + + Can also be shown with `:Inspect`. *:Inspect* + + Parameters: ~ + • {bufnr} (number|nil) defaults to the current buffer + • {row} (number|nil) row to inspect, 0-based. Defaults to the row of + the current cursor + • {col} (number|nil) col to inspect, 0-based. Defaults to the col of + the current cursor + • {filter} (table|nil) see |vim.inspect_pos()| + + deep_equal({a}, {b}) *vim.deep_equal()* @@ -1501,8 +1574,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 +1588,40 @@ 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: + + >lua + + 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 +1630,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|nil) If `true` use `sep` literally (passed to string.find) Return: ~ @@ -1544,6 +1640,7 @@ gsplit({s}, {sep}, {plain}) *vim.gsplit()* See also: ~ |vim.split()| + |luaref-patterns| https://www.lua.org/pil/20.2.html http://lua-users.org/wiki/StringLibraryTutorial @@ -1551,7 +1648,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 +1659,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 +1675,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|nil) Start range of slice + • {finish} (number|nil) 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 @@ -1597,28 +1694,40 @@ pesc({s}) *vim.pesc()* See also: ~ https://github.com/rxi/lume +spairs({t}) *vim.spairs()* + Enumerate a table sorted by its keys. + + Parameters: ~ + • {t} (table) List-like table + + Return: ~ + iterator over sorted keys and their values + + See also: ~ + Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua + split({s}, {sep}, {kwargs}) *vim.split()* Splits a string at each instance of a separator. - Examples: > + Examples: >lua - split(":aa::b:", ":") --> {'','aa','','b',''} - split("axaby", "ab?") --> {'','x','y'} - split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} + 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'} < 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 + string[] List of split components See also: ~ |vim.gsplit()| @@ -1627,8 +1736,8 @@ 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 +1749,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,22 +1758,23 @@ 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` tbl_count({t}) *vim.tbl_count()* Counts the number of non-nil values in table `t`. -> - vim.tbl_count({ a=1, b=2 }) => 2 - vim.tbl_count({ 1, 2 }) => 2 + >lua + + vim.tbl_count({ a=1, b=2 }) --> 2 + vim.tbl_count({ 1, 2 }) --> 2 < Parameters: ~ - {t} (table) Table + • {t} (table) Table Return: ~ (number) Number of non-nil values in table @@ -1676,29 +1786,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 +1820,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 +1831,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 @@ -1733,15 +1843,15 @@ tbl_get({o}, {...}) *vim.tbl_get()* Index into a table (first argument) via string keys passed as subsequent arguments. Return `nil` if the key does not exist. - Examples: > + Examples: >lua vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil < 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 +1861,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 +1877,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 +1887,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 +1899,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,27 +1910,28 @@ 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 See also: ~ + |luaref-patterns| https://www.lua.org/pil/20.2.html validate({opt}) *vim.validate()* Validates a parameter specification (types and values). - Usage example: > + Usage example: >lua function user.new(name, age, hobbies) vim.validate{ @@ -1832,29 +1943,29 @@ validate({opt}) *vim.validate()* end < - Examples with explicit argument values (can be run directly): > + Examples with explicit argument values (can be run directly): >lua vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} - => NOP (success) + --> NOP (success) vim.validate{arg1={1, 'table'}} - => error('arg1: expected table, got number') + --> error('arg1: expected table, got number') vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}} - => error('arg1: expected even number, got 3') + --> error('arg1: expected even number, got 3') < - If multiple types are valid they can be given as a list. > + If multiple types are valid they can be given as a list. >lua vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} - => NOP (success) + --> NOP (success) vim.validate{arg1={1, {'string', table'}}} - => error('arg1: expected string|table, got number') + --> error('arg1: expected string|table, got number') < 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 +1990,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 +1999,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 +2009,7 @@ uri_to_bufnr({uri}) *vim.uri_to_bufnr()* the uri already exists. Parameters: ~ - {uri} (string) + • {uri} (string) Return: ~ (number) bufnr @@ -1907,7 +2018,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 @@ -1919,7 +2030,7 @@ Lua module: ui *lua-ui* input({opts}, {on_confirm}) *vim.ui.input()* Prompts the user for input - Example: > + Example: >lua vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input) vim.o.shiftwidth = tonumber(input) @@ -1927,7 +2038,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,14 +2047,15 @@ 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. + typed (it might be an empty string if nothing was + entered), or `nil` if the user aborted the dialog. select({items}, {opts}, {on_choice}) *vim.ui.select()* Prompts the user to pick a single item from a collection of entries - Example: > + Example: >lua vim.ui.select({ 'tabs', 'spaces' }, { prompt = 'Select tabs or spaces:', @@ -1960,8 +2072,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 +2083,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,14 +2111,14 @@ 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. - Note that Lua filetype detection is disabled when |g:do_legacy_filetype| - is set. - - Example: > + Example: >lua vim.filetype.add({ extension = { @@ -2029,6 +2141,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' @@ -2040,7 +2154,7 @@ add({filetypes}) *vim.filetype.add()* }) < - To add a fallback match on contents (see |new-filetype-scripts|), use > + To add a fallback match on contents, use >lua vim.filetype.add { pattern = { @@ -2060,7 +2174,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()* @@ -2079,23 +2193,24 @@ match({args}) *vim.filetype.match()* Each of the three options is specified using a key to the single argument of this function. Example: -> - -- Using a buffer number - vim.filetype.match({ buf = 42 }) + >lua + + -- Using a buffer number + vim.filetype.match({ buf = 42 }) - -- Override the filename of the given buffer - vim.filetype.match({ buf = 42, filename = 'foo.c' }) + -- Override the filename of the given buffer + vim.filetype.match({ buf = 42, filename = 'foo.c' }) - -- Using a filename without a buffer - vim.filetype.match({ filename = 'main.lua' }) + -- Using a filename without a buffer + vim.filetype.match({ filename = 'main.lua' }) - -- Using file contents - vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) + -- Using file contents + vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) < 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} @@ -2121,7 +2236,7 @@ match({args}) *vim.filetype.match()* Lua module: keymap *lua-keymap* del({modes}, {lhs}, {opts}) *vim.keymap.del()* - Remove an existing mapping. Examples: > + Remove an existing mapping. Examples: >lua vim.keymap.del('n', 'lhs') @@ -2129,7 +2244,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. @@ -2137,7 +2252,7 @@ del({modes}, {lhs}, {opts}) *vim.keymap.del()* |vim.keymap.set()| set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* - Add a new |mapping|. Examples: > + Add a new |mapping|. Examples: >lua -- Can add mapping to Lua functions vim.keymap.set('n', 'lhs', function() print("real lua function") end) @@ -2156,25 +2271,25 @@ set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)') < - Note that in a mapping like: > + Note that in a mapping like: >lua vim.keymap.set('n', 'asdf', require('jkl').my_fun) < the `require('jkl')` gets evaluated during this call in order to access the function. If you want to avoid this cost at startup you can wrap it in a function, for - example: > + example: >lua vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end) < 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,18 +2315,23 @@ 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} -dir({path}) *vim.fs.dir()* +dir({path}, {opts}) *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()|. + • {opts} table|nil Optional keyword arguments: + • depth: integer|nil How deep the traverse (default 1) + • skip: (fun(dir_name: string): boolean)|nil Predicate to + control traversal. Return false to stop searching the + current directory. Only useful when depth > 1 Return: ~ Iterator over files and directories in {path}. Each iteration yields @@ -2222,7 +2342,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} @@ -2236,15 +2356,18 @@ find({names}, {opts}) *vim.fs.find()* searches are recursive and may search through many directories! If {stop} is non-nil, then the search stops when the directory given in {stop} is reached. The search terminates when {limit} (default 1) matches are found. - The search can be narrowed to find only files or or only directories by + The search can be narrowed to find only files or only directories by 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. The function is called per file and + directory within the traversed directories to test if they + match {names}. + • {opts} (table) Optional keyword arguments: • path (string): Path to begin searching from. If omitted, - the current working directory is used. + the |current-directory| is used. • upward (boolean, default false): If true, search upward through parent directories. Otherwise, search through child directories (recursively). @@ -2252,13 +2375,14 @@ find({names}, {opts}) *vim.fs.find()* reached. The directory itself is not searched. • type (string): Find only files ("file") or directories ("directory"). If omitted, both files and directories that - match {name} are included. + match {names} are included. • limit (number, default 1): Stop the search after finding this many matches. Use `math.huge` to place no limit on the number of matches. Return: ~ - (table) The paths of all matching files or directories + (table) Normalized paths |vim.fs.normalize()| of all matching files or + directories normalize({path}) *vim.fs.normalize()* Normalize a path to a standard format. A tilde (~) character at the @@ -2266,20 +2390,20 @@ normalize({path}) *vim.fs.normalize()* backslash (\) characters are converted to forward slashes (/). Environment variables are also expanded. - Example: > + Examples: >lua - vim.fs.normalize('C:\Users\jdoe') - => 'C:/Users/jdoe' + vim.fs.normalize('C:\\Users\\jdoe') + --> 'C:/Users/jdoe' - vim.fs.normalize('~/src/neovim') - => '/home/jdoe/src/neovim' + vim.fs.normalize('~/src/neovim') + --> '/home/jdoe/src/neovim' - vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') - => '/Users/jdoe/.config/nvim/init.vim' + vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') + --> '/Users/jdoe/.config/nvim/init.vim' < Parameters: ~ - {path} (string) Path to normalize + • {path} (string) Path to normalize Return: ~ (string) Normalized path @@ -2287,7 +2411,7 @@ normalize({path}) *vim.fs.normalize()* parents({start}) *vim.fs.parents()* Iterate over all the parents of the given file or directory. - Example: > + Example: >lua local root_dir for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do @@ -2303,9 +2427,49 @@ parents({start}) *vim.fs.parents()* < Parameters: ~ - {start} (string) Initial file or directory. + • {start} (string) Initial file or directory. Return: ~ (function) Iterator + +============================================================================== +Lua module: secure *lua-secure* + +read({path}) *vim.secure.read()* + Attempt to read the file at {path} prompting the user if the file should + be trusted. The user's choice is persisted in a trust database at + $XDG_STATE_HOME/nvim/trust. + + Parameters: ~ + • {path} (string) Path to a file to read. + + Return: ~ + (string|nil) The contents of the given file if it exists and is + trusted, or nil otherwise. + + See also: ~ + |:trust| + +trust({opts}) *vim.secure.trust()* + Manage the trust database. + + The trust database is located at |$XDG_STATE_HOME|/nvim/trust. + + Parameters: ~ + • {opts} (table) + • action (string): "allow" to add a file to the trust database + and trust it, "deny" to add a file to the trust database and + deny it, "remove" to remove file from the trust database + • path (string|nil): Path to a file to update. Mutually + exclusive with {bufnr}. Cannot be used when {action} is + "allow". + • bufnr (number|nil): Buffer number to update. Mutually + exclusive with {path}. + + Return: ~ + (boolean, string) success, msg: + • true and full path of target file if operation was successful + • false and error message on failure + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/luaref.txt b/runtime/doc/luaref.txt index 9dbd2d4de5..aafdd5c43e 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* @@ -203,7 +136,7 @@ For convenience, when the opening long bracket is immediately followed by a newline, the newline is not included in the string. As an example, in a system using ASCII (in which `a` is coded as 97, newline is coded as 10, and `1` is coded as 49), the five literals below denote the same string: -> +>lua a = 'alo\n123"' a = "alo\n123\"" a = '\97lo\10\04923"' @@ -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,13 +277,13 @@ 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|.) An access to a global variable `x` is equivalent to `_env.x`, which in turn is equivalent to -> +>lua gettable_event(_env, "x") < where `_env` is the environment of the running function. (The `_env` variable is @@ -433,13 +366,13 @@ before the adjustment (except when the call is enclosed in parentheses; see The assignment statement first evaluates all its expressions and only then are the assignments performed. Thus the code -> +>lua i = 3 i, a[i] = i+1, 20 < sets `a[3]` to 20, without affecting `a[4]` because the `i` in `a[i]` is evaluated (to 3) before it is assigned 4. Similarly, the line -> +>lua x, y = y, x < exchanges the values of `x` and `y`. @@ -452,7 +385,7 @@ defined or callable in Lua. We use it here only for explanatory purposes.) An assignment to a global variable `x = val` is equivalent to the assignment `_env.x = val`, which in turn is equivalent to -> +>lua settable_event(_env, "x", val) < where `_env` is the environment of the running function. (The `_env` variable is @@ -517,19 +450,20 @@ The `block` is repeated for `name` starting at the value of the first `exp`, unt it passes the second `exp` by steps of the third `exp`. More precisely, 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: >lua - `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: >lua + 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|). @@ -648,7 +582,7 @@ adjusts the result list to one element, discarding all values except the first one. Here are some examples: -> +>lua f() -- adjusted to 0 results g(f(), x) -- f() is adjusted to 1 result g(x, f()) -- g gets x plus all results from f() @@ -681,7 +615,7 @@ or strings that can be converted to numbers (see |luaref-langCoercion|), then al operations have the usual meaning. Exponentiation works for any exponent. For instance, `x^(-0.5)` computes the inverse of the square root of `x`. Modulo is defined as -> +>lua a % b == a - math.floor(a/b)*b < That is, it is the remainder of a division that rounds the quotient towards @@ -808,11 +742,11 @@ key `exp1` and value `exp2`. A field of the form `name = exp` is equivalent to `["name"] = exp`. Finally, fields of the form `exp` are equivalent to `[i] = exp`, where `i` are consecutive numerical integers, starting with 1. Fields in the other formats do not affect this counting. For example, -> +>lua a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } < is equivalent to -> +>lua do local t = {} t[f(1)] = g @@ -868,7 +802,7 @@ argument list is a single new table. A call of the form `f'` `string` `'` As an exception to the free-format syntax of Lua, you cannot put a line break before the `(` in a function call. This restriction avoids some ambiguities in the language. If you write -> +>lua a = f (g).x(a) < @@ -886,7 +820,7 @@ function. Note that a tail call only happens with a particular syntax, where the `return` has one single function call as argument; this syntax makes the calling function return exactly the returns of the called function. So, none of the following examples are tail calls: -> +>lua return (f(x)) -- results adjusted to 1 return 2 * f(x) return x, f(x) -- additional results @@ -967,7 +901,7 @@ expression is used as the last element of a list of expressions, then no adjustment is made (unless the call is enclosed in parentheses). As an example, consider the following definitions: -> +>lua function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end @@ -1008,7 +942,7 @@ is syntactic sugar for Lua is a lexically scoped language. The scope of variables begins at the first statement after their declaration and lasts until the end of the innermost block that includes the declaration. Consider the following example: -> +>lua x = 10 -- global variable do -- new block local x = x -- new `x`, with value 10 @@ -1033,7 +967,7 @@ function. Notice that each execution of a local statement defines new local variables. Consider the following example: -> +>lua a = {} local x = 20 for i=1,10 do @@ -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 @@ -1109,7 +1043,7 @@ given object, we use the expression metatable(obj)[event] < This should be read as -> +>lua rawget(metatable(obj) or {}, event) < That is, the access to a metamethod does not invoke other metamethods, and the @@ -1123,13 +1057,13 @@ the `+` operation. The function `getbinhandler` below defines how Lua chooses a handler for a binary operation. First, Lua tries the first operand. If its type does not define a handler for the operation, then Lua tries the second operand. -> +>lua function getbinhandler (op1, op2, event) return metatable(op1)[event] or metatable(op2)[event] end < By using this function, the behavior of the `op1 + op2` is -> +>lua function add_event (op1, op2) local o1, o2 = tonumber(op1), tonumber(op2) if o1 and o2 then -- both operands are numeric? @@ -1170,7 +1104,7 @@ with the function `pow` (from the C math library) as the primitive operation. "unm": *__unm()* ------ the unary `-` operation. -> +>lua function unm_event (op) local o = tonumber(op) if o then -- operand is numeric? @@ -1190,7 +1124,7 @@ the unary `-` operation. "concat": *__concat()* --------- the `..` (concatenation) operation. -> +>lua function concat_event (op1, op2) if (type(op1) == "string" or type(op1) == "number") and (type(op2) == "string" or type(op2) == "number") then @@ -1208,7 +1142,7 @@ the `..` (concatenation) operation. "len": *__len()* ------ the `#` operation. -> +>lua function len_event (op) if type(op) == "string" then return strlen(op) -- primitive string length @@ -1233,7 +1167,7 @@ The function `getcomphandler` defines how Lua chooses a metamethod for comparison operators. A metamethod only is selected when both objects being compared have the same type and the same metamethod for the selected operation. -> +>lua function getcomphandler (op1, op2, event) if type(op1) ~= type(op2) then return nil end local mm1 = metatable(op1)[event] @@ -1242,7 +1176,7 @@ operation. end < The "eq" event is defined as follows: -> +>lua function eq_event (op1, op2) if type(op1) ~= type(op2) then -- different types? return false -- different objects @@ -1264,7 +1198,7 @@ The "eq" event is defined as follows: "lt": *__lt()* ----- the `<` operation. -> +>lua function lt_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 < op2 -- numeric comparison @@ -1285,7 +1219,7 @@ the `<` operation. "le": *__le()* ----- the `<=` operation. -> +>lua function le_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 <= op2 -- numeric comparison @@ -1313,7 +1247,7 @@ to `not (b < a)`. "index": *__index()* -------- The indexing access `table[key]`. -> +>lua function gettable_event (table, key) local h if type(table) == "table" then @@ -1335,7 +1269,7 @@ The indexing access `table[key]`. "newindex": *__newindex()* ----------- The indexing assignment `table[key] = value`. -> +>lua function settable_event (table, key, value) local h if type(table) == "table" then @@ -1357,7 +1291,7 @@ The indexing assignment `table[key] = value`. "call": *__call()* ------- called when Lua calls a value. -> +>lua function function_event (func, ...) if type(func) == "function" then return func(...) -- primitive call @@ -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). @@ -1452,7 +1386,7 @@ Garbage userdata with a field `__gc` in their metatables are not collected immediately by the garbage collector. Instead, Lua puts them in a list. After the collection, Lua does the equivalent of the following function for each userdata in that list: -> +>lua function gc_event (udata) local h = metatable(udata).__gc if h then @@ -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 @@ -1535,7 +1469,7 @@ coroutine. Any arguments passed to this function go as extra arguments to propagated to the caller. As an example, consider the next code: -> +>lua function foo1 (a) print("foo", a) return coroutine.yield(2*a) @@ -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 @@ -1626,7 +1559,7 @@ Most query functions accept as indices any value inside the available stack space, that is, indices up to the maximum stack size you have set through `lua_checkstack`. Such indices are called acceptable indices. More formally, we define an acceptable index as follows: -> +>lua (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace) < Note that 0 is never an acceptable index. @@ -1647,7 +1580,7 @@ pseudo-index `LUA_ENVIRONINDEX`. To access and change the value of global variables, you can use regular table operations over an environment table. For instance, to access the value of a global variable, do -> +>c lua_getfield(L, LUA_GLOBALSINDEX, varname); < @@ -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* @@ -1706,7 +1639,7 @@ Inside a C function you can raise an error by calling `lua_error` (see Here we list all functions and types from the C API in alphabetical order. lua_Alloc *lua_Alloc()* -> +>c typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, @@ -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,8 +1662,8 @@ 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()|). +>c static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ @@ -1747,7 +1680,7 @@ lua_Alloc *lua_Alloc()* behaviors. lua_atpanic *lua_atpanic()* -> +>c lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf); < Sets a new panic function and returns the old one. @@ -1761,7 +1694,7 @@ lua_atpanic *lua_atpanic()* stack. lua_call *lua_call()* -> +>c void lua_call (lua_State *L, int nargs, int nresults); < Calls a function. @@ -1785,11 +1718,11 @@ lua_call *lua_call()* The following example shows how the host program may do the equivalent to this Lua code: -> +>lua a = f("how", t.x, 14) < Here it is in C: -> +>c lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be called lua_pushstring(L, "how"); // 1st argument lua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexed @@ -1804,7 +1737,7 @@ lua_call *lua_call()* practice. lua_CFunction *luaref-cfunction* *lua_CFunction()* -> +>c typedef int (*lua_CFunction) (lua_State *L); < Type for C functions. @@ -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, @@ -1825,7 +1758,7 @@ lua_CFunction *luaref-cfunction* *lua_CFunction()* *luaref-cfunctionexample* As an example, the following function receives a variable number of numerical arguments and returns their average and sum: -> +>c static int foo (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0; @@ -1844,7 +1777,7 @@ lua_CFunction *luaref-cfunction* *lua_CFunction()* < lua_checkstack *lua_checkstack()* -> +>c int lua_checkstack (lua_State *L, int extra); < Ensures that there are at least `extra` free stack slots in the stack. @@ -1853,7 +1786,7 @@ lua_checkstack *lua_checkstack()* the new size, it is left unchanged. lua_close *lua_close()* -> +>c void lua_close (lua_State *L); < Destroys all objects in the given Lua state (calling the corresponding @@ -1865,7 +1798,7 @@ lua_close *lua_close()* are not needed, to avoid growing too large. lua_concat *lua_concat()* -> +>c void lua_concat (lua_State *L, int n); < Concatenates the `n` values at the top of the stack, pops them, and @@ -1875,35 +1808,35 @@ lua_concat *lua_concat()* usual semantics of Lua (see |luaref-langConcat|). lua_cpcall *lua_cpcall()* -> +>c int lua_cpcall (lua_State *L, lua_CFunction func, void *ud); < 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. lua_createtable *lua_createtable()* -> +>c void lua_createtable (lua_State *L, int narr, int nrec); < Creates a new empty table and pushes it onto the stack. The new table 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()* -> +>c int lua_dump (lua_State *L, lua_Writer writer, void *data); < Dumps a function as a binary chunk. Receives a Lua function on the top 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. @@ -1911,7 +1844,7 @@ lua_dump *lua_dump()* This function does not pop the Lua function from the stack. lua_equal *lua_equal()* -> +>c int lua_equal (lua_State *L, int index1, int index2); < Returns 1 if the two values in acceptable indices `index1` and @@ -1920,15 +1853,15 @@ lua_equal *lua_equal()* if any of the indices is non valid. lua_error *lua_error()* -> +>c int lua_error (lua_State *L); < 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()* -> +>c int lua_gc (lua_State *L, int what, int data); < Controls the garbage collector. @@ -1936,46 +1869,46 @@ 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. lua_getallocf *lua_getallocf()* -> +>c lua_Alloc lua_getallocf (lua_State *L, void **ud); < 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()* -> +>c void lua_getfenv (lua_State *L, int index); < Pushes onto the stack the environment table of the value at the given index. lua_getfield *lua_getfield()* -> +>c void lua_getfield (lua_State *L, int index, const char *k); < Pushes onto the stack the value `t[k]`, where `t` is the value at the @@ -1983,17 +1916,17 @@ lua_getfield *lua_getfield()* metamethod for the "index" event (see |luaref-langMetatables|). lua_getglobal *lua_getglobal()* -> +>c void lua_getglobal (lua_State *L, const char *name); < Pushes onto the stack the value of the global `name`. It is defined as a macro: -> +>c #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s) < lua_getmetatable *lua_getmetatable()* -> +>c int lua_getmetatable (lua_State *L, int index); < Pushes onto the stack the metatable of the value at the given @@ -2002,7 +1935,7 @@ lua_getmetatable *lua_getmetatable()* stack. lua_gettable *lua_gettable()* -> +>c void lua_gettable (lua_State *L, int index); < Pushes onto the stack the value `t[k]`, where `t` is the value at the @@ -2014,7 +1947,7 @@ lua_gettable *lua_gettable()* the "index" event (see |luaref-langMetatables|). lua_gettop *lua_gettop()* -> +>c int lua_gettop (lua_State *L); < Returns the index of the top element in the stack. Because indices @@ -2023,7 +1956,7 @@ lua_gettop *lua_gettop()* 0 means an empty stack). lua_insert *lua_insert()* -> +>c void lua_insert (lua_State *L, int index); < Moves the top element into the given valid index, shifting up the @@ -2031,7 +1964,7 @@ lua_insert *lua_insert()* pseudo-index, because a pseudo-index is not an actual stack position. lua_Integer *lua_Integer()* -> +>c typedef ptrdiff_t lua_Integer; < The type used by the Lua API to represent integral values. @@ -2040,77 +1973,77 @@ lua_Integer *lua_Integer()* type the machine handles "comfortably". lua_isboolean *lua_isboolean()* -> +>c int lua_isboolean (lua_State *L, int index); < Returns 1 if the value at the given acceptable index has type boolean, and 0 otherwise. lua_iscfunction *lua_iscfunction()* -> +>c int lua_iscfunction (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a C function, and 0 otherwise. lua_isfunction *lua_isfunction()* -> +>c int lua_isfunction (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a function (either C or Lua), and 0 otherwise. lua_islightuserdata *lua_islightuserdata()* -> +>c int lua_islightuserdata (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a light userdata, and 0 otherwise. lua_isnil *lua_isnil()* -> +>c int lua_isnil (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is `nil`, and 0 otherwise. lua_isnumber *lua_isnumber()* -> +>c int lua_isnumber (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a number or a string convertible to a number, and 0 otherwise. lua_isstring *lua_isstring()* -> +>c int lua_isstring (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a string or a number (which is always convertible to a string), and 0 otherwise. lua_istable *lua_istable()* -> +>c int lua_istable (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a table, and 0 otherwise. lua_isthread *lua_isthread()* -> +>c int lua_isthread (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a thread, and 0 otherwise. lua_isuserdata *lua_isuserdata()* -> +>c int lua_isuserdata (lua_State *L, int index); < Returns 1 if the value at the given acceptable index is a userdata (either full or light), and 0 otherwise. lua_lessthan *lua_lessthan()* -> +>c int lua_lessthan (lua_State *L, int index1, int index2); < Returns 1 if the value at acceptable index `index1` is smaller than @@ -2119,7 +2052,7 @@ lua_lessthan *lua_lessthan()* Also returns 0 if any of the indices is non valid. lua_load *lua_load()* -> +>c int lua_load (lua_State *L, lua_Reader reader, void *data, @@ -2136,17 +2069,17 @@ 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 error messages and in debug information (see |luaref-apiDebug|). lua_newstate *lua_newstate()* -> +>c lua_State *lua_newstate (lua_Alloc f, void *ud); < Creates a new, independent state. Returns `NULL` if cannot create the @@ -2156,19 +2089,19 @@ lua_newstate *lua_newstate()* simply passes to the allocator in every call. lua_newtable *lua_newtable()* -> +>c void lua_newtable (lua_State *L); < 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()* -> +>c 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. @@ -2177,7 +2110,7 @@ lua_newthread *lua_newthread()* are subject to garbage collection, like any Lua object. lua_newuserdata *lua_newuserdata()* -> +>c void *lua_newuserdata (lua_State *L, size_t size); < This function allocates a new block of memory with the given size, @@ -2195,7 +2128,7 @@ lua_newuserdata *lua_newuserdata()* is collected again then Lua frees its corresponding memory. lua_next *lua_next()* -> +>c int lua_next (lua_State *L, int index); < Pops a key from the stack, and pushes a key-value pair from the table @@ -2205,7 +2138,7 @@ lua_next *lua_next()* *luaref-tabletraversal* A typical traversal looks like this: -> +>c /* table is in the stack at index 't' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { @@ -2218,12 +2151,12 @@ 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`. lua_Number *lua_Number()* -> +>c typedef double lua_Number; < The type of numbers in Lua. By default, it is double, but that can be @@ -2233,7 +2166,7 @@ lua_Number *lua_Number()* another type for numbers (e.g., float or long). lua_objlen *lua_objlen()* -> +>c size_t lua_objlen (lua_State *L, int index); < Returns the "length" of the value at the given acceptable index: for @@ -2242,13 +2175,13 @@ lua_objlen *lua_objlen()* block of memory allocated for the userdata; for other values, it is 0. lua_pcall *lua_pcall()* -> +>c lua_pcall (lua_State *L, int nargs, int nresults, int errfunc); < 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`, @@ -2277,19 +2210,19 @@ lua_pcall *lua_pcall()* - `LUA_ERRERR` error while running the error handler function. lua_pop *lua_pop()* -> +>c void lua_pop (lua_State *L, int n); < Pops `n` elements from the stack. lua_pushboolean *lua_pushboolean()* -> +>c void lua_pushboolean (lua_State *L, int b); < Pushes a boolean value with value `b` onto the stack. lua_pushcclosure *lua_pushcclosure()* -> +>c void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); < Pushes a new C closure onto the stack. @@ -2305,7 +2238,7 @@ lua_pushcclosure *lua_pushcclosure()* pops these values from the stack. lua_pushcfunction *lua_pushcfunction()* -> +>c void lua_pushcfunction (lua_State *L, lua_CFunction f); < Pushes a C function onto the stack. This function receives a pointer @@ -2314,15 +2247,15 @@ 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: -> +>c #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0) < lua_pushfstring *lua_pushfstring()* -> +>c const char *lua_pushfstring (lua_State *L, const char *fmt, ...); < Pushes onto the stack a formatted string and returns a pointer to this @@ -2341,13 +2274,13 @@ lua_pushfstring *lua_pushfstring()* character). lua_pushinteger *lua_pushinteger()* -> +>c void lua_pushinteger (lua_State *L, lua_Integer n); < Pushes a number with value `n` onto the stack. lua_pushlightuserdata *lua_pushlightuserdata()* -> +>c void lua_pushlightuserdata (lua_State *L, void *p); < Pushes a light userdata onto the stack. @@ -2359,7 +2292,7 @@ lua_pushlightuserdata *lua_pushlightuserdata()* same C address. lua_pushlstring *lua_pushlstring()* -> +>c void lua_pushlstring (lua_State *L, const char *s, size_t len); < Pushes the string pointed to by `s` with size `len` onto the stack. @@ -2368,19 +2301,19 @@ lua_pushlstring *lua_pushlstring()* returns. The string can contain embedded zeros. lua_pushnil *lua_pushnil()* -> +>c void lua_pushnil (lua_State *L); < Pushes a nil value onto the stack. lua_pushnumber *lua_pushnumber()* -> +>c void lua_pushnumber (lua_State *L, lua_Number n); < Pushes a number with value `n` onto the stack. lua_pushstring *lua_pushstring()* -> +>c void lua_pushstring (lua_State *L, const char *s); < Pushes the zero-terminated string pointed to by `s` onto the stack. @@ -2390,30 +2323,30 @@ lua_pushstring *lua_pushstring()* end at the first zero. lua_pushthread *lua_pushthread()* -> +>c int lua_pushthread (lua_State *L); < Pushes the thread represented by `L` onto the stack. Returns 1 if this thread is the main thread of its state. lua_pushvalue *lua_pushvalue()* -> +>c void lua_pushvalue (lua_State *L, int index); < Pushes a copy of the element at the given valid index onto the stack. lua_pushvfstring *lua_pushvfstring()* -> +>c const char *lua_pushvfstring (lua_State *L, 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. lua_rawequal *lua_rawequal()* -> +>c int lua_rawequal (lua_State *L, int index1, int index2); < Returns 1 if the two values in acceptable indices `index1` and @@ -2422,14 +2355,14 @@ lua_rawequal *lua_rawequal()* valid. lua_rawget *lua_rawget()* -> +>c 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()* -> +>c void lua_rawgeti (lua_State *L, int index, int n); < Pushes onto the stack the value `t[n]`, where `t` is the value at the @@ -2437,14 +2370,14 @@ lua_rawgeti *lua_rawgeti()* invoke metamethods. lua_rawset *lua_rawset()* -> +>c 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()* -> +>c void lua_rawseti (lua_State *L, int index, int n); < Does the equivalent of `t[n] = v`, where `t` is the value at the given @@ -2454,12 +2387,12 @@ lua_rawseti *lua_rawseti()* that is, it does not invoke metamethods. lua_Reader *lua_Reader()* -> +>c typedef const char * (*lua_Reader) (lua_State *L, 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 @@ -2469,20 +2402,20 @@ lua_Reader *lua_Reader()* zero. lua_register *lua_register()* -> +>c void lua_register (lua_State *L, const char *name, lua_CFunction f); < Sets the C function `f` as the new value of global `name`. It is defined as a macro: -> +>c #define lua_register(L,n,f) \ (lua_pushcfunction(L, f), lua_setglobal(L, n)) < lua_remove *lua_remove()* -> +>c void lua_remove (lua_State *L, int index); < Removes the element at the given valid index, shifting down the @@ -2490,7 +2423,7 @@ lua_remove *lua_remove()* pseudo-index, because a pseudo-index is not an actual stack position. lua_replace *lua_replace()* -> +>c void lua_replace (lua_State *L, int index); < Moves the top element into the given position (and pops it), without @@ -2498,35 +2431,35 @@ lua_replace *lua_replace()* position). lua_resume *lua_resume()* -> +>c int lua_resume (lua_State *L, int narg); < 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`, and then call `lua_resume`. lua_setallocf *lua_setallocf()* -> +>c void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); < Changes the allocator function of a given state to `f` with user data `ud`. lua_setfenv *lua_setfenv()* -> +>c int lua_setfenv (lua_State *L, int index); < Pops a table from the stack and sets it as the new environment for the @@ -2535,7 +2468,7 @@ lua_setfenv *lua_setfenv()* Otherwise it returns 1. lua_setfield *lua_setfield()* -> +>c void lua_setfield (lua_State *L, int index, const char *k); < Does the equivalent to `t[k] = v`, where `t` is the value at the given @@ -2546,24 +2479,24 @@ lua_setfield *lua_setfield()* |luaref-langMetatables|). lua_setglobal *lua_setglobal()* -> +>c void lua_setglobal (lua_State *L, const char *name); < Pops a value from the stack and sets it as the new value of global `name`. It is defined as a macro: -> +>c #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s) < lua_setmetatable *lua_setmetatable()* -> +>c int lua_setmetatable (lua_State *L, int index); < Pops a table from the stack and sets it as the new metatable for the value at the given acceptable index. lua_settable *lua_settable()* -> +>c void lua_settable (lua_State *L, int index); < Does the equivalent to `t[k] = v`, where `t` is the value at the given @@ -2575,7 +2508,7 @@ lua_settable *lua_settable()* (see |luaref-langMetatables|). lua_settop *lua_settop()* -> +>c void lua_settop (lua_State *L, int index); < Accepts any acceptable index, or 0, and sets the stack top to this @@ -2584,7 +2517,7 @@ lua_settop *lua_settop()* elements are removed. lua_State *lua_State()* -> +>c typedef struct lua_State lua_State; < Opaque structure that keeps the whole state of a Lua interpreter. The @@ -2593,10 +2526,10 @@ 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()* -> +>c int lua_status (lua_State *L); < Returns the status of the thread `L`. @@ -2606,7 +2539,7 @@ lua_status *lua_status()* suspended. lua_toboolean *lua_toboolean()* -> +>c int lua_toboolean (lua_State *L, int index); < Converts the Lua value at the given acceptable index to a C boolean @@ -2614,21 +2547,21 @@ 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()* -> +>c lua_CFunction lua_tocfunction (lua_State *L, int index); < Converts a value at the given acceptable index to a C function. That value must be a C function; otherwise it returns `NULL`. lua_tointeger *lua_tointeger()* -> +>c 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. @@ -2636,7 +2569,7 @@ lua_tointeger *lua_tointeger()* way. lua_tolstring *lua_tolstring()* -> +>c const char *lua_tolstring (lua_State *L, int index, size_t *len); < Converts the Lua value at the given acceptable index to a C string. If @@ -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 @@ -2655,16 +2588,16 @@ lua_tolstring *lua_tolstring()* value is removed from the stack. lua_tonumber *lua_tonumber()* -> +>c 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. lua_topointer *lua_topointer()* -> +>c const void *lua_topointer (lua_State *L, int index); < Converts the value at the given acceptable index to a generic C @@ -2676,22 +2609,22 @@ lua_topointer *lua_topointer()* Typically this function is used only for debug information. lua_tostring *lua_tostring()* -> +>c 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()* -> +>c 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()* -> +>c void *lua_touserdata (lua_State *L, int index); < If the value at the given acceptable index is a full userdata, returns @@ -2699,7 +2632,7 @@ lua_touserdata *lua_touserdata()* pointer. Otherwise, it returns `NULL`. lua_type *lua_type()* -> +>c int lua_type (lua_State *L, int index); < Returns the type of the value in the given acceptable index, or @@ -2710,20 +2643,20 @@ lua_type *lua_type()* `LUA_TUSERDATA`, `LUA_TTHREAD`, and `LUA_TLIGHTUSERDATA`. lua_typename *lua_typename()* -> +>c const char *lua_typename (lua_State *L, int tp); < Returns the name of the type encoded by the value `tp`, which must be one the values returned by `lua_type`. lua_Writer *lua_Writer()* -> +>c typedef int (*lua_Writer) (lua_State *L, const void* p, 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`. @@ -2732,7 +2665,7 @@ lua_Writer *lua_Writer()* means an error and stops `lua_dump` from calling the writer again. lua_xmove *lua_xmove()* -> +>c void lua_xmove (lua_State *from, lua_State *to, int n); < Exchange values between different threads of the `same` global state. @@ -2741,19 +2674,19 @@ lua_xmove *lua_xmove()* onto the stack `to`. lua_yield *lua_yield()* -> +>c int lua_yield (lua_State *L, int nresults); < Yields a coroutine. This function should only be called as the return expression of a C function, as follows: -> +>c return lua_yield (L, nresults); < 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;` +>c + 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 @@ -2833,40 +2768,40 @@ The fields of `lua_Debug` have the following meaning: upvalues of the function. lua_gethook *lua_gethook()* -> +>c lua_Hook lua_gethook (lua_State *L); < Returns the current hook function. lua_gethookcount *lua_gethookcount()* -> +>c int lua_gethookcount (lua_State *L); < Returns the current hook count. lua_gethookmask *lua_gethookmask()* -> +>c int lua_gethookmask (lua_State *L); < Returns the current hook mask. lua_getinfo *lua_getinfo()* -> +>c int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); < Returns information about a specific function or function invocation. 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, `lua_getinfo` pops the function in the top of the stack.) For instance, to know in which line a function `f` was defined, you can write the following code: -> +>c lua_Debug ar; lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */ lua_getinfo(L, ">S", &ar); @@ -2891,13 +2826,13 @@ lua_getinfo *lua_getinfo()* `what`). lua_getlocal *lua_getlocal()* -> +>c const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n); < 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 @@ -2911,12 +2846,12 @@ lua_getlocal *lua_getlocal()* number of active local variables. lua_getstack *lua_getstack()* -> +>c int lua_getstack (lua_State *L, int level, lua_Debug *ar); < 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 @@ -2924,7 +2859,7 @@ lua_getstack *lua_getstack()* with a level greater than the stack depth, it returns 0. lua_getupvalue *lua_getupvalue()* -> +>c const char *lua_getupvalue (lua_State *L, int funcindex, int n); < Gets information about a closure's upvalue. (For Lua functions, @@ -2940,7 +2875,7 @@ lua_getupvalue *lua_getupvalue()* string `""` as a name for all upvalues. lua_Hook *lua_Hook()* -> +>c typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); < Type for debugging hook functions. @@ -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`. @@ -2962,7 +2897,7 @@ lua_Hook *lua_Hook()* lua_sethook *lua_sethook()* -> +>c int lua_sethook (lua_State *L, lua_Hook f, int mask, int count); < Sets the debugging hook function. @@ -2991,12 +2926,12 @@ lua_sethook *lua_sethook()* A hook is disabled by setting `mask` to zero. lua_setlocal *lua_setlocal()* -> +>c const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n); < 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. @@ -3004,13 +2939,13 @@ lua_setlocal *lua_setlocal()* number of active local variables. lua_setupvalue *lua_setupvalue()* -> +>c const char *lua_setupvalue (lua_State *L, int funcindex, int n); < 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. @@ -3018,7 +2953,7 @@ lua_setupvalue *lua_setupvalue()* *luaref-debugexample* As an example, the following function lists the names of all local variables and upvalues for a function at a given level of the stack: -> +>c int listvars (lua_State *L, int level) { lua_Debug ar; int i; @@ -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 @@ -3068,46 +3002,46 @@ Here we list all functions and types from the auxiliary library in alphabetical order. luaL_addchar *luaL_addchar()* -> +>c 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()* -> +>c 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()* -> +>c 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()* -> +>c 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()* -> +>c 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 added to the buffer. luaL_argcheck *luaL_argcheck()* -> +>c void luaL_argcheck (lua_State *L, int cond, int narg, @@ -3120,7 +3054,7 @@ luaL_argcheck *luaL_argcheck()* < luaL_argerror *luaL_argerror()* -> +>c int luaL_argerror (lua_State *L, int narg, const char *extramsg); < Raises an error with the following message, where `func` is retrieved @@ -3132,7 +3066,7 @@ luaL_argerror *luaL_argerror()* functions as `return luaL_argerror(` `args` `)`. luaL_Buffer *luaL_Buffer()* -> +>c typedef struct luaL_Buffer luaL_Buffer; < Type for a `string buffer`. @@ -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,19 +3090,19 @@ 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. luaL_buffinit *luaL_buffinit()* -> +>c 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()* -> +>c int luaL_callmeta (lua_State *L, int obj, const char *e); < Calls a metamethod. @@ -3181,49 +3115,49 @@ luaL_callmeta *luaL_callmeta()* 0 (without pushing any value on the stack). luaL_checkany *luaL_checkany()* -> +>c void luaL_checkany (lua_State *L, int narg); < Checks whether the function has an argument of any type (including `nil`) at position `narg`. luaL_checkint *luaL_checkint()* -> +>c int luaL_checkint (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns this number cast to an `int`. luaL_checkinteger *luaL_checkinteger()* -> +>c 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()* -> +>c long luaL_checklong (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns this number cast to a `long`. luaL_checklstring *luaL_checklstring()* -> +>c const char *luaL_checklstring (lua_State *L, int narg, size_t *l); < Checks whether the function argument `narg` is a string and returns this string; if `l` is not `NULL` fills `*l` with the string's length. luaL_checknumber *luaL_checknumber()* -> +>c 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()* -> +>c int luaL_checkoption (lua_State *L, int narg, const char *def, @@ -3243,7 +3177,7 @@ luaL_checkoption *luaL_checkoption()* select options.) luaL_checkstack *luaL_checkstack()* -> +>c void luaL_checkstack (lua_State *L, int sz, const char *msg); < Grows the stack size to `top + sz` elements, raising an error if the @@ -3251,53 +3185,53 @@ luaL_checkstack *luaL_checkstack()* the error message. luaL_checkstring *luaL_checkstring()* -> +>c const char *luaL_checkstring (lua_State *L, int narg); < Checks whether the function argument `narg` is a string and returns this string. luaL_checktype *luaL_checktype()* -> +>c 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()* -> +>c 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()* -> +>c int luaL_dofile (lua_State *L, const char *filename); < Loads and runs the given file. It is defined as the following macro: -> +>c (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) < It returns 0 if there are no errors or 1 in case of errors. luaL_dostring *luaL_dostring()* -> +>c int luaL_dostring (lua_State *L, const char *str); < Loads and runs the given string. It is defined as the following macro: -> +>c (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) < It returns 0 if there are no errors or 1 in case of errors. luaL_error *luaL_error()* -> +>c int luaL_error (lua_State *L, const char *fmt, ...); < 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. @@ -3305,7 +3239,7 @@ luaL_error *luaL_error()* functions as `return luaL_error(` `args` `)`. luaL_getmetafield *luaL_getmetafield()* -> +>c int luaL_getmetafield (lua_State *L, int obj, const char *e); < Pushes onto the stack the field `e` from the metatable of the object @@ -3313,14 +3247,14 @@ luaL_getmetafield *luaL_getmetafield()* metatable does not have this field, returns 0 and pushes nothing. luaL_getmetatable *luaL_getmetatable()* -> +>c 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()* -> +>c const char *luaL_gsub (lua_State *L, const char *s, const char *p, @@ -3331,25 +3265,25 @@ luaL_gsub *luaL_gsub()* returns it. luaL_loadbuffer *luaL_loadbuffer()* -> +>c int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, 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 chunk name, used for debug information and error messages. luaL_loadfile *luaL_loadfile()* -> +>c 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 `#`. @@ -3359,11 +3293,11 @@ luaL_loadfile *luaL_loadfile()* As `lua_load`, this function only loads the chunk; it does not run it. luaL_loadstring *luaL_loadstring()* -> +>c 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`. @@ -3372,7 +3306,7 @@ luaL_loadstring *luaL_loadstring()* run it. luaL_newmetatable *luaL_newmetatable()* -> +>c int luaL_newmetatable (lua_State *L, const char *tname); < If the registry already has the key `tname`, returns 0. Otherwise, @@ -3383,27 +3317,27 @@ luaL_newmetatable *luaL_newmetatable()* `tname` in the registry. luaL_newstate *luaL_newstate()* -> +>c 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 error. luaL_openlibs *luaL_openlibs()* -> +>c void luaL_openlibs (lua_State *L); < Opens all standard Lua libraries into the given state. See also |luaref-openlibs| for details on how to open individual libraries. luaL_optint *luaL_optint()* -> +>c int luaL_optint (lua_State *L, int narg, int d); < If the function argument `narg` is a number, returns this number cast @@ -3411,17 +3345,17 @@ luaL_optint *luaL_optint()* Otherwise, raises an error. luaL_optinteger *luaL_optinteger()* -> +>c lua_Integer luaL_optinteger (lua_State *L, int narg, 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()* -> +>c long luaL_optlong (lua_State *L, int narg, long d); < If the function argument `narg` is a number, returns this number cast @@ -3429,7 +3363,7 @@ luaL_optlong *luaL_optlong()* Otherwise, raises an error. luaL_optlstring *luaL_optlstring()* -> +>c const char *luaL_optlstring (lua_State *L, int narg, const char *d, @@ -3442,7 +3376,7 @@ luaL_optlstring *luaL_optlstring()* If `l` is not `NULL`, fills the position `*l` with the results' length. luaL_optnumber *luaL_optnumber()* -> +>c lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d); < If the function argument `narg` is a number, returns this number. If @@ -3450,7 +3384,7 @@ luaL_optnumber *luaL_optnumber()* error. luaL_optstring *luaL_optstring()* -> +>c const char *luaL_optstring (lua_State *L, int narg, const char *d); @@ -3460,24 +3394,24 @@ luaL_optstring *luaL_optstring()* error. luaL_prepbuffer *luaL_prepbuffer()* -> +>c 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()* -> +>c void luaL_pushresult (luaL_Buffer *B); < Finishes the use of buffer `B` leaving the final string on the top of the stack. luaL_ref *luaL_ref()* -> +>c int luaL_ref (lua_State *L, int t); < Creates and returns a `reference`, in the table at index `t`, for the @@ -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 @@ -3495,19 +3429,19 @@ luaL_ref *luaL_ref()* different from any reference returned by `luaL_ref`. luaL_Reg *luaL_Reg()* -> +>c typedef struct luaL_Reg { const char *name; lua_CFunction func; } 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`. luaL_register *luaL_register()* -> +>c void luaL_register (lua_State *L, const char *libname, const luaL_Reg *l); @@ -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 @@ -3528,13 +3462,13 @@ luaL_register *luaL_register()* In any case the function leaves the table on the top of the stack. luaL_typename *luaL_typename()* -> +>c const char *luaL_typename (lua_State *L, int idx); < Returns the name of the type of the value at index `idx`. luaL_typerror *luaL_typerror()* -> +>c int luaL_typerror (lua_State *L, int narg, const char *tname); < Generates an error with a message like the following: @@ -3543,22 +3477,22 @@ 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()* -> +>c 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. If `ref` is `LUA_NOREF` or `LUA_REFNIL`, `luaL_unref` does nothing. luaL_where *luaL_where()* -> +>c void luaL_where (lua_State *L, int lvl); < Pushes onto the stack a string identifying the current position of the @@ -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,15 +3633,15 @@ 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 -> +>lua assert(loadstring(s))() < @@ -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 @@ -3823,7 +3756,7 @@ type({v}) *luaref-type()* unpack({list} [, {i} [, {j}]]) *luaref-unpack()* Returns the elements from the given table. This function is equivalent to -> +>lua return list[i], list[i+1], ..., list[j] < except that the above code can be written only for a fixed number of @@ -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. @@ -4088,11 +4021,11 @@ string.format({formatstring}, {...}) *string.format()* interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call -> +>lua string.format('%q', 'a string with "quotes" and \n new line') < will produce the string: -> +>lua "a string with \"quotes\" and \ new line" < @@ -4110,7 +4043,7 @@ string.gmatch({s}, {pattern}) *string.gmatch()* in each call. As an example, the following loop -> +>lua s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) @@ -4119,7 +4052,7 @@ string.gmatch({s}, {pattern}) *string.gmatch()* will iterate over all the words from string {s}, printing one per line. The next example collects all pairs `key=value` from the given string into a table: -> +>lua t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do @@ -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 @@ -4158,7 +4091,7 @@ string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsu{b}()* occurrence of `pattern` is replaced. Here are some examples: -> +>lua x = string.gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world" @@ -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,12 +4827,11 @@ debug.traceback([{thread},] [{message}] [,{level}]) *debug.traceback()* ============================================================================== A BIBLIOGRAPHY *luaref-bibliography* -============================================================================== This help file is a minor adaptation from this main reference: - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., - "Lua: 5.1 reference manual", http://www.lua.org/manual/5.1/manual.html + "Lua: 5.1 reference manual", https://www.lua.org/manual/5.1/manual.html Lua is discussed in these references: @@ -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,29 +4869,28 @@ 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 -(http://www.vim.org/scripts/script.php?script_id=614). +(https://www.vim.org/scripts/script.php?script_id=614). Adapted for bundled Nvim documentation; the original plugin can be found at -http://www.vim.org/scripts/script.php?script_id=1291 +https://www.vim.org/scripts/script.php?script_id=1291 ------------------------------------------------------------------------------ vi:tw=78:ts=4:ft=help:norl:et diff --git a/runtime/doc/luvref.txt b/runtime/doc/luvref.txt index ee45444b42..859e75e4af 100644 --- a/runtime/doc/luvref.txt +++ b/runtime/doc/luvref.txt @@ -3,7 +3,7 @@ LUV REFERENCE MANUAL - + *luvref* This file documents the Lua bindings for the LibUV library which is used for Nvim's event-loop and is accessible from Lua via |vim.loop| (e.g., |uv.version()| is exposed as `vim.loop.version()`). @@ -28,7 +28,7 @@ TCP Echo Server Example~ Here is a small example showing a TCP echo server: - > + >lua local uv = vim.loop local server = uv.new_tcp() @@ -97,7 +97,7 @@ used here to facilitate documenting consistent behavior: CONTENTS *luv-contents* This documentation is mostly a retelling of the libuv API documentation -(http://docs.libuv.org/en/v1.x/api.html) within the context of luv's Lua API. +(https://docs.libuv.org/en/v1.x/api.html) within the context of luv's Lua API. Low-level implementation details and unexposed C functions and types are not documented here except for when they are relevant to behavior seen in the Lua module. @@ -250,7 +250,7 @@ uv.loop_configure({option}, {...}) *uv.loop_configure()* An example of a valid call to this function is: - > + >lua uv.loop_configure("block_signal", "sigprof") < @@ -343,7 +343,7 @@ uv.walk({callback}) *uv.walk()* Returns: Nothing. - > + >lua -- Example usage of uv.walk to close all handles that -- aren't already closing. uv.walk(function (handle) @@ -613,7 +613,7 @@ uv.new_timer() *uv.new_timer()* Returns: `uv_timer_t userdata` or `fail` - > + >lua -- Creating a simple setTimeout wrapper local function setTimeout(timeout, callback) local timer = uv.new_timer() @@ -737,7 +737,7 @@ uv.timer_get_due_in({timer}) *uv.timer_get_due_in()* Prepare handles will run the given callback once per loop iteration, right before polling for I/O. - > + >lua local prepare = uv.new_prepare() prepare:start(function() print("Before I/O polling") @@ -782,7 +782,7 @@ uv.prepare_stop({prepare}) *uv.prepare_stop()* Check handles will run the given callback once per loop iteration, right after polling for I/O. - > + >lua local check = uv.new_check() check:start(function() print("After I/O polling") @@ -834,7 +834,7 @@ blocking for I/O. WARNING: Despite the name, idle handles will get their callbacks called on every loop iteration, not when the loop is actually "idle". - > + >lua local idle = uv.new_idle() idle:start(function() print("Before I/O polling, no blocking") @@ -879,7 +879,7 @@ uv.idle_stop({check}) *uv.idle_stop()* Async handles allow the user to "wakeup" the event loop and get a callback called from another thread. - > + >lua local async async = uv.new_async(function() print("async operation ran") @@ -933,7 +933,7 @@ uv.async_send({async}, {...}) *uv.async_send()* Poll handles are used to watch file descriptors for readability and writability, similar to the purpose of poll(2) -(http://linux.die.net/man/2/poll). +(https://linux.die.net/man/2/poll). The purpose of poll handles is to enable integrating external libraries that rely on the event loop to signal it about the socket status changes, like @@ -1062,7 +1062,7 @@ Unix Notes: will lead to unpredictable behavior and is strongly discouraged. Future versions of libuv may simply reject them. - > + >lua -- Create a new signal handler local signal = uv.new_signal() -- Define a handler function @@ -1164,7 +1164,7 @@ uv.spawn({path}, {options}, {on_exit}) *uv.spawn()* permissions to use the setuid or setgid specified, or not having enough memory to allocate for the new process. - > + >lua local stdin = uv.new_pipe() local stdout = uv.new_pipe() local stderr = uv.new_pipe() @@ -1358,7 +1358,7 @@ uv.accept({stream}, {client_stream}) *uv.accept()* Returns: `0` or `fail` - > + >lua server:listen(128, function (err) local client = uv.new_tcp() server:accept(client) @@ -1382,7 +1382,7 @@ uv.read_start({stream}, {callback}) *uv.read_start()* Returns: `0` or `fail` - > + >lua stream:read_start(function (err, chunk) if err then -- handle read error @@ -1690,7 +1690,7 @@ uv.tcp_connect({tcp}, {host}, {port}, {callback}) *uv.tcp_connect()* Returns: `uv_connect_t userdata` or `fail` - > + >lua local client = uv.new_tcp() client:connect("127.0.0.1", 8080, function (err) -- check error and carry on. @@ -1755,7 +1755,7 @@ uv.socketpair([{socktype}, [{protocol}, [{flags1}, [{flags2}]]]]) Returns: `table` or `fail` - `[1, 2]` : `integer` (file descriptor) - > + >lua -- Simple read/write with tcp local fds = uv.socketpair(nil, nil, {nonblock=true}, {nonblock=true}) @@ -1780,7 +1780,7 @@ uv.socketpair([{socktype}, [{protocol}, [{flags1}, [{flags2}]]]]) Pipe handles provide an abstraction over local domain sockets on Unix and named pipes on Windows. - > + >lua local pipe = uv.new_pipe(false) pipe:bind('/tmp/sock.test') @@ -1959,7 +1959,7 @@ uv.pipe({read_flags}, {write_flags}) *uv.pipe()* - `read` : `integer` (file descriptor) - `write` : `integer` (file descriptor) - > + >lua -- Simple read/write with pipe_open local fds = uv.pipe({nonblock=true}, {nonblock=true}) @@ -1983,7 +1983,7 @@ uv.pipe({read_flags}, {write_flags}) *uv.pipe()* TTY handles represent a stream for the console. - > + >lua -- Simple echo program local stdin = uv.new_tty(0, true) local stdout = uv.new_tty(1, false) @@ -2537,7 +2537,7 @@ FS call. Synchronous and asynchronous versions of `readFile` (with naive error handling) are implemented below as an example: - > + >lua local function readFileSync(path) local fd = assert(uv.fs_open(path, "r", 438)) local stat = assert(uv.fs_fstat(fd)) @@ -2550,7 +2550,7 @@ handling) are implemented below as an example: print("synchronous read", data) < - > + >lua local function readFile(path, callback) uv.fs_open(path, "r", 438, function(err, fd) assert(not err, err) @@ -2626,7 +2626,7 @@ uv.fs_read({fd}, {size} [, {offset} [, {callback}]]) *uv.fs_read()* indicates EOF. If `offset` is nil or omitted, it will default to `-1`, which - indicates 'use and update the current file offset.' + indicates "use and update the current file offset." Note: When `offset` is >= 0, the current file offset will not be updated by the read. @@ -2665,7 +2665,7 @@ uv.fs_write({fd}, {data} [, {offset} [, {callback}]]) *uv.fs_write()* written. If `offset` is nil or omitted, it will default to `-1`, which - indicates 'use and update the current file offset.' + indicates "use and update the current file offset." Note: When `offset` is >= 0, the current file offset will not be updated by the write. @@ -3253,7 +3253,7 @@ Libuv provides a threadpool which can be used to run user code and get notified in the loop thread. This threadpool is internally used to run all file system operations, as well as `getaddrinfo` and `getnameinfo` requests. - > + >lua local function work_callback(a, b) return a + b end @@ -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..cb8b162eb6 100644 --- a/runtime/doc/map.txt +++ b/runtime/doc/map.txt @@ -215,6 +215,9 @@ The search string will not be echoed when using this mapping. Messages from the executed command are still given though. To shut them up too, add a ":silent" in the executed command: > :map <silent> ,h :exe ":silent normal /Header\r"<CR> +Note that the effect of a command might also be silenced, e.g., when the +mapping selects another entry for command line completion it won't be +displayed. Prompts will still be given, e.g., for inputdialog(). Using "<silent>" for an abbreviation is possible, but will cause redrawing of the command line to fail. @@ -648,6 +651,10 @@ The special key name "<Plug>" can be used for an internal mapping, which is not to be matched with any key sequence. This is useful in plugins |using-<Plug>|. + *<MouseMove>* +The special key name "<MouseMove>" can be used to handle mouse movement. It +needs to be enabled with 'mousemoveevent'. + *<Char>* *<Char->* To map a character by its decimal, octal or hexadecimal number the <Char> construct can be used: @@ -659,9 +666,9 @@ This is useful to specify a (multibyte) character in a 'keymap' file. Upper and lowercase differences are ignored. *map-comments* -It is not possible to put a comment after these commands, because the '"' +It is not possible to put a comment after these commands, because the `"` character is considered to be part of the {lhs} or {rhs}. However, one can -use |", since this starts a new, empty command with a comment. +use `|"`, since this starts a new, empty command with a comment. *map_bar* *map-bar* Since the '|' character is used to separate a map command from the next @@ -691,8 +698,8 @@ To avoid mapping of the characters you type in insert or Command-line mode, type a CTRL-V first. The mapping in Insert mode is disabled if the 'paste' option is on. *map-error* -Note that when an error is encountered (that causes an error message or beep) -the rest of the mapping is not executed. This is Vi-compatible. +Note that when an error is encountered (that causes an error message or might +cause a beep) the rest of the mapping is not executed. This is Vi-compatible. Note that the second character (argument) of the commands @zZtTfF[]rm'`"v and CTRL-X is not mapped. This was done to be able to use all the named @@ -865,28 +872,56 @@ Here is an example that counts the number of spaces with <F4>: > " doubling <F4> works on a line nnoremap <expr> <F4><F4> CountSpaces() .. '_' - function CountSpaces(type = '') abort + function CountSpaces(context = {}, type = '') abort if a:type == '' - set opfunc=CountSpaces + let context = #{ + \ dot_command: v:false, + \ extend_block: '', + \ virtualedit: [&l:virtualedit, &g:virtualedit], + \ } + let &operatorfunc = function('CountSpaces', [context]) + set virtualedit=block return 'g@' endif - let sel_save = &selection - let reg_save = getreginfo('"') - let cb_save = &clipboard - let visual_marks_save = [getpos("'<"), getpos("'>")] + let save = #{ + \ clipboard: &clipboard, + \ selection: &selection, + \ virtualedit: [&l:virtualedit, &g:virtualedit], + \ register: getreginfo('"'), + \ visual_marks: [getpos("'<"), getpos("'>")], + \ } try - set clipboard= selection=inclusive - let commands = #{line: "'[V']y", char: "`[v`]y", block: "`[\<c-v>`]y"} - silent exe 'noautocmd keepjumps normal! ' .. get(commands, a:type, '') - echom count(getreg('"'), ' ') + set clipboard= selection=inclusive virtualedit= + let commands = #{ + \ line: "'[V']", + \ char: "`[v`]", + \ block: "`[\<C-V>`]", + \ }[a:type] + let [_, _, col, off] = getpos("']") + if off != 0 + let vcol = getline("'[")->strpart(0, col + off)->strdisplaywidth() + if vcol >= [line("'["), '$']->virtcol() - 1 + let a:context.extend_block = '$' + else + let a:context.extend_block = vcol .. '|' + endif + endif + if a:context.extend_block != '' + let commands ..= 'oO' .. a:context.extend_block + endif + let commands ..= 'y' + execute 'silent noautocmd keepjumps normal! ' .. commands + echomsg getreg('"')->count(' ') finally - call setreg('"', reg_save) - call setpos("'<", visual_marks_save[0]) - call setpos("'>", visual_marks_save[1]) - let &clipboard = cb_save - let &selection = sel_save + call setreg('"', save.register) + call setpos("'<", save.visual_marks[0]) + call setpos("'>", save.visual_marks[1]) + let &clipboard = save.clipboard + let &selection = save.selection + let [&l:virtualedit, &g:virtualedit] = get(a:context.dot_command ? save : a:context, 'virtualedit') + let a:context.dot_command = v:true endtry endfunction @@ -1336,7 +1371,6 @@ completion can be enabled: -complete=color color schemes -complete=command Ex command (and arguments) -complete=compiler compilers - -complete=cscope |:cscope| suboptions -complete=dir directory names -complete=environment environment variable names -complete=event autocommand events @@ -1398,9 +1432,11 @@ The function arguments are: The function may use these for determining context. For the "custom" argument, it is not necessary to filter candidates against the (implicit pattern in) ArgLead. Vim will filter the candidates with its regexp engine -after function return, and this is probably more efficient in most cases. For -the "customlist" argument, Vim will not filter the returned completion -candidates and the user supplied function should filter the candidates. +after function return, and this is probably more efficient in most cases. If +'wildoptions' contains "fuzzy", then the candidates will be filtered using +|fuzzy-matching|. For the "customlist" argument, Vim will not +filter the returned completion candidates and the user supplied function +should filter the candidates. The following example lists user names to a Finger command > :com -complete=custom,ListUsers -nargs=1 Finger !finger <args> @@ -1437,7 +1473,7 @@ Possible attributes are: number. -count=N A count (default N) which is specified either in the line number position, or as an initial argument (like |:Next|). - Specifying -count (without a default) acts like -count=0 + -count Acts like -count=0 Note that -range=N and -count=N are mutually exclusive - only one should be specified. @@ -1448,14 +1484,16 @@ which by default correspond to the current line, last line and the whole buffer, relate to arguments, (loaded) buffers, windows or tab pages. Possible values are (second column is the short name used in listing): - -addr=lines line Range of lines (this is the default) + -addr=lines Range of lines (this is the default for -range) -addr=arguments arg Range for arguments -addr=buffers buf Range for buffers (also not loaded buffers) -addr=loaded_buffers load Range for loaded buffers -addr=windows win Range for windows -addr=tabs tab Range for tab pages -addr=quickfix qf Range for quickfix entries - -addr=other ? other kind of range + -addr=other ? Other kind of range; can use ".", "$" and "%" + as with "lines" (this is the default for + -count) Incremental preview ~ @@ -1623,11 +1661,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 +1698,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 +1709,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 +1723,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 +1740,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 +1749,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..99dfa54218 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,41 +334,14 @@ 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 GNU iconv can convert most encodings. Unicode is used as the intermediate encoding, which allows conversion from and to all other - encodings. See http://www.gnu.org/directory/libiconv.html. - - Japanese: nkf - Nkf is "Network Kanji code conversion Filter". One of the most unique - facility of nkf is the guess of the input Kanji code. So, you don't - need to know what the inputting file's |charset| is. When convert to - EUC-JP from ISO-2022-JP or Shift_JIS, simply do the following command - in Vim: - :%!nkf -e - Nkf can be found at: - http://www.sfc.wide.ad.jp/~max/FreeBSD/ports/distfiles/nkf-1.62.tar.gz - - Chinese: hc - Hc is "Hanzi Converter". Hc convert a GB file to a Big5 file, or Big5 - file to GB file. Hc can be found at: - ftp://ftp.cuhk.hk/pub/chinese/ifcss/software/unix/convert/hc-30.tar.gz - - Korean: hmconv - Hmconv is Korean code conversion utility especially for E-mail. It can - convert between EUC-KR and ISO-2022-KR. Hmconv can be found at: - ftp://ftp.kaist.ac.kr/pub/hangul/code/hmconv/ - - Multilingual: lv - Lv is a Powerful Multilingual File Viewer. And it can be worked as - |charset| converter. Supported |charset|: ISO-2022-CN, ISO-2022-JP, - ISO-2022-KR, EUC-CN, EUC-JP, EUC-KR, EUC-TW, UTF-7, UTF-8, ISO-8859 - series, Shift_JIS, Big5 and HZ. Lv can be found at: - http://www.ff.iij4u.or.jp/~nrt/lv/index.html + encodings. See https://directory.fsf.org/wiki/Libiconv. *mbyte-conversion* @@ -405,17 +377,6 @@ is suitable for complex input, such as CJK. large overhead in communication, but it provides safe synchronization with no restrictions on applications. - For example, there are xwnmo and kinput2 Japanese |IM-server|, both are - FrontEnd system. Xwnmo is distributed with Wnn (see below), kinput2 can be - found at: ftp://ftp.sra.co.jp/pub/x11/kinput2/ - - For Chinese, there's a great XIM server named "xcin", you can input both - Traditional and Simplified Chinese characters. And it can accept other - locale if you make a correct input table. Xcin can be found at: - http://cle.linux.org.tw/xcin/ - Others are scim: http://scim.freedesktop.org/ and fcitx: - http://www.fcitx.org/ - - Conversion Server *conversion-server* Some system needs additional server: conversion server. Most of Japanese @@ -664,7 +625,7 @@ and what the keymaps are to get those characters: glyph encoding keymap ~ Char UTF-8 cp1255 hebrew hebrewp name ~ -× 0x5d0 0xe0 t a 'alef +× 0x5d0 0xe0 t a ´alef ב 0x5d1 0xe1 c b bet ×’ 0x5d2 0xe2 d g gimel ד 0x5d3 0xe3 s d dalet @@ -745,7 +706,7 @@ Char UTF-8 hebrew name Combining forms: ï¬ 0xfb20 X` Alternative `ayin -ﬡ 0xfb21 X' Alternative 'alef +ﬡ 0xfb21 X' Alternative ´alef ﬢ 0xfb22 X-d Alternative dalet ﬣ 0xfb23 X-h Alternative he ﬤ 0xfb24 X-k Alternative kaf diff --git a/runtime/doc/message.txt b/runtime/doc/message.txt index dac4df5ee9..dffdb5950f 100644 --- a/runtime/doc/message.txt +++ b/runtime/doc/message.txt @@ -573,9 +573,7 @@ when using ":w"), therefore Vim requires using a ! after the command, e.g.: VirtualBinding Messages like this appear when starting up. This is not a Vim problem, your -X11 configuration is wrong. You can find a hint on how to solve this here: -http://groups.yahoo.com/group/solarisonintel/message/12179. -[this URL is no longer valid] +X11 configuration is wrong. *W10* > Warning: Changing a readonly file @@ -603,6 +601,7 @@ probably means that some other program changed the file. You will have to find out what happened, and decide which version of the file you want to keep. Set the 'autoread' option if you want to do this automatically. This message is not given when 'buftype' is not empty. +Also see the |FileChangedShell| autocommand. There is one situation where you get this message even though there is nothing wrong: If you save a file in Windows on the day the daylight saving time @@ -821,7 +820,7 @@ Type effect ~ the clipboard ("* and "+ registers) {menu-entry} what the menu is defined to in Cmdline-mode. - <LeftMouse> (*) next page + <LeftMouse> next page (*) Any other key causes the meaning of the keys to be displayed. diff --git a/runtime/doc/mlang.txt b/runtime/doc/mlang.txt index 9d3a51302d..84b8498d39 100644 --- a/runtime/doc/mlang.txt +++ b/runtime/doc/mlang.txt @@ -92,27 +92,10 @@ use of "-" and "_". :lang mes en < -MS-WINDOWS MESSAGE TRANSLATIONS *win32-gettext* - -If you used the self-installing .exe file, message translations should work -already. Otherwise get the libintl.dll file if you don't have it yet: - - http://sourceforge.net/projects/gettext -Or: - https://mlocati.github.io/gettext-iconv-windows/ - -This also contains tools xgettext, msgformat and others. - -libintl.dll should be placed in same directory as (g)vim.exe, or one of the -directories listed in the PATH environment value. Vim also looks for the -alternate names "libintl-8.dll" and "intl.dll". - Message files (vim.mo) have to be placed in "$VIMRUNTIME/lang/xx/LC_MESSAGES", -where "xx" is the abbreviation of the language (mostly two letters). - -If you write your own translations you need to generate the .po file and -convert it to a .mo file. You need to get the source distribution and read -the file "src/po/README.txt". +where "xx" is the abbreviation of the language (mostly two letters). If you +write your own translations you need to generate the .po file and convert it +to a .mo file. To overrule the automatic choice of the language, set the $LANG variable to the language of your choice. use "en" to disable translations. > diff --git a/runtime/doc/motion.txt b/runtime/doc/motion.txt index 511b1bd7b2..929efee19f 100644 --- a/runtime/doc/motion.txt +++ b/runtime/doc/motion.txt @@ -309,10 +309,10 @@ g<Down> [count] display lines downward. |exclusive| motion. an operator, because it's not linewise. *-* -- <minus> [count] lines upward, on the first non-blank +`-` <minus> [count] lines upward, on the first non-blank character |linewise|. -+ or *+* +`+` or *+* CTRL-M or *CTRL-M* *<CR>* <CR> [count] lines downward, on the first non-blank character |linewise|. @@ -438,9 +438,9 @@ between Vi and Vim. } [count] |paragraph|s forward. |exclusive| motion. *]]* -]] [count] |section|s forward or to the next '{' in the +]] [count] |section|s forward or to the next "{" in the first column. When used after an operator, then also - stops below a '}' in the first column. |exclusive| + stops below a "}" in the first column. |exclusive| Note that |exclusive-linewise| often applies. *][* @@ -449,12 +449,12 @@ between Vi and Vim. Note that |exclusive-linewise| often applies. *[[* -[[ [count] |section|s backward or to the previous '{' in +[[ [count] |section|s backward or to the previous "{" in the first column. |exclusive| Note that |exclusive-linewise| often applies. *[]* -[] [count] |section|s backward or to the previous '}' in +[] [count] |section|s backward or to the previous "}" in the first column. |exclusive| Note that |exclusive-linewise| often applies. @@ -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 @@ -1004,8 +1004,8 @@ These commands are not marks themselves, but jump to a mark: Note that ":keepjumps" must be used for every command. When invoking a function the commands in that function can still change the jumplist. Also, for - ":keepjumps exe 'command '" the "command" won't keep - jumps. Instead use: ":exe 'keepjumps command'" + `:keepjumps exe 'command '` the "command" won't keep + jumps. Instead use: `:exe 'keepjumps command'` ============================================================================== 8. Jumps *jump-motions* @@ -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..5c234677ef --- /dev/null +++ b/runtime/doc/news.txt @@ -0,0 +1,194 @@ +*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. + +• Cscope support is now removed (see |cscope| and |nvim-features-removed|): + - Commands removed: + - `:cscope` + - `:lcscope` + - `:scscope` + - `:cstag` + - Options removed: + - `cscopepathcomp` + - `cscopeprg` + - `cscopequickfix` + - `cscoperelative` + - `cscopetag` + - `cscopetagorder` + - `cscopeverbose` + - Eval functions removed: + - `cscope_connection()` + + Note: support for |ctags| remains with no plans to remove. + + See https://github.com/neovim/neovim/pull/20545 for more information. + +• `:hardcopy` is now removed (see |hardcopy| and |nvim-features-removed|): + - Commands removed: + - `:hardcopy` + - Options removed: + - `printdevice` + - `printencoding` + - `printexpr` + - `printfont` + - `printheader` + - `printmbcharset` + +• libiconv is now a required build dependency. + +============================================================================== +NEW FEATURES *news-features* + +The following new APIs or features were added. + +• |nvim_open_win()| now accepts a relative `mouse` option to open a floating win + relative to the mouse. Note that the mouse doesn't update frequently without + setting `vim.o.mousemoveevent = true` + +• EditorConfig support is now builtin. This is enabled by default and happens + automatically. To disable it, users should add >lua + + vim.g.editorconfig = false +< + (or the Vimscript equivalent) to their |config| file. + +• Run Lua scripts from your shell using |-l|. > + nvim -l foo.lua --arg1 --arg2 +< Also works with stdin: > + echo "print(42)" | nvim -l - + +• Added a |vim.lsp.codelens.clear()| function to clear codelenses. + +• |vim.inspect_pos()|, |vim.show_pos()| and |:Inspect| allow a user to get or show items + at a given buffer position. Currently this includes treesitter captures, + semantic tokens, syntax groups and extmarks. + +• Added support for semantic token highlighting to the LSP client. This + functionality is enabled by default when a client that supports this feature + is attached to a buffer. Opt-out can be performed by deleting the + `semanticTokensProvider` from the LSP client's {server_capabilities} in the + `LspAttach` callback. + + See |lsp-semantic_tokens| for more information. + +• |vim.treesitter.show_tree()| opens a split window showing a text + representation of the nodes in a language tree for the current buffer. + +• Added support for the `willSave` and `willSaveWaitUntil` capabilities to the + LSP client. `willSaveWaitUntil` allows a server to modify a document before it + gets saved. Example use-cases by language servers include removing unused + imports, or formatting the file. + +• Treesitter syntax highlighting for `help` files now supports highlighted + code examples. To enable, create a `.config/nvim/ftplugin/help.lua` with + the contents >lua + vim.treesitter.start() +< + Note: Highlighted code examples are only available in the Nvim manual, not + in help files taken from Vim. The treesitter `help` parser is also work in + progress and not guaranteed to correctly highlight every help file in the + wild. + +• |vim.secure.trust()|, |:trust| allows the user to manage files in trust + database. + +• |vim.diagnostic.open_float()| (and therefore |vim.diagnostic.config()|) now + accepts a `suffix` option which, by default, renders LSP error codes. + Similarly, the `virtual_text` configuration in |vim.diagnostic.config()| now + has a `suffix` option which does nothing by default. + +• |vim.fs.dir()| now has a `opts` argument with a depth field to allow + recursively searching a directory tree. + +• |vim.secure.read()| reads a file and prompts the user if it should be + trusted and, if so, returns the file's contents. + +• When using Nvim inside tmux 3.2 or later, the default clipboard provider + will now copy to the system clipboard. |provider-clipboard| + +• |'showcmdloc'| option to display the 'showcmd' information in the + status line or tab line. A new %S statusline item is available to place + the 'showcmd' text in a custom 'statusline'. Useful for when |'cmdheight'| + is set to 0. + +• |'splitkeep'| option to control the scroll behavior of horizontal splits. + +• |'statuscolumn'| option to customize the area to the side of a window, + normally containing the fold, sign and number columns. This new option follows + the 'statusline' syntax and can be used to transform the line numbers, create + mouse click callbacks for |signs|, introduce a custom margin or separator etc. + +• |nvim_select_popupmenu_item()| now supports |cmdline-completion| popup menu. + +• |'diffopt'| now includes a `linematch` option to enable a second-stage diff + on individual hunks to provide much more accurate diffs. This option is also + available to |vim.diff()| + + See https://github.com/neovim/neovim/pull/14537. + +• |vim.diagnostic.is_disabled()| checks if diagnostics are disabled in a given + buffer or namespace. + +• |--remote-ui| option was added to connect to a remote instance and display + in it in a |TUI| in the local terminal. This can be used run a headless nvim + instance in the background and display its UI on demand, which previously + only was possible using an external UI implementation. + +• Several improvements were made to make the code generation scripts more + deterministic, and a `LUA_GEN_PRG` build parameter has been introduced to + allow for a workaround for some remaining reproducibility problems. + +• |:highlight| now supports an additional attribute "altfont". + +============================================================================== +CHANGED FEATURES *news-changes* + +The following changes to existing APIs or features add new behavior. + +• 'exrc' now supports `.nvim.lua` file. +• 'exrc' is no longer marked deprecated. + +• The |TUI| is changed to run in a separate process (previously, a separate + thread was used). This is not supposed to be a visible change to the user, + but might be the cause of subtle changes of behavior and bugs. + + Previously, the TUI could be disabled as a build time feature (+tui/-tui), + resulting in a nvim binary which only could be run headless or embedded + in an external process. As of this version, TUI is always available. + +• API calls now show more information about where an exception happened. + +============================================================================== +REMOVED FEATURES *news-removed* + +The following deprecated functions or APIs were removed. + +• It is no longer possible to scroll the whole screen when showing messages + longer than 'cmdheight'. |msgsep| is now always enabled even if 'display' + doesn't contain the "msgsep" flag. + +• `filetype.vim` is removed in favor of |lua-filetype| + (Note that filetype logic and tests still align with Vim, so additions or + changes need to be contributed there first.) + See https://github.com/neovim/neovim/pull/20674. + +============================================================================== +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..ef407922da 100644 --- a/runtime/doc/nvim.txt +++ b/runtime/doc/nvim.txt @@ -1,33 +1,33 @@ *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. If you already use Vim see |nvim-from-vim| for a quickstart. -If you are new to Vim, try the 30-minute tutorial: > +If you are new to Vim, try the 30-minute tutorial: >vim :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: > +1. To start the transition, create your |init.vim| (user config) file: >vim - :call mkdir(stdpath('config'), 'p') :exe 'edit '.stdpath('config').'/init.vim' + :write ++p -2. Add these contents to the file: > +2. Add these contents to the file: >vim set runtimepath^=~/.vim runtimepath+=~/.vim/after let &packpath = &runtimepath @@ -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: +>vim 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: +>vim if has('nvim') tnoremap <Esc> <C-\><C-n> endif -< + For a more granular approach use |exists()|: -> +>vim 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: >vim + 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/nvim_terminal_emulator.txt b/runtime/doc/nvim_terminal_emulator.txt index 546f92e92f..96f99528ed 100644 --- a/runtime/doc/nvim_terminal_emulator.txt +++ b/runtime/doc/nvim_terminal_emulator.txt @@ -27,12 +27,12 @@ There are several ways to create a terminal buffer: - Run the |:terminal| command. - Call the |nvim_open_term()| or |termopen()| function. -- Edit a "term://" buffer. Examples: > +- Edit a "term://" buffer. Examples: >vim :edit term://bash :vsplit term://top < Note: To open a "term://" buffer from an autocmd, the |autocmd-nested| - modifier is required. > + modifier is required. >vim autocmd VimEnter * ++nested split term://sh < (This is only mentioned for reference; use |:terminal| instead.) @@ -62,13 +62,13 @@ Terminal-mode forces these local options: Terminal-mode has its own |:tnoremap| namespace for mappings, this can be used to automate any terminal interaction. -To map <Esc> to exit terminal-mode: > +To map <Esc> to exit terminal-mode: >vim :tnoremap <Esc> <C-\><C-n> -To simulate |i_CTRL-R| in terminal-mode: > +To simulate |i_CTRL-R| in terminal-mode: >vim :tnoremap <expr> <C-R> '<C-\><C-N>"'.nr2char(getchar()).'pi' -To use `ALT+{h,j,k,l}` to navigate windows from any mode: > +To use `ALT+{h,j,k,l}` to navigate windows from any mode: >vim :tnoremap <A-h> <C-\><C-N><C-w>h :tnoremap <A-j> <C-\><C-N><C-w>j :tnoremap <A-k> <C-\><C-N><C-w>k @@ -109,7 +109,7 @@ global configuration. - 'list' is disabled - 'wrap' is disabled -You can change the defaults with a TermOpen autocommand: > +You can change the defaults with a TermOpen autocommand: >vim au TermOpen * setlocal list TERMINAL COLORS ~ @@ -117,7 +117,7 @@ TERMINAL COLORS ~ The `{g,b}:terminal_color_x` variables control the terminal color palette, where `x` is the color index between 0 and 255 inclusive. The variables are read during |TermOpen|. The value must be a color name or hexadecimal string. -Example: > +Example: >vim let g:terminal_color_4 = '#ff0000' let g:terminal_color_5 = 'green' Only works for RGB UIs (see 'termguicolors'); for 256-color terminals the @@ -131,7 +131,7 @@ Status Variables *terminal-status* Terminal buffers maintain some buffer-local variables and options. The values are initialized before TermOpen, so you can use them in a local 'statusline'. -Example: > +Example: >vim :autocmd TermOpen * setlocal statusline=%{b:term_title} - *b:term_title* Terminal title (user-writable), typically displayed in the @@ -141,10 +141,10 @@ Example: > input to the terminal. - The |TermClose| event gives the terminal job exit code in the |v:event| "status" field. For example, this autocmd closes terminal buffers if the job - exited without error: > + exited without error: >vim autocmd TermClose * if !v:event.status | exe 'bdelete! '..expand('<abuf>') | endif -Use |jobwait()| to check if the terminal job has finished: > +Use |jobwait()| to check if the terminal job has finished: >vim let running = jobwait([&channel], 0)[0] == -1 ============================================================================== @@ -156,11 +156,11 @@ Vim this also works remotely over an ssh connection. Starting ~ *termdebug-starting* -Load the plugin with this command: > +Load the plugin with this command: >vim packadd termdebug < *:Termdebug* To start debugging use `:Termdebug` or `:TermdebugCommand` followed by the -command name, for example: > +command name, for example: >vim :Termdebug vim This opens two windows: @@ -189,16 +189,16 @@ Only one debugger can be active at a time. *:TermdebugCommand* If you want to give specific commands to the command being debugged, you can use the `:TermdebugCommand` command followed by the command name and -additional parameters. > +additional parameters. >vim :TermdebugCommand vim --clean -c ':set nu' Both the `:Termdebug` and `:TermdebugCommand` support an optional "!" bang argument to start the command right away, without pausing at the gdb window -(and cursor will be in the debugged window). For example: > +(and cursor will be in the debugged window). For example: >vim :TermdebugCommand! vim --clean To attach gdb to an already running executable or use a core file, pass extra -arguments. E.g.: > +arguments. E.g.: >vim :Termdebug vim core :Termdebug vim 98343 @@ -212,7 +212,7 @@ Start in the Vim "src" directory and build Vim: > % make Start Vim: > % ./vim -Load the termdebug plugin and start debugging Vim: > +Load the termdebug plugin and start debugging Vim: >vim :packadd termdebug :Termdebug vim You should now have three windows: @@ -223,7 +223,7 @@ You should now have three windows: Put focus on the gdb window and type: > break ex_help run -Vim will start running in the program window. Put focus there and type: > +Vim will start running in the program window. Put focus there and type: >vim :help gui Gdb will run into the ex_help breakpoint. The source window now shows the ex_cmds.c file. A red "1 " marker will appear in the signcolumn where the @@ -329,7 +329,7 @@ Other commands ~ Events ~ *termdebug-events* -Four autocommands can be used: > +Four autocommands can be used: >vim au User TermdebugStartPre echomsg 'debugging starting' au User TermdebugStartPost echomsg 'debugging started' au User TermdebugStopPre echomsg 'debugging stopping' @@ -355,6 +355,20 @@ TermdebugStopPost After debugging has ended, gdb-related windows the state before the debugging was restored. +Customizing ~ + *termdebug-customizing* *g:termdebug_config* +In the past several global variables were used for configuration. These are +deprecated and using the g:termdebug_config dictionary is preferred. When +g:termdebug_config exists the other global variables will NOT be used. +The recommended way is to start with an empty dictionary: >vim + let g:termdebug_config = {} + +Then you can add entries to the dictionary as mentioned below. The +deprecated global variable names are mentioned for completeness. If you are +switching over to using g:termdebug_config you can find the old variable name +and take over the value, then delete the deprecated variable. + + Prompt mode ~ *termdebug-prompt* When on MS-Windows, gdb will run in a buffer with 'buftype' set to "prompt". @@ -366,23 +380,23 @@ This works slightly differently: - A separate :terminal window will be opened to run the debugged program in. *termdebug_use_prompt* -Prompt mode can be used with: > +Prompt mode can be used with: >vim let g:termdebug_config['use_prompt'] = 1 -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_use_prompt = 1 < *termdebug_map_K* -The K key is normally mapped to :Evaluate. If you do not want this use: > +The K key is normally mapped to :Evaluate. If you do not want this use: >vim let g:termdebug_config['map_K'] = 0 -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_map_K = 0 < *termdebug_disasm_window* If you want the Asm window shown by default, set the flag to 1. -the "disasm_window_height" entry can be used to set the window height: > +the "disasm_window_height" entry can be used to set the window height: >vim let g:termdebug_config['disasm_window'] = 1 let g:termdebug_config['disasm_window_height'] = 15 -or, if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_disasm_window = 15 Any value greater than 1 will set the Asm window height to that value. @@ -400,45 +414,38 @@ interrupt the running program. But after using the MI command communication channel. -Customizing ~ - *termdebug-customizing* *g:termdebug_config* -In the past several global variables were used for configuration. These are -deprecated, using the g:termdebug_config dictionary is preferred. When -g:termdebug_config exists the other global variables will not be used. - - GDB command ~ *g:termdebugger* To change the name of the gdb command, set "debugger" entry in g:termdebug_config or the "g:termdebugger" variable before invoking -`:Termdebug`: > +`:Termdebug`: >vim let g:termdebug_config['command'] = "mygdb" -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebugger = "mygdb" -If the command needs an argument use a List: > +If the command needs an argument use a List: >vim let g:termdebug_config['command'] = ['rr', 'replay', '--'] -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebugger = ['rr', 'replay', '--'] To not use neovim floating windows for previewing variable evaluation, set the -`g:termdebug_useFloatingHover` variable like this: > +`g:termdebug_useFloatingHover` variable like this: >vim let g:termdebug_useFloatingHover = 0 If you are a mouse person, you can also define a mapping using your right click to one of the terminal command like evaluate the variable under the -cursor: > +cursor: >vim nnoremap <RightMouse> :Evaluate<CR> -or set/unset a breakpoint: > +or set/unset a breakpoint: >vim nnoremap <RightMouse> :Break<CR> Several arguments will be added to make gdb work well for the debugger. -If you want to modify them, add a function to filter the argument list: > +If you want to modify them, add a function to filter the argument list: >vim let g:termdebug_config['command_filter'] = MyDebugFilter If you do not want the arguments to be added, but you do need to set the -"pty", use a function to add the necessary arguments: > +"pty", use a function to add the necessary arguments: >vim let g:termdebug_config['command_add_args'] = MyAddArguments The function will be called with the list of arguments so far, and a second argument that is the name of the pty. @@ -451,7 +458,7 @@ Then your gdb is too old. Colors ~ - *hl-debugPC* *hl-debugBreakpoint* + *hl-debugPC* *hl-debugBreakpoint* The color of the signs can be adjusted with these highlight groups: - debugPC the current position - debugBreakpoint a breakpoint @@ -467,34 +474,31 @@ When 'background' is "dark": Shortcuts ~ *termdebug_shortcuts* - You can define your own shortcuts (mappings) to control gdb, that can work in -any window, using the TermDebugSendCommand() function. Example: > +any window, using the TermDebugSendCommand() function. Example: >vim map ,w :call TermDebugSendCommand('where')<CR> The argument is the gdb command. Popup menu ~ *termdebug_popup* - By default the Termdebug plugin sets 'mousemodel' to "popup_setpos" and adds these entries to the popup menu: Set breakpoint `:Break` Clear breakpoint `:Clear` Evaluate `:Evaluate` -If you don't want this then disable it with: > +If you don't want this then disable it with: >vim let g:termdebug_config['popup'] = 0 -or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_popup = 0 Vim window width ~ *termdebug_wide* - To change the width of the Vim window when debugging starts and use a vertical -split: > +split: >vim let g:termdebug_config['wide'] = 163 -Or if there is no g:termdebug_config: > +If there is no g:termdebug_config you can use: >vim let g:termdebug_wide = 163 This will set 'columns' to 163 when `:Termdebug` is used. The value is diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 2e0c1f8cc4..b1af90a604 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -145,7 +145,7 @@ This sets the 'titlestring' option to "hi" and 'iconstring' to "there": > Similarly, the double quote character starts a comment. To include the '"' in the option value, use '\"' instead. This example sets the 'titlestring' -option to 'hi "there"': > +option to "hi "there"": > :set titlestring=hi\ \"there\" For Win32 backslashes in file names are mostly not removed. More precise: For @@ -163,7 +163,7 @@ halved and when you expect the backslashes to be kept. The third gives a result which is probably not what you want. Avoid it. *add-option-flags* *remove-option-flags* - *E539* *E550* *E551* *E552* + *E539* Some options are a list of flags. When you want to add a flag to such an option, without changing the existing ones, you can do it like this: > :set guioptions+=a @@ -313,14 +313,23 @@ Note: In the future more global options can be made |global-local|. Using *option-value-function* -Some options ('completefunc', 'imactivatefunc', 'imstatusfunc', 'omnifunc', -'operatorfunc', 'quickfixtextfunc' and 'tagfunc') are set to a function name -or a function reference or a lambda function. Examples: +Some options ('completefunc', 'omnifunc', 'operatorfunc', 'quickfixtextfunc', +'tagfunc' and 'thesaurusfunc') are set to a function name or a function +reference or a lambda function. When using a lambda it will be converted to +the name, e.g. "<lambda>123". Examples: > set opfunc=MyOpFunc - set opfunc=function("MyOpFunc") - set opfunc=funcref("MyOpFunc") - set opfunc={t\ ->\ MyOpFunc(t)} + set opfunc=function('MyOpFunc') + set opfunc=funcref('MyOpFunc') + set opfunc={a\ ->\ MyOpFunc(a)} + " set using a funcref variable + let Fn = function('MyTagFunc') + let &tagfunc = Fn + " set using a lambda expression + let &tagfunc = {t -> MyTagFunc(t)} + " set using a variable with lambda expression + let L = {a, b, c -> MyTagFunc(a, b , c)} + let &tagfunc = L < Setting the filetype @@ -440,9 +449,9 @@ se[t] the string "set " or "se " (note the space); When : a colon [text] any text or empty -Examples: - /* vim: set ai tw=75: */ ~ - /* Vim: set ai tw=75: */ ~ +Examples: > + /* vim: set ai tw=75: */ + /* Vim: set ai tw=75: */ The white space before {vi:|vim:|Vim:|ex:} is required. This minimizes the chance that a normal word like "lex:" is caught. There is one exception: @@ -479,10 +488,10 @@ number can be specified where "vim:" or "Vim:" is used: vim={vers}: version {vers} vim>{vers}: version after {vers} {vers} is 700 for Vim 7.0 (hundred times the major version plus minor). -For example, to use a modeline only for Vim 7.0: - /* vim700: set foldmethod=marker */ ~ -To use a modeline for Vim after version 7.2: - /* vim>702: set cole=2: */ ~ +For example, to use a modeline only for Vim 7.0: > + /* vim700: set foldmethod=marker */ +To use a modeline for Vim after version 7.2: > + /* vim>702: set cole=2: */ There can be no blanks between "vim" and the ":". The modeline is ignored if {vers} does not fit in an integer. @@ -491,16 +500,16 @@ The number of lines that are checked can be set with the 'modelines' option. If 'modeline' is off or 'modelines' is 0 no lines are checked. Note that for the first form all of the rest of the line is used, thus a line -like: - /* vi:ts=4: */ ~ -will give an error message for the trailing "*/". This line is OK: - /* vi:set ts=4: */ ~ +like: > + /* vi:ts=4: */ +will give an error message for the trailing "*/". This line is OK: > + /* vi:set ts=4: */ If an error is detected the rest of the line is skipped. If you want to include a ':' in a set command precede it with a '\'. The -backslash in front of the ':' will be removed. Example: - /* vi:set fillchars=stl\:^,vert\:\|: */ ~ +backslash in front of the ':' will be removed. Example: > + /* vi:set fillchars=stl\:^,vert\:\|: */ This sets the 'fillchars' option to "stl:^,vert:\|". Only a single backslash before the ':' is removed. Thus to include "\:" you have to specify "\\:". *E992* @@ -621,7 +630,7 @@ A jump table for the options with a short description can be found at |Q_op|. by Vim with the width of glyphs in the font. Perhaps it also has to be set to "double" under CJK MS-Windows when the system locale is set to one of CJK locales. See Unicode Standard Annex #11 - (http://www.unicode.org/reports/tr11). + (https://www.unicode.org/reports/tr11). *'autochdir'* *'acd'* *'noautochdir'* *'noacd'* 'autochdir' 'acd' boolean (default off) @@ -1053,19 +1062,26 @@ A jump table for the options with a short description can be found at |Q_op|. text should normally be narrower. This prevents text indented almost to the right window border occupying lot of vertical space when broken. + (default: 20) shift:{n} After applying 'breakindent', the wrapped line's beginning will be shifted by the given number of characters. It permits dynamic French paragraph indentation (negative) or emphasizing the line continuation (positive). + (default: 0) sbr Display the 'showbreak' value before applying the additional indent. + (default: off) list:{n} Adds an additional indent for lines that match a numbered or bulleted list (using the 'formatlistpat' setting). list:-1 Uses the length of a match with 'formatlistpat' for indentation. - The default value for min is 20, shift and list is 0. + (default: 0) + column:{n} Indent at column {n}. Will overrule the other + sub-options. Note: an additional indent may be + added for the 'showbreak' setting. + (default: off) *'browsedir'* *'bsdir'* 'browsedir' 'bsdir' string (default: "last") @@ -1309,7 +1325,7 @@ A jump table for the options with a short description can be found at |Q_op|. These names are recognized: *clipboard-unnamed* - unnamed When included, Vim will use the clipboard register '*' + unnamed When included, Vim will use the clipboard register "*" for all yank, delete, change and put operations which would normally go to the unnamed register. When a register is explicitly specified, it will always be @@ -1320,8 +1336,8 @@ A jump table for the options with a short description can be found at |Q_op|. *clipboard-unnamedplus* unnamedplus A variant of the "unnamed" flag which uses the - clipboard register '+' (|quoteplus|) instead of - register '*' for all yank, delete, change and put + clipboard register "+" (|quoteplus|) instead of + register "*" for all yank, delete, change and put operations which would normally go to the unnamed register. When "unnamed" is also included to the option, yank and delete operations (but not put) @@ -1337,9 +1353,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) @@ -1434,7 +1455,9 @@ A jump table for the options with a short description can be found at |Q_op|. This option specifies a function to be used for Insert mode completion with CTRL-X CTRL-U. |i_CTRL-X_CTRL-U| See |complete-functions| for an explanation of how the function is - invoked and what it should return. + invoked and what it should return. The value can be the name of a + function, a |lambda| or a |Funcref|. See |option-value-function| for + more information. This option cannot be set from a |modeline| or in the |sandbox|, for security reasons. @@ -1787,43 +1810,6 @@ A jump table for the options with a short description can be found at |Q_op|. _ When using |cw| on a word, do not include the whitespace following the word in the motion. - *'cscopepathcomp'* *'cspc'* -'cscopepathcomp' 'cspc' number (default 0) - global - Determines how many components of the path to show in a list of tags. - See |cscopepathcomp|. - - *'cscopeprg'* *'csprg'* -'cscopeprg' 'csprg' string (default "cscope") - global - Specifies the command to execute cscope. See |cscopeprg|. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - - *'cscopequickfix'* *'csqf'* -'cscopequickfix' 'csqf' string (default "") - global - Specifies whether to use quickfix window to show cscope results. - See |cscopequickfix|. - - *'cscoperelative'* *'csre'* *'nocscoperelative'* *'nocsre'* -'cscoperelative' 'csre' boolean (default off) - global - In the absence of a prefix (-P) for cscope. setting this option enables - to use the basename of cscope.out path as the prefix. - See |cscoperelative|. - - *'cscopetag'* *'cst'* *'nocscopetag'* *'nocst'* -'cscopetag' 'cst' boolean (default off) - global - Use cscope for tag commands. See |cscope-options|. - - *'cscopetagorder'* *'csto'* -'cscopetagorder' 'csto' number (default 0) - global - Determines the order in which ":cstag" performs a search. See - |cscopetagorder|. - *'cursorbind'* *'crb'* *'nocursorbind'* *'nocrb'* 'cursorbind' 'crb' boolean (default off) local to window @@ -1904,9 +1890,9 @@ A jump table for the options with a short description can be found at |Q_op|. ^\(#\s*define\|[a-z]*\s*const\s*[a-z]*\) < You can also use "\ze" just before the name and continue the pattern to check what is following. E.g. for Javascript, if a function is - defined with "func_name = function(args)": > + defined with `func_name = function(args)`: > ^\s*\ze\i\+\s*=\s*function( -< If the function is defined with "func_name : function() {...": > +< If the function is defined with `func_name : function() {...`: > ^\s*\ze\i\+\s*[:]\s*(*function\s*( < When using the ":set" command, you need to double the backslashes! To avoid that use `:let` with a single quote string: > @@ -2049,6 +2035,16 @@ A jump table for the options with a short description can be found at |Q_op|. Use the indent heuristic for the internal diff library. + linematch:{n} Enable a second stage diff on each generated + hunk in order to align lines. When the total + number of lines in a hunk exceeds {n}, the + second stage diff will not be performed as + very large hunks can cause noticeable lag. A + recommended setting is "linematch:60", as this + will enable alignment for a 2 buffer diff with + hunks of up to 30 lines each, or a 3 buffer + diff with hunks of up to 20 lines each. + algorithm:{text} Use the specified diff algorithm with the internal diff engine. Currently supported algorithms are: @@ -2123,9 +2119,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 +2131,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 @@ -2167,6 +2163,16 @@ A jump table for the options with a short description can be found at |Q_op|. See 'fileencoding' to control file-content encoding. + *'endoffile'* *'eof'* *'noendoffile'* *'noeof'* +'endoffile' 'eof' boolean (default off) + local to buffer + Indicates that a CTRL-Z character was found at the end of the file + when reading it. Normally only happens when 'fileformat' is "dos". + When writing a file and this option is off and the 'binary' option + is on, or 'fixeol' option is off, no CTRL-Z will be written at the + end of the file. + See |eol-and-eof| for example settings. + *'endofline'* *'eol'* *'noendofline'* *'noeol'* 'endofline' 'eol' boolean (default on) local to buffer @@ -2181,6 +2187,7 @@ A jump table for the options with a short description can be found at |Q_op|. to remember the presence of a <EOL> for the last line in the file, so that when you write the file the situation from the original file can be kept. But you can change it if you want to. + See |eol-and-eof| for example settings. *'equalalways'* *'ea'* *'noequalalways'* *'noea'* 'equalalways' 'ea' boolean (default on) @@ -2257,6 +2264,22 @@ A jump table for the options with a short description can be found at |Q_op|. This option is reset when the 'paste' option is set and restored when the 'paste' option is reset. + *'exrc'* *'ex'* *'noexrc'* *'noex'* +'exrc' 'ex' boolean (default off) + global + Enables the reading of .nvim.lua, .nvimrc, and .exrc files in the current + directory. + + The file is only sourced if the user indicates the file is trusted. If + it is, the SHA256 hash of the file contents and the full path of the + file are persisted to a trust database. The user is only prompted + again if the file contents change. See |vim.secure.read()|. + + Use |:trust| to manage the trusted file database. + + This option cannot be set from a |modeline| or in the |sandbox|, for + security reasons. + *'fileencoding'* *'fenc'* *E213* 'fileencoding' 'fenc' string (default: "") local to buffer @@ -2438,13 +2461,13 @@ A jump table for the options with a short description can be found at |Q_op|. this use the ":filetype on" command. |:filetype| Setting this option to a different value is most useful in a modeline, for a file for which the file type is not automatically recognized. - Example, for in an IDL file: - /* vim: set filetype=idl : */ ~ - |FileType| |filetypes| + Example, for in an IDL file: > + /* vim: set filetype=idl : */ +< |FileType| |filetypes| When a dot appears in the value then this separates two filetype - names. Example: - /* vim: set filetype=c.doxygen : */ ~ - This will use the "c" filetype first, then the "doxygen" filetype. + names. Example: > + /* vim: set filetype=c.doxygen : */ +< This will use the "c" filetype first, then the "doxygen" filetype. This works both for filetype plugins and for syntax files. More than one dot may appear. This option is not copied to another buffer, independent of the 's' or @@ -2454,28 +2477,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,29 +2526,31 @@ 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) local to buffer When writing a file and this option is on, <EOL> at the end of file - will be restored if missing. Turn this option off if you want to + will be restored if missing. Turn this option off if you want to preserve the situation from the original file. When the 'binary' option is set the value of this option doesn't matter. See the 'endofline' option. + See |eol-and-eof| for example settings. *'foldclose'* *'fcl'* 'foldclose' 'fcl' string (default "") @@ -2710,6 +2738,11 @@ A jump table for the options with a short description can be found at |Q_op|. When the expression evaluates to non-zero Vim will fall back to using the internal format mechanism. + If the expression starts with s: or |<SID>|, then it is replaced with + the script ID (|local-function|). Example: > + set formatexpr=s:MyFormatExpr() + set formatexpr=<SID>SomeFormatExpr() +< The expression will be evaluated in the |sandbox| when set from a modeline, see |sandbox-option|. That stops the option from working, since changing the buffer text is not allowed. @@ -3323,13 +3356,22 @@ A jump table for the options with a short description can be found at |Q_op|. local to buffer Expression to be used to transform the string found with the 'include' option to a file name. Mostly useful to change "." to "/" for Java: > - :set includeexpr=substitute(v:fname,'\\.','/','g') + :setlocal includeexpr=substitute(v:fname,'\\.','/','g') < The "v:fname" variable will be set to the file name that was detected. - + Note the double backslash: the `:set` command first halves them, then + one remains in the value, where "\." matches a dot literally. For + simple character replacements `tr()` avoids the need for escaping: > + :setlocal includeexpr=tr(v:fname,'.','/') +< Also used for the |gf| command if an unmodified file name can't be found. Allows doing "gf" on the name after an 'include' statement. Also used for |<cfile>|. + If the expression starts with s: or |<SID>|, then it is replaced with + the script ID (|local-function|). Example: > + set includeexpr=s:MyIncludeExpr(v:fname) + set includeexpr=<SID>SomeIncludeExpr(v:fname) +< The expression will be evaluated in the |sandbox| when set from a modeline, see |sandbox-option|. This option cannot be set in a modeline when 'modelineexpr' is off. @@ -3380,11 +3422,16 @@ A jump table for the options with a short description can be found at |Q_op|. in Insert mode as specified with the 'indentkeys' option. When this option is not empty, it overrules the 'cindent' and 'smartindent' indenting. When 'lisp' is set, this option is - overridden by the Lisp indentation algorithm. + is only used when 'lispoptions' contains "expr:1". When 'paste' is set this option is not used for indenting. The expression is evaluated with |v:lnum| set to the line number for which the indent is to be computed. The cursor is also in this line when the expression is evaluated (but it may be moved around). + If the expression starts with s: or |<SID>|, then it is replaced with + the script ID (|local-function|). Example: > + set indentexpr=s:MyIndentExpr() + set indentexpr=<SID>SomeIndentExpr() +< The expression must return the number of spaces worth of indent. It can return "-1" to keep the current indent (this means 'autoindent' is used for the indent). @@ -3747,6 +3794,17 @@ A jump table for the options with a short description can be found at |Q_op|. calling an external program if 'equalprg' is empty. This option is not used when 'paste' is set. + *'lispoptions'* *'lop'* +'lispoptions' 'lop' string (default "") + local to buffer + Comma-separated list of items that influence the Lisp indenting when + enabled with the |'lisp'| option. Currently only one item is + supported: + expr:1 use 'indentexpr' for Lisp indenting when it is set + expr:0 do not use 'indentexpr' for Lisp indenting (default) + Note that when using 'indentexpr' the `=` operator indents all the + lines, otherwise the first line is not indented (Vi-compatible). + *'lispwords'* *'lw'* 'lispwords' 'lw' string (default is very long) global or local to buffer |global-local| @@ -3785,21 +3843,21 @@ A jump table for the options with a short description can be found at |Q_op|. The third character is optional. tab:xy The 'x' is always used, then 'y' as many times as will - fit. Thus "tab:>-" displays: + fit. Thus "tab:>-" displays: > > >- >-- etc. - +< tab:xyz The 'z' is always used, then 'x' is prepended, and then 'y' is used as many times as will fit. Thus - "tab:<->" displays: + "tab:<->" displays: > > <> <-> <--> etc. - +< When "tab:" is omitted, a tab is shown as ^I. *lcs-space* space:c Character to show for a space. When omitted, spaces @@ -3811,22 +3869,25 @@ A jump table for the options with a short description can be found at |Q_op|. setting, except for single spaces. When omitted, the "space" setting is used. For example, `:set listchars=multispace:---+` shows ten consecutive - spaces as: - ---+---+-- ~ + spaces as: > + ---+---+-- +< *lcs-lead* lead:c Character to show for leading spaces. When omitted, leading spaces are blank. Overrides the "space" and "multispace" settings for leading spaces. You can combine it with "tab:", for example: > :set listchars+=tab:>-,lead:. -< *lcs-leadmultispace* +< + *lcs-leadmultispace* leadmultispace:c... Like the |lcs-multispace| value, but for leading spaces only. Also overrides |lcs-lead| for leading multiple spaces. `:set listchars=leadmultispace:---+` shows ten - consecutive leading spaces as: - ---+---+--XXX ~ + consecutive leading spaces as: > + ---+---+--XXX +< Where "XXX" denotes the first non-blank characters in the line. *lcs-trail* @@ -3911,9 +3972,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'* @@ -4065,7 +4126,8 @@ A jump table for the options with a short description can be found at |Q_op|. checked for set commands. If 'modeline' is off or 'modelines' is zero no lines are checked. See |modeline|. - *'modifiable'* *'ma'* *'nomodifiable'* *'noma'* *E21* + *'modifiable'* *'ma'* *'nomodifiable'* *'noma'* + *E21* 'modifiable' 'ma' boolean (default on) local to buffer When off the buffer contents cannot be changed. The 'fileformat' and @@ -4229,6 +4291,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 @@ -4289,7 +4360,7 @@ A jump table for the options with a short description can be found at |Q_op|. w x updown up-down sizing arrows w x leftright left-right sizing arrows w x busy The system's usual busy pointer - w x no The system's usual 'no input' pointer + w x no The system's usual "no input" pointer x udsizing indicates up-down resizing x lrsizing indicates left-right resizing x crosshair like a big thin + @@ -4366,12 +4437,12 @@ A jump table for the options with a short description can be found at |Q_op|. 'nonu' 'nu' 'nonu' 'nu' 'nornu' 'nornu' 'rnu' 'rnu' - +> |apple | 1 apple | 2 apple | 2 apple |pear | 2 pear | 1 pear | 1 pear |nobody | 3 nobody | 0 nobody |3 nobody |there | 4 there | 1 there | 1 there - +< *'numberwidth'* *'nuw'* 'numberwidth' 'nuw' number (default: 4) local to window @@ -4392,7 +4463,9 @@ A jump table for the options with a short description can be found at |Q_op|. This option specifies a function to be used for Insert mode omni completion with CTRL-X CTRL-O. |i_CTRL-X_CTRL-O| See |complete-functions| for an explanation of how the function is - invoked and what it should return. + invoked and what it should return. The value can be the name of a + function, a |lambda| or a |Funcref|. See |option-value-function| for + more information. This option is usually set by a filetype plugin: |:filetype-plugin-on| This option cannot be set from a |modeline| or in the |sandbox|, for @@ -4555,7 +4628,7 @@ A jump table for the options with a short description can be found at |Q_op|. < - A directory name may end in a ':' or '/'. - Environment variables are expanded |:set_env|. - When using |netrw.vim| URLs can be used. For example, adding - "http://www.vim.org" will make ":find index.html" work. + "https://www.vim.org" will make ":find index.html" work. - Search upwards and downwards in a directory tree using "*", "**" and ";". See |file-searching| for info and syntax. - Careful with '\' characters, type two to get one in the option: > @@ -4611,58 +4684,6 @@ A jump table for the options with a short description can be found at |Q_op|. set. It's normally not set directly, but by using one of the commands |:ptag|, |:pedit|, etc. - *'printdevice'* *'pdev'* -'printdevice' 'pdev' string (default empty) - global - The name of the printer to be used for |:hardcopy|. - See |pdev-option|. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - - *'printencoding'* *'penc'* -'printencoding' 'penc' string (default empty, except for some systems) - global - Sets the character encoding used when printing. - See |penc-option|. - - *'printexpr'* *'pexpr'* -'printexpr' 'pexpr' string (default: see below) - global - Expression used to print the PostScript produced with |:hardcopy|. - See |pexpr-option|. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - - *'printfont'* *'pfn'* -'printfont' 'pfn' string (default "courier") - global - The name of the font that will be used for |:hardcopy|. - See |pfn-option|. - - *'printheader'* *'pheader'* -'printheader' 'pheader' string (default "%<%f%h%m%=Page %N") - global - The format of the header produced in |:hardcopy| output. - See |pheader-option|. - - *'printmbcharset'* *'pmbcs'* -'printmbcharset' 'pmbcs' string (default "") - global - The CJK character set to be used for CJK output from |:hardcopy|. - See |pmbcs-option|. - - *'printmbfont'* *'pmbfn'* -'printmbfont' 'pmbfn' string (default "") - global - List of font names to be used for CJK output from |:hardcopy|. - See |pmbfn-option|. - - *'printoptions'* *'popt'* -'printoptions' 'popt' string (default "") - global - List of items that control the format of the output of |:hardcopy|. - See |popt-option|. - *'pumblend'* *'pb'* 'pumblend' 'pb' number (default 0) global @@ -4920,8 +4941,7 @@ A jump table for the options with a short description can be found at |Q_op|. $XDG_CONFIG_HOME/nvim/after") global List of directories to be searched for these runtime files: - filetype.vim filetypes by file name |new-filetype| - scripts.vim filetypes by file contents |new-filetype-scripts| + filetype.lua filetypes |new-filetype| autoload/ automatically loaded scripts |autoload-functions| colors/ color scheme files |:colorscheme| compiler/ compiler files |:compiler| @@ -4930,10 +4950,12 @@ 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 +4976,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 +4999,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) @@ -5084,19 +5101,6 @@ A jump table for the options with a short description can be found at |Q_op|. two letters (See |object-motions|). The default makes a section start at the nroff macros ".SH", ".NH", ".H", ".HU", ".nh" and ".sh". - *'secure'* *'nosecure'* *E523* -'secure' boolean (default off) - global - When on, ":autocmd", shell and write commands are not allowed in - ".nvimrc" and ".exrc" in the current directory and map commands are - displayed. Switch it off only if you know that you will not run into - problems, or when the 'exrc' option is off. On Unix this option is - only used if the ".nvimrc" or ".exrc" is not owned by you. This can be - dangerous if the systems allows users to do a "chown". You better set - 'secure' at the end of your |init.vim| then. - This option cannot be set from a |modeline| or in the |sandbox|, for - security reasons. - *'selection'* *'sel'* 'selection' 'sel' string (default "inclusive") global @@ -5341,7 +5345,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= @@ -5509,42 +5513,48 @@ A jump table for the options with a short description can be found at |Q_op|. messages, for example with CTRL-G, and to avoid some other messages. It is a list of flags: flag meaning when present ~ - f use "(3 of 5)" instead of "(file 3 of 5)" - i use "[noeol]" instead of "[Incomplete last line]" - l use "999L, 888B" instead of "999 lines, 888 bytes" - m use "[+]" instead of "[Modified]" - n use "[New]" instead of "[New File]" - r use "[RO]" instead of "[readonly]" - w use "[w]" instead of "written" for file write message + f use "(3 of 5)" instead of "(file 3 of 5)" *shm-f* + i use "[noeol]" instead of "[Incomplete last line]" *shm-i* + l use "999L, 888B" instead of "999 lines, 888 bytes" *shm-l* + m use "[+]" instead of "[Modified]" *shm-m* + n use "[New]" instead of "[New File]" *shm-n* + r use "[RO]" instead of "[readonly]" *shm-r* + w use "[w]" instead of "written" for file write message *shm-w* and "[a]" instead of "appended" for ':w >> file' command - x use "[dos]" instead of "[dos format]", "[unix]" instead of - "[unix format]" and "[mac]" instead of "[mac format]". - a all of the above abbreviations - - o overwrite message for writing a file with subsequent message - for reading a file (useful for ":wn" or when 'autowrite' on) - O message for reading a file overwrites any previous message. - Also for quickfix message (e.g., ":cn"). - s don't give "search hit BOTTOM, continuing at TOP" or "search - hit TOP, continuing at BOTTOM" messages; when using the search - count do not show "W" after the count message (see S below) - t truncate file message at the start if it is too long to fit - on the command-line, "<" will appear in the left most column. - Ignored in Ex mode. - T truncate other messages in the middle if they are too long to - fit on the command line. "..." will appear in the middle. - Ignored in Ex mode. - W don't give "written" or "[w]" when writing a file - A don't give the "ATTENTION" message when an existing swap file - is found. - I don't give the intro message when starting Vim |:intro|. - c don't give |ins-completion-menu| messages. For example, - "-- XXX completion (YYY)", "match 1 of 2", "The only match", - "Pattern not found", "Back at original", etc. - q use "recording" instead of "recording @a" - F don't give the file info when editing a file, like `:silent` - was used for the command - S do not show search count message when searching, e.g. + x use "[dos]" instead of "[dos format]", "[unix]" *shm-x* + instead of "[unix format]" and "[mac]" instead of "[mac + format]" + a all of the above abbreviations *shm-a* + + o overwrite message for writing a file with subsequent *shm-o* + message for reading a file (useful for ":wn" or when + 'autowrite' on) + O message for reading a file overwrites any previous *shm-O* + message; also for quickfix message (e.g., ":cn") + s don't give "search hit BOTTOM, continuing at TOP" or *shm-s* + "search hit TOP, continuing at BOTTOM" messages; when using + the search count do not show "W" after the count message (see + S below) + t truncate file message at the start if it is too long *shm-t* + to fit on the command-line, "<" will appear in the left most + column; ignored in Ex mode + T truncate other messages in the middle if they are too *shm-T* + long to fit on the command line; "..." will appear in the + middle; ignored in Ex mode + W don't give "written" or "[w]" when writing a file *shm-W* + A don't give the "ATTENTION" message when an existing *shm-A* + swap file is found + I don't give the intro message when starting Vim, *shm-I* + see |:intro| + c don't give |ins-completion-menu| messages; for *shm-c* + example, "-- XXX completion (YYY)", "match 1 of 2", "The only + match", "Pattern not found", "Back at original", etc. + C don't give messages while scanning for ins-completion *shm-C* + items, for instance "scanning tags" + q use "recording" instead of "recording @a" *shm-q* + F don't give the file info when editing a file, like *shm-F* + `:silent` was used for the command + S do not show search count message when searching, e.g. *shm-S* "[1/5]" This gives you the opportunity to avoid that a change between buffers @@ -5581,7 +5591,6 @@ A jump table for the options with a short description can be found at |Q_op|. global Show (partial) command in the last line of the screen. Set this option off if your terminal is slow. - The option has no effect when 'cmdheight' is zero. In Visual mode the size of the selected area is shown: - When selecting characters within a line, the number of characters. If the number of bytes is different it is also displayed: "2-6" @@ -5589,6 +5598,23 @@ A jump table for the options with a short description can be found at |Q_op|. - When selecting more than one line, the number of lines. - When selecting a block, the size in screen characters: {lines}x{columns}. + This information can be displayed in an alternative location using the + 'showcmdloc' option, useful when 'cmdheight' is 0. + + *'showcmdloc'* *'sloc'* +'showcmdloc' 'sloc' string (default "last") + global + This option can be used to display the (partially) entered command in + another location. Possible values are: + last Last line of the screen (default). + statusline Status line of the current window. + tabline First line of the screen if 'showtabline' is enabled. + Setting this option to "statusline" or "tabline" means that these will + be redrawn whenever the command changes, which can be on every key + pressed. + The %S 'statusline' item can be used in 'statusline' or 'tabline' to + place the text. Without a custom 'statusline' or 'tabline' it will be + displayed in a convenient location. *'showfulltag'* *'sft'* *'noshowfulltag'* *'nosft'* 'showfulltag' 'sft' boolean (default off) @@ -5692,9 +5718,9 @@ 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 + Note regarding "orphaned signs": with signcolumn numbers higher than 1, deleting lines will also remove the associated signs automatically, in contrast to the default Vim behavior of keeping and grouping them. This is done in order for the signcolumn appearance not appear weird @@ -5722,11 +5748,11 @@ A jump table for the options with a short description can be found at |Q_op|. alternative. Normally 'autoindent' should also be on when using 'smartindent'. An indent is automatically inserted: - - After a line ending in '{'. + - After a line ending in "{". - After a line starting with a keyword from 'cinwords'. - - Before a line starting with '}' (only with the "O" command). + - Before a line starting with "}" (only with the "O" command). When typing '}' as the first character in a new line, that line is - given the same indent as the matching '{'. + given the same indent as the matching "{". When typing '#' as the first character in a new line, the indent for that line is removed, the '#' is put in the first column. The indent is restored for the next line. If you don't want this, use this @@ -5860,10 +5886,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 +5969,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 @@ -5958,6 +6004,60 @@ A jump table for the options with a short description can be found at |Q_op|. In case of buffer changing commands the cursor is placed at the column where it was the last time the buffer was edited. + *'statuscolumn'* *'stc'* +'statuscolumn' 'stc' string (default: empty) + local to window + EXPERIMENTAL + When non-empty, this option determines the content of the area to the + side of a window, normally containing the fold, sign and number columns. + The format of this option is like that of 'statusline'. + + Some of the items from the 'statusline' format are different for + 'statuscolumn': + + %l line number of currently drawn line + %r relative line number of currently drawn line + %s sign column for currently drawn line + %C fold column for currently drawn line + + NOTE: To draw the sign and fold columns, their items must be included in + 'statuscolumn'. Even when they are not included, the status column width + will adapt to the 'signcolumn' and 'foldcolumn' width. + + The |v:lnum| variable holds the line number to be drawn. + The |v:relnum| variable holds the relative line number to be drawn. + The |v:virtnum| variable is negative when drawing virtual lines, zero + when drawing the actual buffer line, and positive when + drawing the wrapped part of a buffer line. + + NOTE: The %@ click execute function item is supported as well but the + specified function will be the same for each row in the same column. + It cannot be switched out through a dynamic 'statuscolumn' format, the + handler should be written with this in mind. + + Examples: >vim + " Relative number with bar separator and click handlers: + :set statuscolumn=%@SignCb@%s%=%T%@NumCb@%r│%T + + " Right aligned relative cursor line number: + :let &stc='%=%{v:relnum?v:relnum:v:lnum} ' + + " Line numbers in hexadecimal for non wrapped part of lines: + :let &stc='%=%{v:virtnum>0?"":printf("%x",v:lnum)} ' + + " Human readable line numbers with thousands separator: + :let &stc='%{substitute(v:lnum,"\\d\\zs\\ze\\' + . '%(\\d\\d\\d\\)\\+$",",","g")}' + + " Both relative and absolute line numbers with different + " highlighting for odd and even relative numbers: + :let &stc='%#NonText#%{&nu?v:lnum:""}' . + '%=%{&rnu&&(v:lnum%2)?"\ ".v:relnum:""}' . + '%#LineNr#%{&rnu&&!(v:lnum%2)?"\ ".v:relnum:""}' + +< WARNING: this expression is evaluated for each screen line so defining + an expensive expression can negatively affect render performance. + *'statusline'* *'stl'* *E540* *E542* 'statusline' 'stl' string (default empty) global or local to window |global-local| @@ -5982,6 +6082,8 @@ A jump table for the options with a short description can be found at |Q_op|. When there is error while evaluating the option then it will be made empty to avoid further errors. Otherwise screen updating would loop. + When the result contains unprintable characters the result is + unpredictable. Note that the only effect of 'ruler' when this option is set (and 'laststatus' is 2 or 3) is controlling the output of |CTRL-G|. @@ -5989,12 +6091,12 @@ A jump table for the options with a short description can be found at |Q_op|. field meaning ~ - Left justify the item. The default is right justified when minwid is larger than the length of the item. - 0 Leading zeroes in numeric items. Overridden by '-'. - minwid Minimum width of the item, padding as set by '-' & '0'. + 0 Leading zeroes in numeric items. Overridden by "-". + minwid Minimum width of the item, padding as set by "-" & "0". Value must be 50 or less. - maxwid Maximum width of the item. Truncation occurs with a '<' + maxwid Maximum width of the item. Truncation occurs with a "<" on the left for text items. Numeric items will be - shifted down to maxwid-2 digits followed by '>'number + shifted down to maxwid-2 digits followed by ">"number where number is the amount of missing digits, much like an exponential notation. item A one letter code as described below. @@ -6030,7 +6132,6 @@ A jump table for the options with a short description can be found at |Q_op|. o N Byte number in file of byte under cursor, first byte is 1. Mnemonic: Offset from start of file (with one added) O N As above, in hexadecimal. - N N Printer page number. (Only works in the 'printheader' option.) l N Line number. L N Number of lines in buffer. c N Column number (byte index). @@ -6040,24 +6141,25 @@ A jump table for the options with a short description can be found at |Q_op|. P S Percentage through file of displayed window. This is like the percentage described for 'ruler'. Always 3 in length, unless translated. + S S 'showcmd' content, see 'showcmdloc'. a S Argument list status as in default title. ({current} of {max}) Empty if the argument file count is zero or one. - { NF Evaluate expression between '%{' and '}' and substitute result. - Note that there is no '%' before the closing '}'. The - expression cannot contain a '}' character, call a function to + { NF Evaluate expression between "%{" and "}" and substitute result. + Note that there is no "%" before the closing "}". The + expression cannot contain a "}" character, call a function to work around that. See |stl-%{| below. - {% - This is almost same as { except the result of the expression is + `{%` - This is almost same as "{" except the result of the expression is re-evaluated as a statusline format string. Thus if the - return value of expr contains % items they will get expanded. - The expression can contain the } character, the end of - expression is denoted by %}. + return value of expr contains "%" items they will get expanded. + The expression can contain the "}" character, the end of + expression is denoted by "%}". For example: > func! Stl_filename() abort return "%t" endfunc < `stl=%{Stl_filename()}` results in `"%t"` `stl=%{%Stl_filename()%}` results in `"Name of current file"` - %} - End of `{%` expression + %} - End of "{%" expression ( - Start of item group. Can be used for setting the width and alignment of a section. Must be followed by %) somewhere. ) - End of item group. No width fields allowed. @@ -6252,12 +6354,12 @@ A jump table for the options with a short description can be found at |Q_op|. Otherwise this option does not always reflect the current syntax (the b:current_syntax variable does). This option is most useful in a modeline, for a file which syntax is - not automatically recognized. Example, in an IDL file: - /* vim: set syntax=idl : */ ~ - When a dot appears in the value then this separates two filetype - names. Example: - /* vim: set syntax=c.doxygen : */ ~ - This will use the "c" syntax first, then the "doxygen" syntax. + not automatically recognized. Example, in an IDL file: > + /* vim: set syntax=idl : */ +< When a dot appears in the value then this separates two filetype + names. Example: > + /* vim: set syntax=c.doxygen : */ +< This will use the "c" syntax first, then the "doxygen" syntax. Note that the second one must be prepared to be loaded as an addition, otherwise it will be skipped. More than one dot may appear. To switch off syntax highlighting for the current file, use: > @@ -6310,7 +6412,7 @@ A jump table for the options with a short description can be found at |Q_op|. the |:retab| command, and the 'softtabstop' option. Note: Setting 'tabstop' to any other value than 8 can make your file - appear wrong in many places, e.g., when printing it. + appear wrong in many places. The value must be more than 0 and less than 10000. There are four main ways to use tabs in Vim: @@ -6403,7 +6505,9 @@ A jump table for the options with a short description can be found at |Q_op|. This option specifies a function to be used to perform tag searches. The function gets the tag pattern and should return a List of matching tags. See |tag-function| for an explanation of how to write the - function and an example. + function and an example. The value can be the name of a function, a + |lambda| or a |Funcref|. See |option-value-function| for more + information. *'taglength'* *'tl'* 'taglength' 'tl' number (default 0) @@ -6465,7 +6569,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'* @@ -6526,6 +6630,8 @@ A jump table for the options with a short description can be found at |Q_op|. global or local to buffer |global-local| This option specifies a function to be used for thesaurus completion with CTRL-X CTRL-T. |i_CTRL-X_CTRL-T| See |compl-thesaurusfunc|. + The value can be the name of a function, a |lambda| or a |Funcref|. + See |option-value-function| for more information. This option cannot be set from a |modeline| or in the |sandbox|, for security reasons. @@ -6732,11 +6838,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 +6863,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 +7047,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: @@ -7022,6 +7134,14 @@ A jump table for the options with a short description can be found at |Q_op|. global A list of words that change how |cmdline-completion| is done. The following values are supported: + fuzzy Use |fuzzy-matching| to find completion matches. When + this value is specified, wildcard expansion will not + be used for completion. The matches will be sorted by + the "best match" rather than alphabetically sorted. + This will find more matches than the wildcard + expansion. Currently fuzzy matching based completion + is not supported for file and directory names and + instead wildcard expansion is used. pum Display the completion matches using the popup menu in the same style as the |ins-completion-menu|. tagfile When using CTRL-D to list matching tags, the kind of @@ -7117,7 +7237,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/pattern.txt b/runtime/doc/pattern.txt index 371a210847..5357aaa3f1 100644 --- a/runtime/doc/pattern.txt +++ b/runtime/doc/pattern.txt @@ -372,7 +372,7 @@ Vim includes two regexp engines: 1. An old, backtracking engine that supports everything. 2. A new, NFA engine that works much faster on some patterns, possibly slower on some patterns. - + *E1281* Vim will automatically select the right engine for you. However, if you run into a problem or want to specifically select one engine or the other, you can prepend one of the following to the pattern: diff --git a/runtime/doc/pi_health.txt b/runtime/doc/pi_health.txt index 04e04b5165..5ba5d1beef 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 < @@ -20,8 +21,8 @@ Plugin authors are encouraged to write new healthchecks. |health-dev| ============================================================================== Commands *health-commands* - *:checkhealth* *:CheckHealth* -:checkhealth Run all healthchecks. + *:che* *:checkhealth* *:CheckHealth* +:che[ckhealth] Run all healthchecks. *E5009* Nvim depends on |$VIMRUNTIME|, 'runtimepath' and 'packpath' to find the standard "runtime files" for syntax highlighting, @@ -29,29 +30,27 @@ Commands *health-commands* :checkhealth). If the runtime files cannot be found then those features will not work. -:checkhealth {plugins} +:che[ckhealth] {plugins} Run healthcheck(s) for one or more plugins. E.g. to run only the standard Nvim healthcheck: > :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..5167b4baf7 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 @@ -2419,15 +2419,6 @@ from the current window (where one does the mf) to the target. Associated setting variable: |g:netrw_localmovecmd| |g:netrw_ssh_cmd| -MARKED FILES: PRINTING *netrw-mp* {{{2 - (See |netrw-mf| and |netrw-mr| for how to mark files) - (uses the local marked file list) - -When "mp" is used, netrw will apply the |:hardcopy| command to marked files. -What netrw does is open each file in a one-line window, execute hardcopy, then -close the one-line window. - - MARKED FILES: SOURCING *netrw-ms* {{{2 (See |netrw-mf| and |netrw-mr| for how to mark files) (uses the local marked file list) @@ -2782,7 +2773,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. @@ -2821,12 +2812,12 @@ your browsing preferences. (see also: |netrw-settings|) function 'netrw_gitignore#Hide() automatically hiding all gitignored files. For more details see |netrw-gitignore|. + default: "" - Examples: - let g:netrw_list_hide= '.*\.swp$' - let g:netrw_list_hide= netrw_gitignore#Hide() .. '.*\.swp$' - default: "" - + Examples: > + let g:netrw_list_hide= '.*\.swp$' + let g:netrw_list_hide= netrw_gitignore#Hide() .. '.*\.swp$' +< *g:netrw_localcopycmd* ="cp" Linux/Unix/MacOS/Cygwin =expand("$COMSPEC") Windows Copies marked files (|netrw-mf|) to target @@ -3268,7 +3259,7 @@ If there are marked files: (see |netrw-mf|) mr [query: reply with *.c] R [query: reply with s/^\(.*\)\.c$/\1.cpp/] < - This example will mark all *.c files and then rename them to *.cpp + This example will mark all "*.c" files and then rename them to "*.cpp" files. Netrw will protect you from overwriting local files without confirmation, but not remote ones. @@ -3280,7 +3271,7 @@ If there are marked files: (see |netrw-mf|) <c-x><c-x> : a pair of contiguous ctrl-x's tells netrw to ignore any portion of the string preceding the double ctrl-x's. < - WARNING:~ + WARNING: ~ Note that moving files is a dangerous operation; copies are safer. That's because a "move" for remote files is actually a copy + delete -- and if @@ -3469,7 +3460,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 +3473,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 +3481,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 +3560,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) @@ -3776,9 +3767,9 @@ Example: Clear netrw's marked file list via a mapping on gu > < *netrw-P22* P22. I get an error message when I try to copy or move a file: {{{2 - +> **error** (netrw) tried using g:netrw_localcopycmd<cp>; it doesn't work! - +< What's wrong? Netrw uses several system level commands to do things (see @@ -3839,7 +3830,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 +3908,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 +3934,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, @@ -4001,9 +3992,9 @@ netrw: Nov 22, 2016 * (glacambre) reported that files containing spaces weren't being obtained properly via scp. Fix: apparently using single quotes - such as with 'file name' wasn't enough; the + such as with "file name" wasn't enough; the spaces inside the quotes also had to be - escaped (ie. 'file\ name'). + escaped (ie. "file\ name"). * Also fixed obtain (|netrw-O|) to be able to obtain files with spaces in their names Dec 20, 2016 * (xc1427) Reported that using "I" (|netrw-I|) diff --git a/runtime/doc/pi_spec.txt b/runtime/doc/pi_spec.txt index 6d45a0f064..d485d6ad49 100644 --- a/runtime/doc/pi_spec.txt +++ b/runtime/doc/pi_spec.txt @@ -34,8 +34,8 @@ also check if the name, version and release matches. The plugin is smart enough to ask you if it should update the package release, if you have not done so. +------------------------------------------------------------------------------ Setting a map *spec-setting-a-map* -------------- As you should know, you can easily set a map to access any Vim command (or anything, for that matter). If you don't like the default map of @@ -54,8 +54,8 @@ This command will add a map only in the spec file buffers. ============================================================================== 2. Customizing *spec-customizing* +------------------------------------------------------------------------------ The format string *spec_chglog_format* ------------------ You can easily customize how your spec file entry will look like. To do this just set the variable "spec_chglog_format" in your vimrc file like @@ -72,8 +72,8 @@ address once. To discover which format options you can use, take a look at the strftime() function man page. +------------------------------------------------------------------------------ Where to insert new items *spec_chglog_prepend* -------------------------- The plugin will usually insert new %changelog entry items (note that it's not the entry itself) after the existing ones. If you set the @@ -83,8 +83,8 @@ spec_chglog_prepend variable > it will insert new items before the existing ones. +------------------------------------------------------------------------------ Inserting release info *spec_chglog_release_info* ----------------------- If you want, the plugin may automatically insert release information on each changelog entry. One advantage of turning this feature on is diff --git a/runtime/doc/pi_tar.txt b/runtime/doc/pi_tar.txt index c6c0596ea0..2230b82dec 100644 --- a/runtime/doc/pi_tar.txt +++ b/runtime/doc/pi_tar.txt @@ -80,25 +80,25 @@ Copyright 2005-2017: *tar-copyright* These options are variables that one may change, typically in one's <.vimrc> file. - Default - Variable Value Explanation - *g:tar_browseoptions* "Ptf" used to get a list of contents - *g:tar_readoptions* "OPxf" used to extract a file from a tarball - *g:tar_cmd* "tar" the name of the tar program - *g:tar_nomax* 0 if true, file window will not be maximized - *g:tar_secure* undef if exists: + Default + Variable Value Explanation + *g:tar_browseoptions* "Ptf" used to get a list of contents + *g:tar_readoptions* "OPxf" used to extract a file from a tarball + *g:tar_cmd* "tar" the name of the tar program + *g:tar_nomax* 0 if true, file window will not be maximized + *g:tar_secure* undef if exists: "--"s will be used to prevent unwanted option expansion in tar commands. Please be sure that your tar command accepts "--"; Posix compliant tar utilities do accept them. if not exists: - The tar plugin will reject any tar + The tar plugin will reject any tar files or member files that begin with "-" Not all tar's support the "--" which is why it isn't default. - *g:tar_writeoptions* "uf" used to update/replace a file + *g:tar_writeoptions* "uf" used to update/replace a file ============================================================================== diff --git a/runtime/doc/pi_zip.txt b/runtime/doc/pi_zip.txt index 2bbd6eea06..9b531d78b4 100644 --- a/runtime/doc/pi_zip.txt +++ b/runtime/doc/pi_zip.txt @@ -39,7 +39,7 @@ Copyright: Copyright (C) 2005-2015 Charles E Campbell *zip-copyright* OPTIONS~ - *g:zip_nomax* + *g:zip_nomax* If this variable exists and is true, the file window will not be automatically maximized when opened. @@ -54,21 +54,21 @@ Copyright: Copyright (C) 2005-2015 Charles E Campbell *zip-copyright* under Windows ("). If you'd rather have no quotes, simply set g:zip_shq to the empty string (let g:zip_shq= "") in your <.vimrc>. - *g:zip_unzipcmd* + *g:zip_unzipcmd* Use this option to specify the program which does the duty of "unzip". It's used during browsing. By default: > - let g:zip_unzipcmd= "unzip" + let g:zip_unzipcmd= "unzip" < *g:zip_zipcmd* Use this option to specify the program which does the duty of "zip". It's used during the writing (updating) of a file already in a zip file; by default: > - let g:zip_zipcmd= "zip" + let g:zip_zipcmd= "zip" < *g:zip_extractcmd* This option specifies the program (and any options needed) used to extract a file from a zip archive. By default, > - let g:zip_extractcmd= g:zip_unzipcmd + let g:zip_extractcmd= g:zip_unzipcmd < PREVENTING LOADING~ @@ -103,14 +103,14 @@ Copyright: Copyright (C) 2005-2015 Charles E Campbell *zip-copyright* ============================================================================== 4. History *zip-history* {{{1 v32 Oct 22, 2021 * to avoid an issue with a vim 8.2 patch, zipfile: has - been changed to zipfile:// . This often shows up + been changed to zipfile:// . This often shows up as zipfile:/// with zipped files that are root-based. v29 Apr 02, 2017 * (Klartext) reported that an encrypted zip file could - opened but the swapfile held unencrypted contents. + opened but the swapfile held unencrypted contents. The solution is to edit the contents of a zip file using the |:noswapfile| modifier. v28 Oct 08, 2014 * changed the sanity checks for executables to reflect - the command actually to be attempted in zip#Read() + the command actually to be attempted in zip#Read() and zip#Write() * added the extraction of a file capability Nov 30, 2015 * added *.epub to the |g:zipPlugin_ext| list diff --git a/runtime/doc/print.txt b/runtime/doc/print.txt deleted file mode 100644 index 924fab175e..0000000000 --- a/runtime/doc/print.txt +++ /dev/null @@ -1,721 +0,0 @@ -*print.txt* Nvim - - - VIM REFERENCE MANUAL by Bram Moolenaar - - -Printing *printing* - - Type |gO| to see the table of contents. - -============================================================================== -1. Introduction *print-intro* - -On MS-Windows Vim can print your text on any installed printer. On other -systems a PostScript file is produced. This can be directly sent to a -PostScript printer. For other printers a program like ghostscript needs to be -used. - -Note: If you have problems printing with |:hardcopy|, an alternative is to use -|:TOhtml| and print the resulting html file from a browser. - - *:ha* *:hardcopy* *E237* *E238* *E324* -:[range]ha[rdcopy][!] [arguments] - Send [range] lines (default whole file) to the - printer. - - On MS-Windows a dialog is displayed to allow selection - of printer, paper size etc. To skip the dialog, use - the [!]. In this case the printer defined by - 'printdevice' is used, or, if 'printdevice' is empty, - the system default printer. - - For systems other than MS-Windows, PostScript is - written in a temp file and 'printexpr' is used to - actually print it. Then [arguments] can be used by - 'printexpr' through |v:cmdarg|. Otherwise [arguments] - is ignored. 'printoptions' can be used to specify - paper size, duplex, etc. - Note: If you want PDF, there are tools such as - "ps2pdf" that can convert the PostScript to PDF. - -:[range]ha[rdcopy][!] >{filename} - As above, but write the resulting PostScript in file - {filename}. - Things like "%" are expanded |cmdline-special| - Careful: An existing file is silently overwritten. - On MS-Windows use the "print to file" feature of the - printer driver. - -Progress is displayed during printing as a page number and a percentage. To -abort printing use the interrupt key (CTRL-C or, on MS-systems, CTRL-Break). - -Printer output is controlled by the 'printfont' and 'printoptions' options. -'printheader' specifies the format of a page header. - -The printed file is always limited to the selected margins, irrespective of -the current window's 'wrap' or 'linebreak' settings. The "wrap" item in -'printoptions' can be used to switch wrapping off. -The current highlighting colors are used in the printout, with the following -considerations: -1) The normal background is always rendered as white (i.e. blank paper). -2) White text or the default foreground is rendered as black, so that it shows - up! -3) If 'background' is "dark", then the colours are darkened to compensate for - the fact that otherwise they would be too bright to show up clearly on - white paper. - -============================================================================== -2. Print options *print-options* - -Here are the details for the options that change the way printing is done. -For generic info about setting options see |options.txt|. - - *pdev-option* -'printdevice' 'pdev' string (default empty) - global -This defines the name of the printer to be used when the |:hardcopy| command -is issued with a bang (!) to skip the printer selection dialog. On Win32, it -should be the printer name exactly as it appears in the standard printer -dialog. -If the option is empty, then vim will use the system default printer for -":hardcopy!" - - *penc-option* *E620* -'printencoding' 'penc' String (default empty, except for: - Windows: cp1252, - Macintosh: mac-roman, - HPUX: hp-roman8) - global -Sets the character encoding used when printing. This option tells Vim which -print character encoding file from the "print" directory in 'runtimepath' to -use. - -This option will accept any value from |encoding-names|. Any recognized names -are converted to Vim standard names - see 'encoding' for more details. Names -not recognized by Vim will just be converted to lower case and underscores -replaced with '-' signs. - -If 'printencoding' is empty or Vim cannot find the file then it will use -'encoding' (if it is set an 8-bit encoding) to find the print character -encoding file. If Vim is unable to find a character encoding file then it -will use the "latin1" print character encoding file. - -When 'encoding' is set to a multibyte encoding, Vim will try to convert -characters to the printing encoding for printing (if 'printencoding' is empty -then the conversion will be to latin1). If no conversion is possible then -printing will fail. Any characters that cannot be converted will be replaced -with upside down question marks. - -Two print character encoding files are provided to support default Mac and -HPUX character encodings and are used by default on these platforms. Code page -1252 print character encoding is used by default on the Windows platform. - - *pexpr-option* -'printexpr' 'pexpr' String (default: see below) - global -Expression that is evaluated to print the PostScript produced with -|:hardcopy|. -The file name to be printed is in |v:fname_in|. -The arguments to the ":hardcopy" command are in |v:cmdarg|. -The expression must take care of deleting the file after printing it. -When there is an error, the expression must return a non-zero number. -If there is no error, return zero or an empty string. -The default for non MS-Windows systems is to simply use "lpr" to print the -file: > - - system(['lpr'] - + (empty(&printdevice)?[]:['-P', &printdevice]) - + [v:fname_in]) - .. delete(v:fname_in) - + v:shell_error - -On MS-Dos and MS-Windows machines the default is to copy the file to the -currently specified printdevice: > - - system(['copy', v:fname_in, empty(&printdevice)?'LPT1':&printdevice]) - .. delete(v:fname_in) - -If you change this option, using a function is an easy way to avoid having to -escape all the spaces. Example: > - - :set printexpr=PrintFile(v:fname_in) - :function PrintFile(fname) - : call system("ghostview " .. a:fname) - : call delete(a:fname) - : return v:shell_error - :endfunc - -Be aware that some print programs return control before they have read the -file. If you delete the file too soon it will not be printed. These programs -usually offer an option to have them remove the file when printing is done. - *E365* -If evaluating the expression fails or it results in a non-zero number, you get -an error message. In that case Vim will delete the file. In the default -value for non-MS-Windows a trick is used: Adding "v:shell_error" will result -in a non-zero number when the system() call fails. - -This option cannot be set from a |modeline| or in the |sandbox|, for security -reasons. - - *pfn-option* *E613* -'printfont' 'pfn' string (default "courier") - global -This is the name of the font that will be used for the |:hardcopy| command's -output. It has the same format as the 'guifont' option, except that only one -font may be named, and the special "guifont=*" syntax is not available. - -In the Win32 GUI version this specifies a font name with its extra attributes, -as with the 'guifont' option. - -For other systems, only ":h11" is recognized, where "11" is the point size of -the font. When omitted, the point size is 10. - - *pheader-option* -'printheader' 'pheader' string (default "%<%f%h%m%=Page %N") - global -This defines the format of the header produced in |:hardcopy| output. The -option is defined in the same way as the 'statusline' option. The same simple -header is used when this option is empty. - - *pmbcs-option* -'printmbcharset' 'pmbcs' string (default "") - global -Sets the CJK character set to be used when generating CJK output from -|:hardcopy|. The following predefined values are currently recognised by Vim: - - Value Description ~ - Chinese GB_2312-80 - (Simplified) GBT_12345-90 - MAC Apple Mac Simplified Chinese - GBT-90_MAC GB/T 12345-90 Apple Mac Simplified - Chinese - GBK GBK (GB 13000.1-93) - ISO10646 ISO 10646-1:1993 - - Chinese CNS_1993 CNS 11643-1993, Planes 1 & 2 - (Traditional) BIG5 - ETEN Big5 with ETen extensions - ISO10646 ISO 10646-1:1993 - - Japanese JIS_C_1978 - JIS_X_1983 - JIS_X_1990 - MSWINDOWS Win3.1/95J (JIS X 1997 + NEC + - IBM extensions) - KANJITALK6 Apple Mac KanjiTalk V6.x - KANJITALK7 Apple Mac KanjiTalk V7.x - - Korean KS_X_1992 - MAC Apple Macintosh Korean - MSWINDOWS KS X 1992 with MS extensions - ISO10646 ISO 10646-1:1993 - -Only certain combinations of the above values and 'printencoding' are -possible. The following tables show the valid combinations: - - euc-cn gbk ucs-2 utf-8 ~ - Chinese GB_2312-80 x - (Simplified) GBT_12345-90 x - MAC x - GBT-90_MAC x - GBK x - ISO10646 x x - - euc-tw big5 ucs-2 utf-8 ~ - Chinese CNS_1993 x - (Traditional) BIG5 x - ETEN x - ISO10646 x x - - euc-jp sjis ucs-2 utf-8 ~ - Japanese JIS_C_1978 x x - JIS_X_1983 x x - JIS_X_1990 x x x - MSWINDOWS x - KANJITALK6 x - KANJITALK7 x - - euc-kr cp949 ucs-2 utf-8 ~ - Korean KS_X_1992 x - MAC x - MSWINDOWS x - ISO10646 x x - -To set up the correct encoding and character set for printing some -Japanese text you would do the following; > - :set printencoding=euc-jp - :set printmbcharset=JIS_X_1983 - -If 'printmbcharset' is not one of the above values then it is assumed to -specify a custom multibyte character set and no check will be made that it is -compatible with the value for 'printencoding'. Vim will look for a file -defining the character set in the "print" directory in 'runtimepath'. - - *pmbfn-option* -'printmbfont' 'pmbfn' string (default "") - global -This is a comma-separated list of fields for font names to be used when -generating CJK output from |:hardcopy|. Each font name has to be preceded -with a letter indicating the style the font is to be used for as follows: - - r:{font-name} font to use for normal characters - b:{font-name} font to use for bold characters - i:{font-name} font to use for italic characters - o:{font-name} font to use for bold-italic characters - -A field with the r: prefix must be specified when doing CJK printing. The -other fontname specifiers are optional. If a specifier is missing then -another font will be used as follows: - - if b: is missing, then use r: - if i: is missing, then use r: - if o: is missing, then use b: - -Some CJK fonts do not contain characters for codes in the ASCII code range. -Also, some characters in the CJK ASCII code ranges differ in a few code points -from traditional ASCII characters. There are two additional fields to control -printing of characters in the ASCII code range. - - c:yes Use Courier font for characters in the ASCII - c:no (default) code range. - - a:yes Use ASCII character set for codes in the ASCII - a:no (default) code range. - -The following is an example of specifying two multibyte fonts, one for normal -and italic printing and one for bold and bold-italic printing, and using -Courier to print codes in the ASCII code range but using the national -character set: > - :set printmbfont=r:WadaMin-Regular,b:WadaMin-Bold,c:yes -< - *popt-option* -'printoptions' 'popt' string (default "") - global -This is a comma-separated list of items that control the format of the output -of |:hardcopy|: - - left:{spec} left margin (default: 10pc) - right:{spec} right margin (default: 5pc) - top:{spec} top margin (default: 5pc) - bottom:{spec} bottom margin (default: 5pc) - {spec} is a number followed by "in" for inches, "pt" - for points (1 point is 1/72 of an inch), "mm" for - millimeters or "pc" for a percentage of the media - size. - Weird example: - left:2in,top:30pt,right:16mm,bottom:3pc - If the unit is not recognized there is no error and - the default value is used. - - header:{nr} Number of lines to reserve for the header. - Only the first line is actually filled, thus when {nr} - is 2 there is one empty line. The header is formatted - according to 'printheader'. - header:0 Do not print a header. - header:2 (default) Use two lines for the header - - syntax:n Do not use syntax highlighting. This is faster and - thus useful when printing large files. - syntax:y Do syntax highlighting. - syntax:a (default) Use syntax highlighting if the printer appears to be - able to print color or grey. - - number:y Include line numbers in the printed output. - number:n (default) No line numbers. - - wrap:y (default) Wrap long lines. - wrap:n Truncate long lines. - - duplex:off Print on one side. - duplex:long (default) Print on both sides (when possible), bind on long - side. - duplex:short Print on both sides (when possible), bind on short - side. - - collate:y (default) Collating: 1 2 3, 1 2 3, 1 2 3 - collate:n No collating: 1 1 1, 2 2 2, 3 3 3 - - jobsplit:n (default) Do all copies in one print job - jobsplit:y Do each copy as a separate print job. Useful when - doing N-up postprocessing. - - portrait:y (default) Orientation is portrait. - portrait:n Orientation is landscape. - *a4* *letter* - paper:A4 (default) Paper size: A4 - paper:{name} Paper size from this table: - {name} size in cm size in inch ~ - 10x14 25.4 x 35.57 10 x 14 - A3 29.7 x 42 11.69 x 16.54 - A4 21 x 29.7 8.27 x 11.69 - A5 14.8 x 21 5.83 x 8.27 - B4 25 x 35.3 10.12 x 14.33 - B5 17.6 x 25 7.17 x 10.12 - executive 18.42 x 26.67 7.25 x 10.5 - folio 21 x 33 8.27 x 13 - ledger 43.13 x 27.96 17 x 11 - legal 21.59 x 35.57 8.5 x 14 - letter 21.59 x 27.96 8.5 x 11 - quarto 21.59 x 27.5 8.5 x 10.83 - statement 13.97 x 21.59 5.5 x 8.5 - tabloid 27.96 x 43.13 11 x 17 - - formfeed:n (default) Treat form feed characters (0x0c) as a normal print - character. - formfeed:y When a form feed character is encountered, continue - printing of the current line at the beginning of the - first line on a new page. - -The item indicated with (default) is used when the item is not present. The -values are not always used, especially when using a dialog to select the -printer and options. -Example: > - :set printoptions=paper:letter,duplex:off - -============================================================================== -3. PostScript Printing *postscript-printing* - *E455* *E456* *E457* *E624* -Provided you have enough disk space there should be no problems generating a -PostScript file. You need to have the runtime files correctly installed (if -you can find the help files, they probably are). - -There are currently a number of limitations with PostScript printing: - -- 'printfont' - The font name is ignored (the Courier family is always used - - it should be available on all PostScript printers) but the font size is - used. - -- 'printoptions' - The duplex setting is used when generating PostScript - output, but it is up to the printer to take notice of the setting. If the - printer does not support duplex printing then it should be silently ignored. - Some printers, however, don't print at all. - -- 8-bit support - While a number of 8-bit print character encodings are - supported it is possible that some characters will not print. Whether a - character will print depends on the font in the printer knowing the - character. Missing characters will be replaced with an upside down question - mark, or a space if that character is also not known by the font. It may be - possible to get all the characters in an encoding to print by installing a - new version of the Courier font family. - -- Multi-byte support - Currently Vim will try to convert multibyte characters - to the 8-bit encoding specified by 'printencoding' (or latin1 if it is - empty). Any characters that are not successfully converted are shown as - unknown characters. Printing will fail if Vim cannot convert the multibyte - to the 8-bit encoding. - -============================================================================== -4. Custom 8-bit Print Character Encodings *postscript-print-encoding* - *E618* *E619* -To use your own print character encoding when printing 8-bit character data -you need to define your own PostScript font encoding vector. Details on how -to define a font encoding vector is beyond the scope of this help file, but -you can find details in the PostScript Language Reference Manual, 3rd Edition, -published by Addison-Wesley and available in PDF form at -http://www.adobe.com/. The following describes what you need to do for Vim to -locate and use your print character encoding. - -i. Decide on a unique name for your encoding vector, one that does not clash - with any of the recognized or standard encoding names that Vim uses (see - |encoding-names| for a list), and that no one else is likely to use. -ii. Copy $VIMRUNTIME/print/latin1.ps to the print subdirectory in your - 'runtimepath' and rename it with your unique name. -iii. Edit your renamed copy of latin1.ps, replacing all occurrences of latin1 - with your unique name (don't forget the line starting %%Title:), and - modify the array of glyph names to define your new encoding vector. The - array must have exactly 256 entries or you will not be able to print! -iv. Within Vim, set 'printencoding' to your unique encoding name and then - print your file. Vim will now use your custom print character encoding. - -Vim will report an error with the resource file if you change the order or -content of the first 3 lines, other than the name of the encoding on the line -starting %%Title: or the version number on the line starting %%Version:. - -[Technical explanation for those that know PostScript - Vim looks for a file -with the same name as the encoding it will use when printing. The file -defines a new PostScript Encoding resource called /VIM-name, where name is the -print character encoding Vim will use.] - -============================================================================== -5. PostScript CJK Printing *postscript-cjk-printing* - *E673* *E674* *E675* - -Vim supports printing of Chinese, Japanese, and Korean files. Setting up Vim -to correctly print CJK files requires setting up a few more options. - -Each of these countries has many standard character sets and encodings which -require that both be specified when printing. In addition, CJK fonts normally -do not have the concept of italic glyphs and use different weight or stroke -style to achieve emphasis when printing. This in turn requires a different -approach to specifying fonts to use when printing. - -The encoding and character set are specified with the 'printencoding' and -'printmbcharset' options. If 'printencoding' is not specified then 'encoding' -is used as normal. If 'printencoding' is specified then characters will be -translated to this encoding for printing. You should ensure that the encoding -is compatible with the character set needed for the file contents or some -characters may not appear when printed. - -The fonts to use for CJK printing are specified with 'printmbfont'. This -option allows you to specify different fonts to use when printing characters -which are syntax highlighted with the font styles normal, italic, bold and -bold-italic. - -No CJK fonts are supplied with Vim. There are some free Korean, Japanese, and -Traditional Chinese fonts available at: - - http://examples.oreilly.com/cjkvinfo/adobe/samples/ - -You can find descriptions of the various fonts in the read me file at - - http://examples.oreilly.de/english_examples/cjkvinfo/adobe/00README - -Please read your printer documentation on how to install new fonts. - -CJK fonts can be large containing several thousand glyphs, and it is not -uncommon to find that they only contain a subset of a national standard. It -is not unusual to find the fonts to not include characters for codes in the -ASCII code range. If you find half-width Roman characters are not appearing -in your printout then you should configure Vim to use the Courier font the -half-width ASCII characters with 'printmbfont'. If your font does not include -other characters then you will need to find another font that does. - -Another issue with ASCII characters, is that the various national character -sets specify a couple of different glyphs in the ASCII code range. If you -print ASCII text using the national character set you may see some unexpected -characters. If you want true ASCII code printing then you need to configure -Vim to output ASCII characters for the ASCII code range with 'printmbfont'. - -It is possible to define your own multibyte character set although this -should not be attempted lightly. A discussion on the process if beyond the -scope of these help files. You can find details on CMap (character map) files -in the document 'Adobe CMap and CIDFont Files Specification, Version 1.0', -available from http://www.adobe.com as a PDF file. - -============================================================================== -6. PostScript Printing Troubleshooting *postscript-print-trouble* - *E621* -Usually the only sign of a problem when printing with PostScript is that your -printout does not appear. If you are lucky you may get a printed page that -tells you the PostScript operator that generated the error that prevented the -print job completing. - -There are a number of possible causes as to why the printing may have failed: - -- Wrong version of the prolog resource file. The prolog resource file - contains some PostScript that Vim needs to be able to print. Each version - of Vim needs one particular version. Make sure you have correctly installed - the runtime files, and don't have any old versions of a file called prolog - in the print directory in your 'runtimepath' directory. - -- Paper size. Some PostScript printers will abort printing a file if they do - not support the requested paper size. By default Vim uses A4 paper. Find - out what size paper your printer normally uses and set the appropriate paper - size with 'printoptions'. If you cannot find the name of the paper used, - measure a sheet and compare it with the table of supported paper sizes listed - for 'printoptions', using the paper that is closest in both width AND height. - Note: The dimensions of actual paper may vary slightly from the ones listed. - If there is no paper listed close enough, then you may want to try psresize - from PSUtils, discussed below. - -- Two-sided printing (duplex). Normally a PostScript printer that does not - support two-sided printing will ignore any request to do it. However, some - printers may abort the job altogether. Try printing with duplex turned off. - Note: Duplex prints can be achieved manually using PS utils - see below. - -- Collated printing. As with Duplex printing, most PostScript printers that - do not support collating printouts will ignore a request to do so. Some may - not. Try printing with collation turned off. - -- Syntax highlighting. Some print management code may prevent the generated - PostScript file from being printed on a black and white printer when syntax - highlighting is turned on, even if solid black is the only color used. Try - printing with syntax highlighting turned off. - -A safe printoptions setting to try is: > - - :set printoptions=paper:A4,duplex:off,collate:n,syntax:n - -Replace "A4" with the paper size that best matches your printer paper. - -============================================================================== -7. PostScript Utilities *postscript-print-util* - -7.1 Ghostscript - -Ghostscript is a PostScript and PDF interpreter that can be used to display -and print on non-PostScript printers PostScript and PDF files. It can also -generate PDF files from PostScript. - -Ghostscript will run on a wide variety of platforms. - -There are three available versions: - -- AFPL Ghostscript (formerly Aladdin Ghostscript) which is free for - non-commercial use. It can be obtained from: - - http://www.cs.wisc.edu/~ghost/ - -- GNU Ghostscript which is available under the GNU General Public License. It - can be obtained from: - - ftp://mirror.cs.wisc.edu/pub/mirrors/ghost/gnu/ - -- A commercial version for inclusion in commercial products. - -Additional information on Ghostscript can also be found at: - - http://www.ghostscript.com/ - -Support for a number of non PostScript printers is provided in the -distribution as standard, but if you cannot find support for your printer -check the Ghostscript site for other printers not included by default. - - -7.2 Ghostscript Previewers. - -The interface to Ghostscript is very primitive so a number of graphical front -ends have been created. These allow easier PostScript file selection, -previewing at different zoom levels, and printing. Check supplied -documentation for full details. - -X11 - -- Ghostview. Obtainable from: - - http://www.cs.wisc.edu/~ghost/gv/ - -- gv. Derived from Ghostview. Obtainable from: - - http://wwwthep.physik.uni-mainz.de/~plass/gv/ - - Copies (possibly not the most recent) can be found at: - - http://www.cs.wisc.edu/~ghost/gv/ - -MS-Windows - -- GSview. Obtainable from: - - http://www.cs.wisc.edu/~ghost/gsview/ - -Linux - -- GSview. Linux version of the popular MS-Windows previewer. - Obtainable from: - - http://www.cs.wisc.edu/~ghost/gsview/ - -- BMV. Different from Ghostview and gv in that it doesn't use X but svgalib. - Obtainable from: - - ftp://sunsite.unc.edu/pub/Linux/apps/graphics/viewers/svga/bmv-1.2.tgz - - -7.3 PSUtils - -PSUtils is a collection of utility programs for manipulating PostScript -documents. Binary distributions are available for many platforms, as well as -the full source. PSUtils can be found at: - - http://knackered.org/angus/psutils - -The utilities of interest include: - -- psnup. Convert PS files for N-up printing. -- psselect. Select page range and order of printing. -- psresize. Change the page size. -- psbook. Reorder and lay out pages ready for making a book. - -The output of one program can be used as the input to the next, allowing for -complex print document creation. - - -N-UP PRINTING - -The psnup utility takes an existing PostScript file generated from Vim and -convert it to an n-up version. The simplest way to create a 2-up printout is -to first create a PostScript file with: > - - :hardcopy > test.ps - -Then on your command line execute: > - - psnup -n 2 test.ps final.ps - -Note: You may get warnings from some Ghostscript previewers for files produced -by psnup - these may safely be ignored. - -Finally print the file final.ps to your PostScript printer with your -platform's print command. (You will need to delete the two PostScript files -afterwards yourself.) 'printexpr' could be modified to perform this extra -step before printing. - - -ALTERNATE DUPLEX PRINTING - -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 -files with all the odd and even numbered pages with: > - - psselect -o test.ps odd.ps - psselect -e test.ps even.ps - -Next print odd.ps with your platform's normal print command. Then take the -print output, turn it over and place it back in the paper feeder. Now print -even.ps with your platform's print command. All the even pages should now -appear on the back of the odd pages. - -There are a couple of points to bear in mind: - -1. Position of the first page. If the first page is on top of the printout - when printing the odd pages then you need to reverse the order that the odd - pages are printed. This can be done with the -r option to psselect. This - will ensure page 2 is printed on the back of page 1. - Note: it is better to reverse the odd numbered pages rather than the even - numbered in case there are an odd number of pages in the original PS file. - -2. Paper flipping. When turning over the paper with the odd pages printed on - them you may have to either flip them horizontally (along the long edge) or - vertically (along the short edge), as well as possibly rotating them 180 - degrees. All this depends on the printer - it will be more obvious for - desktop ink jets than for small office laser printers where the paper path - is hidden from view. - - -============================================================================== -8. Formfeed Characters *printing-formfeed* - -By default Vim does not do any special processing of formfeed control -characters. Setting the 'printoptions' formfeed item will make Vim recognize -formfeed characters and continue printing the current line at the beginning -of the first line on a new page. The use of formfeed characters provides -rudimentary print control but there are certain things to be aware of. - -Vim will always start printing a line (including a line number if enabled) -containing a formfeed character, even if it is the first character on the -line. This means if a line starting with a formfeed character is the first -line of a page then Vim will print a blank page. - -Since the line number is printed at the start of printing the line containing -the formfeed character, the remainder of the line printed on the new page -will not have a line number printed for it (in the same way as the wrapped -lines of a long line when wrap in 'printoptions' is enabled). - -If the formfeed character is the last character on a line, then printing will -continue on the second line of the new page, not the first. This is due to -Vim processing the end of the line after the formfeed character and moving -down a line to continue printing. - -Due to the points made above it is recommended that when formfeed character -processing is enabled, printing of line numbers is disabled, and that form -feed characters are not the last character on a line. Even then you may need -to adjust the number of lines before a formfeed character to prevent -accidental blank pages. - -============================================================================== - vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/provider.txt b/runtime/doc/provider.txt index 9fd35f19c5..5375d971f0 100644 --- a/runtime/doc/provider.txt +++ b/runtime/doc/provider.txt @@ -36,7 +36,7 @@ itself). For Python 3 plugins: 1. Make sure Python 3.4+ is available in your $PATH. -2. Install the module (try "python" if "python3" is missing): > +2. Install the module (try "python" if "python3" is missing): >bash python3 -m pip install --user --upgrade pynvim The pip `--upgrade` flag ensures that you get the latest version even if @@ -46,7 +46,7 @@ See also |python-virtualenv|. Note: The old "neovim" module was renamed to "pynvim". https://github.com/neovim/neovim/wiki/Following-HEAD#20181118 -If you run into problems, uninstall _both_ then install "pynvim" again: > +If you run into problems, uninstall _both_ then install "pynvim" again: >bash python -m pip uninstall neovim pynvim python -m pip install --user --upgrade pynvim @@ -55,11 +55,11 @@ PYTHON PROVIDER CONFIGURATION ~ *g:python3_host_prog* Command to start Python 3 (executable, not directory). Setting this makes startup faster. Useful for working with virtualenvs. Must be set before any -check for has("python3"). > +check for has("python3"). >vim let g:python3_host_prog = '/path/to/python3' < *g:loaded_python3_provider* -To disable Python 3 support: > +To disable Python 3 support: >vim let g:loaded_python3_provider = 0 @@ -70,13 +70,13 @@ virtualenv for Neovim and hard-code the interpreter path via |g:python3_host_prog| so that the "pynvim" package is not required for each virtualenv. -Example using pyenv: > +Example using pyenv: >bash pyenv install 3.4.4 pyenv virtualenv 3.4.4 py3nvim pyenv activate py3nvim python3 -m pip install pynvim pyenv which python # Note the path -The last command reports the interpreter path, add it to your init.vim: > +The last command reports the interpreter path, add it to your init.vim: >vim let g:python3_host_prog = '/path/to/py3nvim/bin/python' See also: https://github.com/zchee/deoplete-jedi/wiki/Setting-up-Python-for-Neovim @@ -90,7 +90,7 @@ Nvim supports Ruby |remote-plugin|s and the Vim legacy |ruby-vim| interface RUBY QUICKSTART ~ -To use Ruby plugins with Nvim, install the latest "neovim" RubyGem: > +To use Ruby plugins with Nvim, install the latest "neovim" RubyGem: >bash gem install neovim Run |:checkhealth| to see if your system is up-to-date. @@ -98,7 +98,7 @@ Run |:checkhealth| to see if your system is up-to-date. RUBY PROVIDER CONFIGURATION ~ *g:loaded_ruby_provider* -To disable Ruby support: > +To disable Ruby support: >vim let g:loaded_ruby_provider = 0 < *g:ruby_host_prog* @@ -106,10 +106,10 @@ Command to start the Ruby host. By default this is "neovim-ruby-host". With project-local Ruby versions (via tools like RVM or rbenv) setting this can avoid the need to install the "neovim" gem in every project. -To use an absolute path (e.g. to an rbenv installation): > +To use an absolute path (e.g. to an rbenv installation): >vim let g:ruby_host_prog = '~/.rbenv/versions/2.4.1/bin/neovim-ruby-host' -To use the RVM "system" Ruby installation: > +To use the RVM "system" Ruby installation: >vim let g:ruby_host_prog = 'rvm system do neovim-ruby-host' ============================================================================== @@ -125,7 +125,7 @@ Note: Only perl versions from 5.22 onward are supported. PERL QUICKSTART~ -To use perl remote-plugins with Nvim, install the "Neovim::Ext" cpan package: > +To use perl remote-plugins with Nvim, install the "Neovim::Ext" cpan package: >bash cpanm -n Neovim::Ext Run |:checkhealth| to see if your system is up-to-date. @@ -133,12 +133,12 @@ Run |:checkhealth| to see if your system is up-to-date. PERL PROVIDER CONFIGURATION~ *g:loaded_perl_provider* -To disable Perl support: > +To disable Perl support: >vim :let g:loaded_perl_provider = 0 < *g:perl_host_prog* Command to start the Perl executable. Must be set before any -check for has("perl"). > +check for has("perl"). >vim let g:perl_host_prog = '/path/to/perl' < ============================================================================== @@ -150,7 +150,7 @@ https://github.com/neovim/node-client/ NODEJS QUICKSTART~ -To use javascript remote-plugins with Nvim, install the "neovim" npm package: > +To use javascript remote-plugins with Nvim, install the "neovim" npm package: >bash npm install -g neovim Run |:checkhealth| to see if your system is up-to-date. @@ -158,14 +158,14 @@ Run |:checkhealth| to see if your system is up-to-date. NODEJS PROVIDER CONFIGURATION~ *g:loaded_node_provider* -To disable Node.js support: > +To disable Node.js support: >vim :let g:loaded_node_provider = 0 < *g:node_host_prog* Command to start the Node.js host. Setting this makes startup faster. By default, Nvim searches for "neovim-node-host" using "npm root -g", which -can be slow. To avoid this, set g:node_host_prog to the host path: > +can be slow. To avoid this, set g:node_host_prog to the host path: >vim let g:node_host_prog = '/usr/local/bin/neovim-node-host' < ============================================================================== @@ -176,7 +176,7 @@ a |provider| which transparently uses shell commands to communicate with the system clipboard or any other clipboard "backend". To ALWAYS use the clipboard for ALL operations (instead of interacting with -the '+' and/or '*' registers explicitly): > +the "+" and/or "*" registers explicitly): >vim set clipboard+=unnamedplus See 'clipboard' for details and options. @@ -188,17 +188,18 @@ registers. Nvim looks for these clipboard tools, in order of priority: - |g:clipboard| - pbcopy, pbpaste (macOS) - wl-copy, wl-paste (if $WAYLAND_DISPLAY is set) + - waycopy, waypaste (if $WAYLAND_DISPLAY is set) - xclip (if $DISPLAY is set) - xsel (if $DISPLAY is set) - lemonade (for SSH) https://github.com/pocke/lemonade - - doitclient (for SSH) http://www.chiark.greenend.org.uk/~sgtatham/doit/ + - doitclient (for SSH) https://www.chiark.greenend.org.uk/~sgtatham/doit/ - win32yank (Windows) - termux (via termux-clipboard-set, termux-clipboard-set) - tmux (if $TMUX is set) *g:clipboard* To configure a custom clipboard tool, set g:clipboard to a dictionary. -For example this configuration integrates the tmux clipboard: > +For example this configuration integrates the tmux clipboard: >vim let g:clipboard = { \ 'name': 'myClipboard', @@ -218,7 +219,8 @@ the selection until the copy command process dies. When pasting, if the copy process has not died the cached selection is applied. g:clipboard can also use functions (see |lambda|) instead of strings. -For example this configuration uses the g:foo variable as a fake clipboard: > +For example this configuration uses the g:foo variable as a fake clipboard: +>vim let g:clipboard = { \ 'name': 'myClipboard', @@ -236,11 +238,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: +>vim + 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 @@ -266,7 +284,7 @@ many commands. Use the |cmdline-window| if you really want to paste multiple lines to the cmdline. You can implement a custom paste handler by redefining |vim.paste()|. -Example: > +Example: >lua vim.paste = (function(lines, phase) vim.api.nvim_put(lines, 'c', true, true) diff --git a/runtime/doc/quickfix.txt b/runtime/doc/quickfix.txt index dab3bfa280..b1f7c927cc 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 @@ -1259,6 +1259,21 @@ not "b:current_compiler". What the command actually does is the following: For writing a compiler plugin, see |write-compiler-plugin|. +DOTNET *compiler-dotnet* + +The .NET CLI compiler outputs both errors and warnings by default. The output +may be limited to include only errors, by setting the g:dotnet_errors_only +variable to |v:true|. + +The associated project name is included in each error and warning. To suppress +the project name, set the g:dotnet_show_project_file variable to |v:false|. + +Example: limit output to only display errors, and suppress the project name: > + let dotnet_errors_only = v:true + let dotnet_show_project_file = v:false + compiler dotnet +< + GCC *quickfix-gcc* *compiler-gcc* There's one variable you can set for the GCC compiler: @@ -1287,7 +1302,7 @@ PYUNIT COMPILER *compiler-pyunit* This is not actually a compiler, but a unit testing framework for the Python language. It is included into standard Python distribution starting from version 2.0. For older versions, you can get it from -http://pyunit.sourceforge.net. +https://pyunit.sourceforge.net. When you run your tests with the help of the framework, possible errors are parsed by Vim and presented for you in quick-fix mode. @@ -1298,8 +1313,6 @@ Useful values for the 'makeprg' options therefore are: setlocal makeprg=./alltests.py " Run a testsuite setlocal makeprg=python\ %:S " Run a single testcase -Also see http://vim.sourceforge.net/tip_view.php?tip_id=280. - TEX COMPILER *compiler-tex* @@ -1572,8 +1585,9 @@ A call of |:clist| writes them accordingly with their correct filenames: Unlike the other prefixes that all match against whole lines, %P, %Q and %O can be used to match several patterns in the same line. Thus it is possible -to parse even nested files like in the following line: +to parse even nested files like in the following line: > {"file1" {"file2" error1} error2 {"file3" error3 {"file4" error4 error5}}} +< The %O then parses over strings that do not contain any push/pop file name information. See |errorformat-LaTeX| for an extended example. @@ -1823,7 +1837,7 @@ In English, that sed script: it as a "continuation of a multi-line message." *errorformat-ant* -For ant (http://jakarta.apache.org/) the above errorformat has to be modified +For ant (https://jakarta.apache.org/) the above errorformat has to be modified to honour the leading [javac] in front of each javac output line: > :set efm=%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%# @@ -1933,13 +1947,13 @@ by Vim. The default format for the lines displayed in the quickfix window and location list window is: - +> <filename>|<lnum> col <col>|<text> - +< 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 +1979,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..d17df3cd61 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,17 +667,12 @@ 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 'copyindent' 'ci' make 'autoindent' use existing indent structure 'cpoptions' 'cpo' flags for Vi-compatible behavior -'cscopepathcomp' 'cspc' how many components of the path to show -'cscopeprg' 'csprg' command to execute cscope -'cscopequickfix' 'csqf' use quickfix window for cscope results -'cscoperelative' 'csre' Use cscope.out path basename as prefix -'cscopetag' 'cst' use cscope for tag commands -'cscopetagorder' 'csto' determines ":cstag" search order 'cursorbind' 'crb' move cursor in window as it moves in other windows 'cursorcolumn' 'cuc' highlight the screen column of the cursor 'cursorline' 'cul' highlight the screen line of the cursor @@ -676,6 +689,7 @@ Short explanation of each option: *option-list* 'display' 'dy' list of flags for how to display text 'eadirection' 'ead' in which direction 'equalalways' works 'encoding' 'enc' encoding used internally +'endoffile' 'eof' write CTRL-Z at end of the file 'endofline' 'eol' write <EOL> for last line in file 'equalalways' 'ea' windows are automatically made the same size 'equalprg' 'ep' external program to use for "=" command @@ -684,7 +698,7 @@ Short explanation of each option: *option-list* 'errorformat' 'efm' description of the lines in the error file 'eventignore' 'ei' autocommand events that are ignored 'expandtab' 'et' use spaces when <Tab> is inserted -'exrc' 'ex' read .nvimrc and .exrc in the current directory +'exrc' 'ex' read init files in the current directory 'fileencoding' 'fenc' file encoding for multibyte text 'fileencodings' 'fencs' automatically detected character encodings 'fileformat' 'ff' file format used for file I/O @@ -759,6 +773,7 @@ Short explanation of each option: *option-list* 'lines' number of lines in the display 'linespace' 'lsp' number of pixel lines to use between characters 'lisp' automatic indenting for Lisp +'lispoptions' 'lop' changes how Lisp indenting is done 'lispwords' 'lw' words that change how lisp indenting works 'list' show <Tab> and <EOL> 'listchars' 'lcs' characters for displaying in list mode @@ -785,6 +800,7 @@ Short explanation of each option: *option-list* 'mousefocus' 'mousef' keyboard focus follows the mouse 'mousehide' 'mh' hide mouse pointer while typing 'mousemodel' 'mousem' changes meaning of mouse buttons +'mousemoveevent' 'mousemev' report mouse moves with <MouseMove> 'mousescroll' amount to scroll by when scrolling with a mouse 'mouseshape' 'mouses' shape of the mouse pointer in different modes 'mousetime' 'mouset' max time between mouse double-click @@ -801,23 +817,12 @@ 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 'previewwindow' 'pvw' identifies the preview window -'printdevice' 'pdev' name of the printer to be used for :hardcopy -'printencoding' 'penc' encoding to be used for printing -'printexpr' 'pexpr' expression used to print PostScript for :hardcopy -'printfont' 'pfn' name of the font to be used for :hardcopy -'printheader' 'pheader' format of the header used for :hardcopy -'printmbcharset' 'pmbcs' CJK character set to be used for :hardcopy -'printmbfont' 'pmbfn' font names to be used for CJK output of :hardcopy -'printoptions' 'popt' controls the format of :hardcopy output -'pumheight' 'ph' maximum height of the popup menu +'pumheight' 'ph' maximum number of items to show in 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 +833,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 @@ -856,7 +860,8 @@ Short explanation of each option: *option-list* 'shiftwidth' 'sw' number of spaces to use for (auto)indent step 'shortmess' 'shm' list of flags, reduce length of messages 'showbreak' 'sbr' string to use at the start of wrapped lines -'showcmd' 'sc' show (partial) command in status line +'showcmd' 'sc' show (partial) command somewhere +'showcmdloc' 'sloc' where to show (partial) command 'showfulltag' 'sft' show full tag pattern when completing tag 'showmatch' 'sm' briefly jump to matching bracket if insert one 'showmode' 'smd' message on status line to show current mode @@ -875,8 +880,10 @@ 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 +'statuscolumn' 'stc' custom format for the status column 'statusline' 'stl' custom format for the status line 'suffixes' 'su' suffixes that are ignored with multiple match 'suffixesadd' 'sua' suffixes added when searching for a file @@ -889,6 +896,7 @@ Short explanation of each option: *option-list* 'tabstop' 'ts' number of spaces that <Tab> in file uses 'tagbsearch' 'tbs' use binary searching in tags files 'tagcase' 'tc' how to handle case when searching in tags files +'tagfunc' 'tfu' function to get list of tag matches 'taglength' 'tl' number of significant characters for a tag 'tagrelative' 'tr' file names in tag file are relative 'tags' 'tag' list of file names used by the tag command @@ -947,18 +955,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 +993,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 +1019,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 +1066,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 +1087,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 +1120,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 +1157,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 +1177,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 +1198,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 +1236,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 +1268,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 +1314,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 +1336,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 +1363,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 +1376,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/remote.txt b/runtime/doc/remote.txt index 0c1e3438de..4610088ab0 100644 --- a/runtime/doc/remote.txt +++ b/runtime/doc/remote.txt @@ -52,6 +52,10 @@ The following command line arguments are available: *--remote-expr* --remote-expr {expr} Evaluate {expr} in server and print the result on stdout. + *--remote-ui* + --remote-ui Display the UI of the server in the terminal. + Fully interactive: keyboard and mouse input + are forwarded to the server. *--server* --server {addr} Connect to the named pipe or socket at the given address for executing remote commands. diff --git a/runtime/doc/repeat.txt b/runtime/doc/repeat.txt index 508565dea4..1bbd20702b 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 @@ -288,7 +289,7 @@ For writing a Vim script, see chapter 41 of the user manual |usr_41.txt|. how this can be useful. This is normally done automatically during startup, - after loading your .vimrc file. With this command it + after loading your |vimrc| file. With this command it can be done earlier. Packages will be loaded only once. Using @@ -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,22 @@ 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. +To allow for calling into package functionality while parsing your |vimrc|, +|:colorscheme| and |autoload| will both automatically search under 'packpath' +as well in addition to 'runtimepath'. See the documentation for each for +details. -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 +594,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 +611,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 +689,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 searched for autoload files, when +sourcing the plugins. ============================================================================== Debugging scripts *debug-scripts* diff --git a/runtime/doc/rileft.txt b/runtime/doc/rileft.txt index aa11462595..4f68ab562c 100644 --- a/runtime/doc/rileft.txt +++ b/runtime/doc/rileft.txt @@ -12,8 +12,9 @@ These functions were originally created by Avner Lottem: E-mail: alottem@iil.intel.com Phone: +972-4-8307322 +------------------------------------------------------------------------------ Introduction ------------- + Some languages such as Arabic, Farsi, Hebrew (among others) require the ability to display their text from right-to-left. Files in those languages are stored conventionally and the right-to-left requirement is only a @@ -32,8 +33,9 @@ as this kind of support is out of the scope of a simple addition to an existing editor (and it's not sanctioned by Unicode either). +------------------------------------------------------------------------------ Highlights ----------- + o Editing left-to-right files as in the original Vim, no change. o Viewing and editing files in right-to-left windows. File orientation @@ -56,11 +58,11 @@ o Many languages use and require right-to-left support. These languages current supported languages include - |arabic.txt| and |hebrew.txt|. +------------------------------------------------------------------------------ Of Interest... --------------- o Invocations - ----------- + + 'rightleft' ('rl') sets window orientation to right-to-left. + 'delcombine' ('deco'), boolean, if editing UTF-8 encoded languages, allows one to remove a composing character which gets superimposed @@ -69,7 +71,7 @@ o Invocations (such as search) to be utilized in right-to-left orientation as well. o Typing backwards *ins-reverse* - ---------------- + In lieu of using the full-fledged 'rightleft' option, one can opt for reverse insertion. When the 'revins' (reverse insert) option is set, inserting happens backwards. This can be used to type right-to-left @@ -85,15 +87,16 @@ o Typing backwards *ins-reverse* in the status line when reverse Insert mode is active. o Pasting when in a rightleft window - ---------------------------------- + When cutting text with the mouse and pasting it in a rightleft window the text will be reversed, because the characters come from the cut buffer from the left to the right, while inserted in the file from the right to the left. In order to avoid it, toggle 'revins' before pasting. +------------------------------------------------------------------------------ Bugs ----- + o Does not handle CTRL-A and CTRL-X commands (add and subtract) correctly when in rightleft window. diff --git a/runtime/doc/russian.txt b/runtime/doc/russian.txt index a2bc9f3b5e..8d3ed360c8 100644 --- a/runtime/doc/russian.txt +++ b/runtime/doc/russian.txt @@ -45,7 +45,7 @@ If you wish to use messages, help files, menus and other items translated to Russian, you will need to install the RuVim Language Pack, available in different codepages from - http://www.sourceforge.net/projects/ruvim/ + https://www.sourceforge.net/projects/ruvim/ After downloading an archive from RuVim project, unpack it into your $VIMRUNTIME directory. We recommend using UTF-8 archive. diff --git a/runtime/doc/sign.txt b/runtime/doc/sign.txt index a2a5645baa..d09d0f226f 100644 --- a/runtime/doc/sign.txt +++ b/runtime/doc/sign.txt @@ -334,8 +334,10 @@ See |sign_getplaced()| for the equivalent Vim script function. :sign place group=* buffer={nr} List signs in all the groups placed in buffer {nr}. +:sign place List placed signs in the global group in all files. + :sign place group={group} - List placed signs in all sign groups in all the files. + List placed signs with sign group {group} in all files. :sign place group=* List placed signs in all sign groups in all files. @@ -381,15 +383,14 @@ sign_define({list}) icon full path to the bitmap file for the sign. linehl highlight group used for the whole line the sign is placed in. + numhl highlight group used for the line number where + the sign is placed. text text that is displayed when there is no icon or the GUI is not being used. texthl highlight group used for the text item culhl highlight group used for the text item when the cursor is on the same line as the sign and 'cursorline' is enabled. - numhl highlight group used for 'number' column at the - associated line. Overrides |hl-LineNr|, - |hl-CursorLineNr|. If the sign named {name} already exists, then the attributes of the sign are updated. @@ -431,6 +432,8 @@ sign_getdefined([{name}]) *sign_getdefined()* linehl highlight group used for the whole line the sign is placed in; not present if not set. name name of the sign + numhl highlight group used for the line number where + the sign is placed; not present if not set. text text that is displayed when there is no icon or the GUI is not being used. texthl highlight group used for the text item; not @@ -439,9 +442,6 @@ sign_getdefined([{name}]) *sign_getdefined()* the cursor is on the same line as the sign and 'cursorline' is enabled; not present if not set. - numhl highlight group used for 'number' column at the - associated line. Overrides |hl-LineNr|, - |hl-CursorLineNr|; not present if not set. Returns an empty List if there are no signs and when {name} is not found. @@ -606,9 +606,9 @@ sign_placelist({list}) then a new unique identifier is allocated. Otherwise the specified number is used. See |sign-identifier| for more information. - lnum line number in the buffer {buf} where the - sign is to be placed. For the accepted values, - see |line()|. + lnum line number in the buffer where the sign is to + be placed. For the accepted values, see + |line()|. name name of the sign to place. See |sign_define()| for more information. priority priority of the sign. When multiple signs are diff --git a/runtime/doc/spell.txt b/runtime/doc/spell.txt index 23d5905ec3..98a6af1b8b 100644 --- a/runtime/doc/spell.txt +++ b/runtime/doc/spell.txt @@ -482,7 +482,7 @@ You can create a Vim spell file from the .aff and .dic files that Myspell uses. Myspell is used by OpenOffice.org and Mozilla. The OpenOffice .oxt files are zip files which contain the .aff and .dic files. You should be able to find them here: - http://extensions.services.openoffice.org/dictionary + https://extensions.services.openoffice.org/dictionary The older, OpenOffice 2 files may be used if this doesn't work: http://wiki.services.openoffice.org/wiki/Dictionaries You can also use a plain word list. The results are the same, the choice @@ -764,13 +764,13 @@ them before the Vim word list is made. The tools for this can be found in the The format for the affix and word list files is based on what Myspell uses (the spell checker of Mozilla and OpenOffice.org). A description can be found here: - http://lingucomponent.openoffice.org/affix.readme ~ + https://lingucomponent.openoffice.org/affix.readme ~ Note that affixes are case sensitive, this isn't obvious from the description. Vim supports quite a few extras. They are described below |spell-affix-vim|. Attempts have been made to keep this compatible with other spell checkers, so that the same files can often be used. One other project that offers more -than Myspell is Hunspell ( http://hunspell.sf.net ). +than Myspell is Hunspell ( https://hunspell.github.io ). WORD LIST FORMAT *spell-dic-format* @@ -886,7 +886,7 @@ right encoding. *spell-AUTHOR* *spell-EMAIL* *spell-COPYRIGHT* NAME Name of the language VERSION 1.0.1 with fixes - HOME http://www.myhome.eu + HOME https://www.example.com AUTHOR John Doe EMAIL john AT Doe DOT net COPYRIGHT LGPL @@ -992,8 +992,8 @@ Note: even when using "num" or "long" the number of flags available to compounding and prefixes is limited to about 250. -AFFIXES - *spell-PFX* *spell-SFX* +AFFIXES *spell-PFX* *spell-SFX* + The usual PFX (prefix) and SFX (suffix) lines are supported (see the Myspell documentation or the Aspell manual: http://aspell.net/man-html/Affix-Compression.html). @@ -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..179bacdb24 100644 --- a/runtime/doc/starting.txt +++ b/runtime/doc/starting.txt @@ -9,7 +9,7 @@ Starting Vim *starting* Type |gO| to see the table of contents. ============================================================================== -Nvim arguments *vim-arguments* +Nvim arguments *cli-arguments* Most often, Nvim is started to edit a single file with the command: > @@ -31,11 +31,11 @@ filename One or more file names. The first one will be the current To avoid a file name starting with a '-' being interpreted as an option, precede the arglist with "--", e.g.: > nvim -- -filename -< All arguments after the "--" will be interpreted as file names, - no other options or "+command" argument can follow. +< All arguments after "--" are interpreted as file names, no + other options or "+command" arguments 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,15 +143,12 @@ 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] Executes Vimscript or Lua (".lua") [file] after the first file + has been read. See also |:source|. If [file] is not given, + defaults to "Session.vim". 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 "-". - --S Works like "-S Session.vim". Only when used as the last - argument or when another "-" option follows. +< Can be repeated like "-c", subject to the same limit of 10 + "-c" arguments. {file} cannot start with a "-". -L *-L* *-r* -r Recovery mode. Without a file name argument, a list of @@ -195,8 +190,9 @@ argument. -E reads stdin as text (into buffer 1). -es *-es* *-Es* *-s-ex* *silent-mode* --Es Silent mode (no UI), for scripting. Unrelated to |-s|. - Disables most prompts, messages, warnings and errors. +-Es Script mode, aka "silent mode", aka "batch mode". No UI, + disables most prompts and messages. Unrelated to |-s|. + See also |-S| to run script files. -es reads/executes stdin as Ex commands. > printf "put ='foo'\n%%print\n" | nvim -es @@ -205,18 +201,44 @@ 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|). +< User |config| is skipped unless |-u| was given. Swap file is skipped (like |-n|). User |shada| is loaded (unless "-i NONE" is given). + *-l* +-l {script} [args] + Executes Lua {script} non-interactively (no UI) with optional + [args] after processing any preceding Nvim |cli-arguments|, + then exits. Exits 1 on Lua error. See |-S| to run multiple Lua + scripts without args, with a UI. + *lua-args* + All [args] are treated as {script} arguments and stored in the + Lua `_G.arg` global table, thus "-l" ends processing of Nvim + arguments. The {script} name is stored at `_G.arg[0]`. + + Sets 'verbose' to 1 (like "-V1"), so Lua `print()` writes to + output. + + Arguments before "-l" are processed before executing {script}. + This example quits before executing "foo.lua": > + nvim +q -l foo.lua +< This loads Lua module "bar" before executing "foo.lua": > + nvim +"lua require('bar')" -l foo.lua +< + Skips user |config| unless |-u| was given. + Disables plugins unless 'loadplugins' was set. + Disables |shada| unless |-i| was given. + Disables swapfile (like |-n|). + *-b* -b Binary mode. File I/O will only recognize <NL> to separate lines. The 'expandtab' option will be reset. The 'textwidth' @@ -224,9 +246,6 @@ argument. is set. This is done after reading the |vimrc| but before reading any file in the arglist. See also |edit-binary|. - *-l* --l Lisp mode. Sets the 'lisp' and 'showmatch' options on. - *-A* -A Arabic mode. Sets the 'arabic' option on. @@ -241,10 +260,10 @@ argument. Example: > nvim -V8 --V[N]{filename} - Like -V and set 'verbosefile' to {filename}. Messages are not - displayed; instead they are written to the file {filename}. - {filename} must not start with a digit. +-V[N]{file} + Like -V and sets 'verbosefile' to {file} (must not start with + a digit). Messages are not displayed, instead they are + written to {file}. Example: > nvim -V20vimlog < @@ -403,18 +422,20 @@ accordingly, proceeding as follows: The |-V| argument can be used to display or log what happens next, useful for debugging the initializations. -3. Wait for UI to connect. +3. Start a server (unless |--listen| was given) and set |v:servername|. + +4. Wait for UI to connect. Nvim started with |--embed| waits for the UI to connect before proceeding to load user configuration. -4. Setup |default-mappings| and |default-autocmds|. Create |popup-menu|. +5. Setup |default-mappings| and |default-autocmds|. Create |popup-menu|. -5. Enable filetype and indent plugins. +6. Enable filetype and indent plugins. This does the same as the command: > :runtime! ftplugin.vim indent.vim < Skipped if the "-u NONE" command line argument was given. -6. Load user config (execute Ex commands from files, environment, …). +7. Load user config (execute Ex commands from files, environment, …). $VIMINIT environment variable is read as one Ex command line (separate multiple commands with '|' or <NL>). *config* *init.vim* *init.lua* *vimrc* *exrc* @@ -445,32 +466,33 @@ 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. c. If the 'exrc' option is on (which is NOT the default), the current - directory is searched for two files. The first that exists is used, - the others are ignored. - - The file ".nvimrc" - - The file ".exrc" + directory is searched for the following files, in order of precedence: + - ".nvim.lua" + - ".nvimrc" + - ".exrc" + The first that exists is used, the others are ignored. -7. Enable filetype detection. +8. Enable filetype detection. This does the same as the command: > - :runtime! filetype.lua filetype.vim + :runtime! filetype.lua < Skipped if ":filetype off" was called or if the "-u NONE" command line argument was given. -8. Enable syntax highlighting. +9. Enable syntax highlighting. This does the same as the command: > :runtime! syntax/syntax.vim < Skipped if ":syntax off" was called or if the "-u NONE" command line argument was given. -9. Load the plugin scripts. *load-plugins* +10. Load the plugin scripts. *load-plugins* This does the same as the command: > :runtime! plugin/**/*.vim :runtime! plugin/**/*.lua @@ -482,13 +504,13 @@ accordingly, proceeding as follows: However, directories in 'runtimepath' ending in "after" are skipped here and only loaded after packages, see below. Loading plugins won't be done when: - - The 'loadplugins' option was reset in a vimrc file. + - The |'loadplugins'| option was reset in a vimrc file. - The |--noplugin| command line argument is used. - The |--clean| command line argument is used. - The "-u NONE" command line argument is used |-u|. - Note that using "-c 'set noloadplugins'" doesn't work, because the + Note that using `-c 'set noloadplugins'` doesn't work, because the commands from the command line have not been executed yet. You can - use "--cmd 'set noloadplugins'" or "--cmd 'set loadplugins'" |--cmd|. + use `--cmd 'set noloadplugins'` or `--cmd 'set loadplugins'` |--cmd|. Packages are loaded. These are plugins, as above, but found in the "start" directory of each entry in 'packpath'. Every plugin directory @@ -500,21 +522,21 @@ accordingly, proceeding as follows: if packages have been found, but that should not add a directory ending in "after". -10. Set 'shellpipe' and 'shellredir' +11. Set 'shellpipe' and 'shellredir' The 'shellpipe' and 'shellredir' options are set according to the value of the 'shell' option, unless they have been set before. This means that Nvim will figure out the values of 'shellpipe' and 'shellredir' for you, unless you have set them yourself. -11. Set 'updatecount' to zero, if "-n" command argument used +12. Set 'updatecount' to zero, if "-n" command argument used -12. Set binary options if the |-b| flag was given. +13. Set binary options if the |-b| flag was given. -13. Read the |shada-file|. +14. Read the |shada-file|. -14. Read the quickfix file if the |-q| flag was given, or exit on failure. +15. Read the quickfix file if the |-q| flag was given, or exit on failure. -15. Open all windows +16. Open all windows When the |-o| flag was given, windows will be opened (but not displayed yet). When the |-p| flag was given, tab pages will be created (but not @@ -524,7 +546,7 @@ accordingly, proceeding as follows: Buffers for all windows will be loaded, without triggering |BufAdd| autocommands. -16. Execute startup commands +17. Execute startup commands If a |-t| flag was given, the tag is jumped to. Commands given with |-c| and |+cmd| are executed. The starting flag is reset, has("vim_starting") will now return zero. @@ -1184,7 +1206,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 +1237,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 +1308,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 +1318,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 +1381,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/support.txt b/runtime/doc/support.txt new file mode 100644 index 0000000000..481959d8f1 --- /dev/null +++ b/runtime/doc/support.txt @@ -0,0 +1,52 @@ +*support.txt* Nvim + + + NVIM REFERENCE MANUAL + + +Support *support* + + Type |gO| to see the table of contents. + +============================================================================== +Supported platforms *supported-platforms* + +`System` `Tier` `Versions` `Tested versions` +Linux 1 >= 2.6.32, glibc >= 2.12 Ubuntu 22.04 +macOS (Intel) 1 >= 10.15 macOS 12 +Windows 64-bit 1 >= 8 Windows Server 2019 +FreeBSD 1 >= 10 FreeBSD 13 +macOS (M1) 2 >= 10.15 +OpenBSD 2 >= 7 +MinGW 2 MinGW-w64 + +Support types ~ + +* Tier 1: Officially supported and tested with CI. Any contributed patch + MUST NOT break such systems. + +* Tier 2: Officially supported, but not necessarily tested with CI. These + systems are maintained to the best of our ability, without being a top + priority. + +* Tier 3: Not tested and no guarantees, but may work. + +Adding support for a new platform ~ + +IMPORTANT: Before attempting to add support for a new platform please open +an issue about it for discussion. + + +============================================================================== +Common + +Some common notes when adding support for new platforms: + +Cmake is the only supported build system. The platform must be buildable with cmake. + +All functionality related to the new platform must be implemented in its own +file inside `src/nvim/os` unless it's already done in a common file, in which +case adding an `#ifdef` is fine. + + + vim:tw=78:ts=8:et:ft=help:norl: diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index b74611633f..bd5a4f1926 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. @@ -464,7 +464,7 @@ Force to omit the line numbers: > Go back to the default to use 'number' by deleting the variable: > :unlet g:html_number_lines < - *g:html_line_ids* + *g:html_line_ids* Default: 1 if |g:html_number_lines| is set, 0 otherwise. When 1, adds an HTML id attribute to each line number, or to an empty <span> inserted for that purpose if no line numbers are shown. This ID attribute @@ -656,6 +656,22 @@ the rendered page generated by 2html.vim. > :let g:html_no_pre = 1 < + *g:html_no_doc* +Default: 0. +When 1 it doesn't generate a full HTML document with a DOCTYPE, <head>, +<body>, etc. If |g:html_use_css| is enabled (the default) you'll have to +define the CSS manually. The |g:html_dynamic_folds| and |g:html_line_ids| +settings (off by default) also insert some JavaScript. + + + *g:html_no_links* +Default: 0. +Don't generate <a> tags for text that looks like an URL. + + *g:html_no_modeline* +Default: 0. +Don't generate a modeline disabling folding. + *g:html_expand_tabs* Default: 0 if 'tabstop' is 8, 'expandtab' is 0, 'vartabstop' is not in use, and no fold column or line numbers occur in the generated HTML; @@ -687,13 +703,13 @@ Automatic detection works for the encodings mentioned specifically by name in |encoding-names|, but TOhtml will only automatically use those encodings with wide browser support. However, you can override this to support specific encodings that may not be automatically detected by default (see options -below). See http://www.iana.org/assignments/character-sets for the IANA names. +below). See https://www.iana.org/assignments/character-sets for the IANA names. Note: By default all Unicode encodings are converted to UTF-8 with no BOM in the generated HTML, as recommended by W3C: - http://www.w3.org/International/questions/qa-choosing-encodings - http://www.w3.org/International/questions/qa-byte-order-mark + https://www.w3.org/International/questions/qa-choosing-encodings + https://www.w3.org/International/questions/qa-byte-order-mark *g:html_use_encoding* Default: none, uses IANA name for current 'fileencoding' as above. @@ -832,7 +848,7 @@ files are included: asm68k Motorola 680x0 assembly asmh8300 Hitachi H-8300 version of GNU assembly ia64 Intel Itanium 64 - fasm Flat assembly (http://flatassembler.net) + fasm Flat assembly (https://flatassembler.net) masm Microsoft assembly (probably works for any 80x86) nasm Netwide assembly tasm Turbo Assembly (with opcodes 80x86 up to Pentium, and @@ -1393,9 +1409,9 @@ Two syntax highlighting files exist for Euphoria. One for Euphoria version 3.1.1, which is the default syntax highlighting file, and one for Euphoria version 4.0.5 or later. -Euphoria version 3.1.1 (http://www.rapideuphoria.com/) is still necessary +Euphoria version 3.1.1 (https://www.rapideuphoria.com/) is still necessary for developing applications for the DOS platform, which Euphoria version 4 -(http://www.openeuphoria.org/) does not support. +(https://www.openeuphoria.org/) does not support. The following file extensions are auto-detected as Euphoria file type: @@ -1452,7 +1468,7 @@ Elixir. FLEXWIKI *flexwiki.vim* *ft-flexwiki-syntax* -FlexWiki is an ASP.NET-based wiki package available at http://www.flexwiki.com +FlexWiki is an ASP.NET-based wiki package available at https://www.flexwiki.com NOTE: This site currently doesn't work, on Wikipedia is mentioned that development stopped in 2009. @@ -1808,7 +1824,7 @@ are read during initialization) > :let html_my_rendering=1 If you'd like to see an example download mysyntax.vim at -http://www.fleiner.com/vim/download.html +https://www.fleiner.com/vim/download.html You can also disable this rendering by adding the following line to your vimrc file: > @@ -1838,6 +1854,16 @@ following two lines to the syntax coloring file for that language Now you just need to make sure that you add all regions that contain the preprocessor language to the cluster htmlPreproc. + *html-folding* +The HTML syntax file provides syntax |folding| (see |:syn-fold|) between start +and end tags. This can be turned on by > + + :let g:html_syntax_folding = 1 + :set foldmethod=syntax + +Note: Syntax folding might slow down syntax highlighting significantly, +especially for large files. + HTML/OS (by Aestiva) *htmlos.vim* *ft-htmlos-syntax* @@ -1936,7 +1962,7 @@ highlight them use: > :let java_highlight_java_lang_ids=1 You can also highlight identifiers of most standard Java packages if you -download the javaid.vim script at http://www.fleiner.com/vim/download.html. +download the javaid.vim script at https://www.fleiner.com/vim/download.html. If you prefer to only highlight identifiers of a certain package, say java.io use the following: > :let java_highlight_java_io=1 @@ -2057,7 +2083,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 +2391,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. ;) @@ -2449,7 +2475,7 @@ from the rest of the name (like 'PkgName::' in '$PkgName::VarName'): > (In Vim 6.x it was the other way around: "perl_want_scope_in_variables" enabled it.) -If you do not want complex things like '@{${"foo"}}' to be parsed: > +If you do not want complex things like `@{${"foo"}}` to be parsed: > :let perl_no_extended_vars = 1 @@ -2897,7 +2923,7 @@ Default folding is rather detailed, i.e., small syntax units like "if", "do", You can set "ruby_foldable_groups" to restrict which groups are foldable: > - :let ruby_foldable_groups = 'if case %' + :let ruby_foldable_groups = 'if case %' < The value is a space-separated list of keywords: @@ -2905,22 +2931,22 @@ The value is a space-separated list of keywords: -------- ------------------------------------- ~ ALL Most block syntax (default) NONE Nothing - if "if" or "unless" block + if "if" or "unless" block def "def" block class "class" block module "module" block - do "do" block + do "do" block begin "begin" block case "case" block for "for", "while", "until" loops - { Curly bracket block or hash literal - [ Array literal - % Literal with "%" notation, e.g.: %w(STRING), %!STRING! - / Regexp + { Curly bracket block or hash literal + [ Array literal + % Literal with "%" notation, e.g.: %w(STRING), %!STRING! + / Regexp string String and shell command output (surrounded by ', ", `) - : Symbol - # Multiline comment - << Here documents + : Symbol + # Multiline comment + << Here documents __END__ Source code after "__END__" directive *ruby_no_expensive* @@ -2986,16 +3012,25 @@ satisfied with it for my own projects. SED *sed.vim* *ft-sed-syntax* To make tabs stand out from regular blanks (accomplished by using Todo -highlighting on the tabs), define "highlight_sedtabs" by putting > - - :let highlight_sedtabs = 1 +highlighting on the tabs), define "g:sed_highlight_tabs" by putting > + :let g:sed_highlight_tabs = 1 +< in the vimrc file. (This special highlighting only applies for tabs inside search patterns, replacement texts, addresses or text included by an Append/Change/Insert command.) If you enable this option, it is also a good idea to set the tab width to one character; by doing that, you can easily count the number of tabs in a string. +GNU sed allows comments after text on the same line. BSD sed only allows +comments where "#" is the first character of the line. To enforce BSD-style +comments, i.e. mark end-of-line comments as errors, use: > + + :let g:sed_dialect = "bsd" +< +Note that there are other differences between GNU sed and BSD sed which are +not (yet) affected by this setting. + Bugs: The transform command (y) is treated exactly like the substitute @@ -3118,7 +3153,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: > @@ -3353,13 +3388,11 @@ of specialized LaTeX commands, syntax, and fonts. If you're using such a package you'll often wish that the distributed syntax/tex.vim would support it. However, clearly this is impractical. So please consider using the techniques in |mysyntaxfile-add| to extend or modify the highlighting provided -by syntax/tex.vim. Please consider uploading any extensions that you write, -which typically would go in $HOME/after/syntax/tex/[pkgname].vim, to -http://vim.sf.net/. +by syntax/tex.vim. I've included some support for various popular packages on my website: > - http://www.drchip.org/astronaut/vim/index.html#LATEXPKGS + https://www.drchip.org/astronaut/vim/index.html#LATEXPKGS < The syntax files there go into your .../after/syntax/tex/ directory. @@ -3538,6 +3571,14 @@ highlighting is to put the following line in your |vimrc|: > < +WDL *wdl.vim* *wdl-syntax* + +The Workflow Description Language is a way to specify data processing workflows +with a human-readable and writeable syntax. This is used a lot in +bioinformatics. More info on the spec can be found here: +https://github.com/openwdl/wdl + + XF86CONFIG *xf86conf.vim* *ft-xf86conf-syntax* The syntax of XF86Config file differs in XFree86 v3.x and v4.x. Both @@ -3690,12 +3731,13 @@ DEFINING CASE *:syn-case* *E390* items until the next ":syntax case" command are affected. :sy[ntax] case - Show either "syntax case match" or "syntax case ignore" (translated). + Show either "syntax case match" or "syntax case ignore". DEFINING FOLDLEVEL *:syn-foldlevel* -:sy[ntax] foldlevel [start | minimum] +:sy[ntax] foldlevel start +:sy[ntax] foldlevel minimum This defines how the foldlevel of a line is computed when using foldmethod=syntax (see |fold-syntax| and |:syn-fold|): @@ -3708,11 +3750,14 @@ DEFINING FOLDLEVEL *:syn-foldlevel* may close and open horizontally within a line. :sy[ntax] foldlevel - Show either "syntax foldlevel start" or "syntax foldlevel minimum". + Show the current foldlevel method, either "syntax foldlevel start" or + "syntax foldlevel minimum". SPELL CHECKING *:syn-spell* -:sy[ntax] spell [toplevel | notoplevel | default] +:sy[ntax] spell toplevel +:sy[ntax] spell notoplevel +:sy[ntax] spell default This defines where spell checking is to be done for text that is not in a syntax item: @@ -3727,8 +3772,8 @@ SPELL CHECKING *:syn-spell* To activate spell checking the 'spell' option must be set. :sy[ntax] spell - Show either "syntax spell toplevel", "syntax spell notoplevel" or - "syntax spell default" (translated). + Show the current syntax spell checking method, either "syntax spell + toplevel", "syntax spell notoplevel" or "syntax spell default". SYNTAX ISKEYWORD SETTING *:syn-iskeyword* @@ -3739,7 +3784,7 @@ SYNTAX ISKEYWORD SETTING *:syn-iskeyword* clear: Syntax specific iskeyword setting is disabled and the buffer-local 'iskeyword' setting is used. - {option} Set the syntax 'iskeyword' option to a new value. + {option} Set the syntax 'iskeyword' option to a new value. Example: > :syntax iskeyword @,48-57,192-255,$,_ @@ -4326,7 +4371,7 @@ IMPLICIT CONCEAL *:syn-conceal-implicit* given explicitly. :sy[ntax] conceal - Show either "syntax conceal on" or "syntax conceal off" (translated). + Show either "syntax conceal on" or "syntax conceal off". ============================================================================== 8. Syntax patterns *:syn-pattern* *E401* *E402* @@ -4806,7 +4851,7 @@ Note that the ":syntax" command can be abbreviated to ":sy", although ":syn" is mostly used, because it looks better. ============================================================================== -12. Highlight command *:highlight* *:hi* *E28* *E411* *E415* +13. Highlight command *:highlight* *:hi* *E28* *E411* *E415* There are two types of highlight groups: - The built-in |highlight-groups|. @@ -4838,7 +4883,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 +4891,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 @@ -4857,7 +4902,7 @@ in their own color. *highlight-clear* *:hi-clear* :hi[ghlight] clear Reset all highlighting to the defaults. Removes all - highlighting for groups added by the user! + highlighting for groups added by the user. Uses the current value of 'background' to decide which default colors to use. If there was a default link, restore it. |:hi-link| @@ -4913,7 +4958,8 @@ the same syntax file on all UIs. *bold* *underline* *undercurl* *underdouble* *underdotted* *underdashed* *inverse* *italic* - *standout* *nocombine* *strikethrough* + *standout* *strikethrough* *altfont* + *nocombine* cterm={attr-list} *attr-list* *highlight-cterm* *E418* attr-list is a comma-separated list (without spaces) of the following items (in any order): @@ -4928,6 +4974,7 @@ cterm={attr-list} *attr-list* *highlight-cterm* *E418* inverse same as reverse italic standout + altfont nocombine override attributes instead of combining them NONE no attributes used (used to reset it) @@ -4935,7 +4982,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 +5003,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 @@ -4997,7 +5044,7 @@ ctermbg={color-nr} *highlight-ctermbg* a number instead of a color name. Note that for 16 color ansi style terminals (including xterms), the - numbers in the NR-8 column is used. Here '*' means 'add 8' so that + numbers in the NR-8 column is used. Here "*" means "add 8" so that Blue is 12, DarkGray is 8 etc. Note that for some color terminals these names may result in the wrong @@ -5016,7 +5063,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 +5111,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. @@ -5099,7 +5146,7 @@ guisp={color-name} *highlight-guisp* "gg" is the Green value "bb" is the Blue value All values are hexadecimal, range from "00" to "ff". Examples: > - :highlight Comment guifg=#11f0c3 guibg=#ff00ff + :highlight Comment guifg=#11f0c3 guibg=#ff00ff < blend={integer} *highlight-blend* Override the blend level for a highlight group within the popupmenu @@ -5123,7 +5170,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* @@ -5174,10 +5221,10 @@ LineNrBelow Line number for when the 'relativenumber' *hl-CursorLineNr* CursorLineNr Like LineNr when 'cursorline' is set and 'cursorlineopt' contains "number" or is "both", for the cursor line. - *hl-CursorLineSign* -CursorLineSign Like SignColumn when 'cursorline' is set for the cursor line. *hl-CursorLineFold* CursorLineFold Like FoldColumn when 'cursorline' is set for the cursor line. + *hl-CursorLineSign* +CursorLineSign Like SignColumn when 'cursorline' is set for the cursor line. *hl-MatchParen* MatchParen Character under the cursor or just before it, if it is a paired bracket, and its match. |pi_paren.txt| @@ -5187,7 +5234,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* @@ -5288,7 +5335,7 @@ Tooltip Current font, background and foreground of the tooltips. Applicable highlight arguments: font, guibg, guifg. ============================================================================== -13. Linking groups *:hi-link* *:highlight-link* *E412* *E413* +14. Linking groups *:hi-link* *:highlight-link* *E412* *E413* When you want to use the same highlighting for several syntax groups, you can do this more easily by linking the groups into one common highlight @@ -5397,8 +5444,7 @@ WARNING: The longer the tags file, the slower this will be, and the more memory Vim will consume. Only highlighting typedefs, unions and structs can be done too. For this you -must use Universal Ctags (found at https://ctags.io) or Exuberant ctags (found -at http://ctags.sf.net). +must use Universal Ctags (https://ctags.io) or Exuberant ctags. Put these lines in your Makefile: @@ -5448,7 +5494,7 @@ is loaded into that window or the file is reloaded. When splitting the window, the new window will use the original syntax. ============================================================================== -17. Color xterms *xterm-color* *color-xterm* +18. Color xterms *xterm-color* *color-xterm* *colortest.vim* To test your color setup, a file has been included in the Vim distribution. @@ -5458,7 +5504,7 @@ To use it, execute this command: > Nvim uses 256-color and |true-color| terminal capabilities wherever possible. ============================================================================== -18. When syntax is slow *:syntime* +19. When syntax is slow *:syntime* This is aimed at authors of a syntax file. 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..0f785dd1eb 100644 --- a/runtime/doc/tagsrch.txt +++ b/runtime/doc/tagsrch.txt @@ -59,9 +59,9 @@ CTRL-] Jump to the definition of the keyword under the CTRL-] is the default telnet escape key. When you type CTRL-] to jump to a tag, you will get the telnet prompt instead. Most versions of telnet allow changing or disabling the default escape key. See the telnet man page. You -can 'telnet -E {Hostname}' to disable the escape character, or 'telnet -e -{EscapeCharacter} {Hostname}' to specify another escape character. If -possible, try to use "ssh" instead of "telnet" to avoid this problem. +can `telnet -E {Hostname}` to disable the escape character, or +`telnet -e {EscapeCharacter} {Hostname}` to specify another escape character. +If possible, try to use "ssh" instead of "telnet" to avoid this problem. *tag-priority* When there are multiple matches for a tag, this priority is used: @@ -404,7 +404,7 @@ is added to the command and on the 'autowrite' option: tag in file autowrite ~ current file changed ! option action ~ ------------------------------------------------------------------------------ + --------------------------------------------------------------------------- yes x x x goto tag no no x x read other file, goto tag no yes yes x abandon current file, read other file, goto @@ -412,7 +412,7 @@ current file changed ! option action ~ no yes no on write current file, read other file, goto tag no yes no off fail ------------------------------------------------------------------------------ + --------------------------------------------------------------------------- - If the tag is in the current file, the command will always work. - If the tag is in another file and the current file was not changed, the @@ -514,18 +514,13 @@ ctags As found on most Unix systems. Only supports C. Only universal ctags A maintained version of ctags based on exuberant ctags. See https://ctags.io. *Exuberant_ctags* -exuberant ctags This is a very good one. It works for C, C++, Java, - Fortran, Eiffel and others. It can generate tags for - many items. See http://ctags.sourceforge.net. - No new version since 2009. +exuberant ctags Works for C, C++, Java, Fortran, Eiffel and others. + See https://ctags.sourceforge.net. No new version + since 2009. JTags For Java, in Java. It can be found at - http://www.fleiner.com/jtags/. + https://www.fleiner.com/jtags/. ptags.py For Python, in Python. Found in your Python source directory at Tools/scripts/ptags.py. -ptags For Perl, in Perl. It can be found at - http://www.eleves.ens.fr:8080/home/nthiery/Tags/. -gnatxref For Ada. See http://www.gnuada.org/. gnatxref is - part of the gnat package. The lines in the tags file must have one of these two formats: @@ -566,8 +561,8 @@ ctags). with Vi, it ignores the following fields. Example: APP file /^static int APP;$/;" v When {tagaddress} is not a line number or search pattern, then - {term} must be |;". Here the bar ends the command (excluding - the bar) and ;" is used to have Vi ignore the rest of the + {term} must be `|;"`. Here the bar ends the command (excluding + the bar) and `;"` is used to have Vi ignore the rest of the line. Example: APP file.c call cursor(3, 4)|;" v @@ -629,8 +624,7 @@ If the command is a normal search command (it starts and ends with "/" or "?"), some special handling is done: - Searching starts on line 1 of the file. The direction of the search is forward for "/", backward for "?". - Note that 'wrapscan' does not matter, the whole file is always searched. (Vi - does use 'wrapscan', which caused tags sometimes not be found.) + Note that 'wrapscan' does not matter, the whole file is always searched. - If the search fails, another try is done ignoring case. If that fails too, a search is done for: "^tagname[ \t]*(" @@ -834,10 +828,10 @@ CTRL-W d Open a new window, with the cursor on the first (default: whole file). See |:search-args| for [/] and [!]. - *:che* *:chec* *:check* *:checkpath* -:che[ckpath] List all the included files that could not be found. + *:checkp* *:checkpath* +:checkp[ath] List all the included files that could not be found. -:che[ckpath]! List all the included files. +:checkp[ath]! List all the included files. *:search-args* Common arguments for the commands above: @@ -854,9 +848,9 @@ Common arguments for the commands above: a comment (even though syntax highlighting does recognize it). Note: Since a macro definition mostly doesn't look like a comment, the [!] makes no difference for ":dlist", ":dsearch" and ":djump". -[/] A pattern can be surrounded by '/'. Without '/' only whole words are - matched, using the pattern "\<pattern\>". Only after the second '/' a - next command can be appended with '|'. Example: > +[/] A pattern can be surrounded by "/". Without "/" only whole words are + matched, using the pattern "\<pattern\>". Only after the second "/" a + next command can be appended with "|". Example: > :isearch /string/ | echo "the last one" < For a ":djump", ":dsplit", ":dlist" and ":dsearch" command the pattern is used as a literal string, not as a search pattern. @@ -870,13 +864,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 @@ -912,6 +908,8 @@ If the function returns |v:null| instead of a List, a standard tag lookup will be performed instead. It is not allowed to change the tagstack from inside 'tagfunc'. *E986* +It is not allowed to close a window or change window from inside 'tagfunc'. +*E1299* The following is a hypothetical example of a function used for 'tagfunc'. It uses the output of |taglist()| to generate the result: a list of tags in the diff --git a/runtime/doc/term.txt b/runtime/doc/term.txt index cd6798a5de..847b4b6112 100644 --- a/runtime/doc/term.txt +++ b/runtime/doc/term.txt @@ -29,7 +29,7 @@ whole. Building your own terminfo is usually as simple as running this as a non-superuser: > - curl -LO http://invisible-island.net/datafiles/current/terminfo.src.gz + curl -LO https://invisible-island.net/datafiles/current/terminfo.src.gz gunzip terminfo.src.gz tic terminfo.src < @@ -76,7 +76,7 @@ supplying an external one with entries for the terminal type. Settings depending on terminal *term-dependent-settings* If you want to set terminal-dependent options or mappings, you can do this in -your init.vim. Example: > +your init.vim. Example: >vim if $TERM =~ '^\(rxvt\|screen\|interix\|putty\)\(-.*\)\?$' set notermguicolors @@ -222,9 +222,9 @@ are not in terminfo you must add them by setting "terminal-overrides" in ~/.tmux.conf . See the tmux(1) manual page for the details of how and what to do in the tmux -configuration file. It will look something like: > +configuration file. It will look something like: >bash set -ga terminal-overrides '*:Ss=\E[%p1%d q:Se=\E[ q' -<or (alas!) for Konsole 18.07.70 or older, something more complex like: > +<or (alas!) for Konsole 18.07.70 or older, something more complex like: >bash set -ga terminal-overrides 'xterm*:\E]50;CursorShape=%?%p1%{3}%<%t%{0}%e%{1}%;%d\007' < ============================================================================== @@ -262,7 +262,7 @@ See the "Options" chapter |options|. If you are using a color terminal that is slow when displaying lines beyond the end of a buffer, this is because Nvim is drawing the whitespace twice, in -two sets of colours and attributes. To prevent this, use this command: > +two sets of colours and attributes. To prevent this, use this command: >vim hi NonText cterm=NONE ctermfg=NONE This draws the spaces with the default colours and attributes, which allows the second pass of drawing to be optimized away. Note: Although in theory the @@ -372,7 +372,7 @@ that has a match selects until that match (like using "v%"). If the match is an #if/#else/#endif block, the selection becomes linewise. For MS-Windows and xterm the time for double clicking can be set with the 'mousetime' option. For the other systems this time is defined outside of Vim. -An example, for using a double click to jump to the tag under the cursor: > +An example, for using a double click to jump to the tag under the cursor: >vim :map <2-LeftMouse> :exe "tag " .. expand("<cword>")<CR> Dragging the mouse with a double click (button-down, button-up, button-down @@ -380,6 +380,8 @@ and then drag) will result in whole words to be selected. This continues until the button is released, at which point the selection is per character again. +For scrolling with the mouse see |scroll-mouse-wheel|. + In Insert mode, when a selection is started, Vim goes into Normal mode temporarily. When Visual or Select mode ends, it returns to Insert mode. This is like using CTRL-O in Insert mode. Select mode is used when the @@ -408,23 +410,23 @@ The X1 and X2 buttons refer to the extra buttons found on some mice. The 'Microsoft Explorer' mouse has these buttons available to the right thumb. Currently X1 and X2 only work on Win32 and X11 environments. -Examples: > +Examples: >vim :noremap <MiddleMouse> <LeftMouse><MiddleMouse> Paste at the position of the middle mouse button click (otherwise the paste -would be done at the cursor position). > +would be done at the cursor position). >vim :noremap <LeftRelease> <LeftRelease>y Immediately yank the selection, when using Visual mode. Note the use of ":noremap" instead of "map" to avoid a recursive mapping. -> +>vim :map <X1Mouse> <C-O> :map <X2Mouse> <C-I> Map the X1 and X2 buttons to go forwards and backwards in the jump list, see |CTRL-O| and |CTRL-I|. *mouse-swap-buttons* -To swap the meaning of the left and right mouse buttons: > +To swap the meaning of the left and right mouse buttons: >vim :noremap <LeftMouse> <RightMouse> :noremap <LeftDrag> <RightDrag> :noremap <LeftRelease> <RightRelease> diff --git a/runtime/doc/testing.txt b/runtime/doc/testing.txt index 4e4a908d0f..ef5e179c86 100644 --- a/runtime/doc/testing.txt +++ b/runtime/doc/testing.txt @@ -20,17 +20,11 @@ and for testing plugins. Vim can be tested after building it, usually with "make test". The tests are located in the directory "src/testdir". -There are several types of tests added over time: - test33.in oldest, don't add any of these - test_something.in old style tests - test_something.vim new style tests - *new-style-testing* -New tests should be added as new style tests. These use functions such as -|assert_equal()| to keep the test commands and the expected result in one -place. - *old-style-testing* -In some cases an old style test needs to be used. +New tests should be added as new style tests. The test scripts are named +test_<feature>.vim (replace <feature> with the feature under test). These use +functions such as |assert_equal()| to keep the test commands and the expected +result in one place. Find more information in the file src/testdir/README.txt. @@ -98,18 +92,46 @@ assert_exception({error} [, {msg}]) *assert_exception()* catch call assert_exception('E492:') endtry - -assert_fails({cmd} [, {error} [, {msg}]]) *assert_fails()* +< + *assert_fails()* +assert_fails({cmd} [, {error} [, {msg} [, {lnum} [, {context}]]]]) Run {cmd} and add an error message to |v:errors| if it does - NOT produce an error. Also see |assert-return|. - When {error} is given it must match in |v:errmsg|. + NOT produce an error or when {error} is not found in the + error message. Also see |assert-return|. + + When {error} is a string it must be found literally in the + first reported error. Most often this will be the error code, + including the colon, e.g. "E123:". > + assert_fails('bad cmd', 'E987:') +< + When {error} is a |List| with one or two strings, these are + used as patterns. The first pattern is matched against the + first reported error: > + assert_fails('cmd', ['E987:.*expected bool']) +< The second pattern, if present, is matched against the last + reported error. To only match the last error use an empty + string for the first error: > + assert_fails('cmd', ['', 'E987:']) +< + If {msg} is empty then it is not used. Do this to get the + default message when passing the {lnum} argument. + + When {lnum} is present and not negative, and the {error} + argument is present and matches, then this is compared with + the line number at which the error was reported. That can be + the line number in a function or in a script. + + When {context} is present it is used as a pattern and matched + against the context (script name or function name) where + {lnum} is located in. + Note that beeping is not considered an error, and some failing commands only beep. Use |assert_beeps()| for those. Can also be used as a |method|: > GetCmd()->assert_fails('E99:') -assert_false({actual} [, {msg}]) *assert_false()* +assert_false({actual} [, {msg}]) *assert_false()* When {actual} is not false an error message is added to |v:errors|, like with |assert_equal()|. Also see |assert-return|. @@ -134,7 +156,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/tips.txt b/runtime/doc/tips.txt index d913b53c6b..5d5e89da77 100644 --- a/runtime/doc/tips.txt +++ b/runtime/doc/tips.txt @@ -8,7 +8,7 @@ Tips and ideas for using Vim *tips* These are just a few that we thought would be helpful for many users. You can find many more tips on the wiki. The URL can be found on -http://www.vim.org +https://www.vim.org Don't forget to browse the user manual, it also contains lots of useful tips |usr_toc.txt|. @@ -297,7 +297,7 @@ be able to give comments to the parts of the mapping. > (<> notation |<>|. Note that this is all typed literally. ^W is "^" "W", not CTRL-W.) -Note that the last comment starts with |", because the ":execute" command +Note that the last comment starts with `|"`, because the ":execute" command doesn't accept a comment directly. You also need to set 'textwidth' to a non-zero value, e.g., > @@ -454,7 +454,7 @@ the current window, try this custom `:HelpCurwin` command: > command -bar -nargs=? -complete=help HelpCurwin execute s:HelpCurwin(<q-args>) let s:did_open_help = v:false - + function s:HelpCurwin(subject) abort let mods = 'silent noautocmd keepalt' if !s:did_open_help diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index 52531a1525..917863eef8 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. -A parser can also be loaded manually using a full path: > +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: >lua 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 >lua -<`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. +Whenever you need to access the current syntax tree, parse the buffer: >lua -Parser methods *lua-treesitter-parser* - -tsparser:parse() *tsparser:parse()* -Whenever you need to access the current syntax tree, parse the buffer: > + 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. - tstree = parser:parse() +Note: To use the parser directly inside a |nvim_buf_attach()| Lua callback, +you must call |vim.treesitter.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. -<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. +See |lua-treesitter-languagetree| for the list of available methods. -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. +============================================================================== +TREESITTER TREES *treesitter-tree* + *tstree* -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. +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. -Tree methods *lua-treesitter-tree* +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")) + ((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!` directive 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,120 +297,408 @@ 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`. + + `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. + +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: > + + ;; inherits: foo,bar + ;; extends + + ;; extends + ;; + ;; inherits: baz +< +============================================================================== +TREESITTER SYNTAX HIGHLIGHTING *treesitter-highlight* + +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 > + + (parameters (identifier) @parameter) +< +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): > - (preproc_function_def name: (identifier) @function) + "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: >vim + + hi @comment.c guifg=Blue + hi @comment.lua guifg=DarkBlue + hi link @comment.doc.java String +< +The following captures are linked by default to standard |group-name|s: +> + @text.literal Comment + @text.reference Identifier + @text.title Title + @text.uri Underlined + @text.underline Underlined + @text.todo Todo + + @comment Comment + @punctuation Delimiter + + @constant Constant + @constant.builtin Special + @constant.macro Define + @define Define + @macro Macro + @string String + @string.escape SpecialChar + @string.special SpecialChar + @character Character + @character.special SpecialChar + @number Number + @boolean Boolean + @float Float + + @function Function + @function.builtin Special + @function.macro Macro + @parameter Identifier + @method Function + @field Identifier + @property Identifier + @constructor Special + + @conditional Conditional + @repeat Repeat + @label Label + @operator Operator + @keyword Keyword + @exception Exception + + @variable Identifier + @type Type + @type.definition Typedef + @storageclass StorageClass + @structure Structure + @namespace Identifier + @include Include + @preproc PreProc + @debug Debug + @tag Tag +< + *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: > - ; ... more definitions - ]] + (comment) @spell +< - highlighter = vim.treesitter.TSHighlighter.new(query, bufnr, lang) - -- alternatively, to use the current buffer and its filetype: - -- highlighter = vim.treesitter.TSHighlighter.new(query) +There is also `@nospell` which disables spellchecking regions with `@spell`. - -- Don't recreate the highlighter for the same buffer, instead - -- modify the query like this: - local query2 = [[ ... ]] - highlighter:set_query(query2) + *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: > -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|: > + (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: > - ((binary_expression left: (identifier) @WarningMsg.left right: (identifier) @WarningMsg.right) - (eq? @WarningMsg.left @WarningMsg.right)) + "!=" @operator (#set! conceal "≠") < -Treesitter Highlighting Priority *lua-treesitter-highlight-priority* +Conceals specified in this way respect 'conceallevel'. -Tree-sitter uses |nvim_buf_set_extmark()| to set highlights with a default + *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_parser({bufnr}, {lang}, {opts}) *get_parser()* - Gets the parser for this bufnr / ft combination. + *vim.treesitter.get_captures_at_cursor()* +get_captures_at_cursor({winnr}) + 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 + + *vim.treesitter.get_captures_at_pos()* +get_captures_at_pos({bufnr}, {row}, {col}) + 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}) *vim.treesitter.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 + + *vim.treesitter.get_node_at_pos()* +get_node_at_pos({bufnr}, {row}, {col}, {opts}) + 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: + • lang string|nil Parser language + • ignore_injections boolean Ignore injected languages + (default true) + + Return: ~ + userdata|nil |tsnode| under the cursor + +get_node_range({node_or_range}) *vim.treesitter.get_node_range()* + Returns the node's range or an unpacked range table + + Parameters: ~ + • {node_or_range} (userdata|table) |tsnode| or table of positions + + Return: ~ + (table) `{ start_row, start_col, end_row, end_col }` + +get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()* + Returns the parser for a specific buffer and filetype and attaches it to + the buffer + + If needed, this will create the parser. + + Parameters: ~ + • {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: ~ + LanguageTree |LanguageTree| object to use for parsing + + *vim.treesitter.get_string_parser()* +get_string_parser({str}, {lang}, {opts}) + Returns a string parser - If needed this will create the parser. Unconditionally attach the provided - callback + 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}) *vim.treesitter.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} + + *vim.treesitter.is_in_node_range()* +is_in_node_range({node}, {line}, {col}) + Determines whether (line, col) position is in node range 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 + • {node} userdata |tsnode| defining the range + • {line} (number) Line (0-based) + • {col} (number) Column (0-based) Return: ~ - The parser + (boolean) True if the position is in node range -get_string_parser({str}, {lang}, {opts}) *get_string_parser()* - Gets a string parser +node_contains({node}, {range}) *vim.treesitter.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} + +show_tree({opts}) *vim.treesitter.show_tree()* + Open a window that displays a textual representation of the nodes in the + language tree. + + While in the window, press "a" to toggle display of anonymous nodes, "I" + to toggle the display of the source language of each node, and press + <Enter> to jump to the node under the cursor in the source buffer. + + Parameters: ~ + • {opts} (table|nil) Optional options table with the following possible + keys: + • lang (string|nil): The language of the source buffer. If + omitted, the filetype of the source buffer is used. + • bufnr (number|nil): Buffer to draw the tree into. If + omitted, a new buffer is created. + • winid (number|nil): Window id to display the tree buffer in. + If omitted, a new window is created with {command}. + • command (string|nil): Vimscript command to create the + window. Default value is "topleft 60vnew". Only used when + {winid} is nil. + • title (string|fun(bufnr:number):string|nil): Title of the + window. If a function, it accepts the buffer number of the + source buffer as its only argument and should return a + string. + +start({bufnr}, {lang}) *vim.treesitter.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: >lua + + 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}) *vim.treesitter.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()* +inspect_language({lang}) *vim.treesitter.language.inspect_language()* Inspects the provided language. Inspecting provides some useful information on the language like node names, ... Parameters: ~ - {lang} The language. + • {lang} (string) Language + + Return: ~ + (table) -require_language({lang}, {path}, {silent}) *require_language()* - Asserts that the provided language is installed, and optionally provide a - path for the parser + *vim.treesitter.language.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()* + *vim.treesitter.query.add_directive()* +add_directive({name}, {handler}, {force}) Adds a new directive to be used in queries Handlers can set match level data by setting directly on the metadata @@ -411,61 +707,85 @@ 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) - -add_predicate({name}, {handler}, {force}) *add_predicate()* + • {name} (string) Name of the directive, without leading # + • {handler} function(match:table, pattern:string, bufnr:number, + predicate:string[], metadata:table) + • match: see |treesitter-query| + • node-level data are accessible via `match[capture_id]` + + • pattern: see |treesitter-query| + • predicate: list of strings containing the full directive + being called, e.g. `(node (#set! conceal "-"))` would get + the predicate `{ "#set!", "conceal", "-" }` + + *vim.treesitter.query.add_predicate()* +add_predicate({name}, {handler}, {force}) 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) - -get_node_text({node}, {source}) *get_node_text()* + • {name} (string) Name of the predicate, without leading # + • {handler} function(match:table, pattern:string, bufnr:number, + predicate:string[]) + • see |vim.treesitter.query.add_directive()| for argument + meanings + + *vim.treesitter.query.get_node_text()* +get_node_text({node}, {source}, {opts}) 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()* +get_query({lang}, {query_name}) *vim.treesitter.query.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()* + *vim.treesitter.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` -list_directives() *list_directives()* + Return: ~ + string[] query_files List of files to load for given query and + language + +list_directives() *vim.treesitter.query.list_directives()* Lists the currently available directives to use in queries. Return: ~ - The list of supported directives. + string[] List of supported directives. + +list_predicates() *vim.treesitter.query.list_predicates()* + Lists the currently available predicates to use in queries. -list_predicates() *list_predicates()* Return: ~ - The list of supported predicates. + string[] List of supported predicates. -parse_query({lang}, {query}) *parse_query()* +parse_query({lang}, {query}) *vim.treesitter.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 +793,214 @@ 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: >lua + + 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: >lua - 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} + *vim.treesitter.query.set_query()* +set_query({lang}, {query_name}, {text}) + 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()* +new({tree}, {opts}) *vim.treesitter.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} A text range, see |LanguageTree:contains| - {self} + • {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} (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 +1008,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 +1029,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. +new({source}, {lang}, {opts}) *vim.treesitter.languagetree.new()* + 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/uganda.txt b/runtime/doc/uganda.txt index 23dfa082a0..d8fc26ad17 100644 --- a/runtime/doc/uganda.txt +++ b/runtime/doc/uganda.txt @@ -11,9 +11,9 @@ Vim is Charityware. You can use and copy it as much as you like, but you are encouraged to make a donation for needy children in Uganda. Please see |kcc| below or visit the ICCF web site, available at these URLs: - http://iccf-holland.org/ - http://www.vim.org/iccf/ - http://www.iccf.nl/ + https://iccf-holland.org/ + https://www.vim.org/iccf/ + https://www.iccf.nl/ You can also sponsor the development of Vim. Vim sponsors can vote for features. See |sponsor|. The money goes to Uganda anyway. @@ -166,10 +166,11 @@ households are stimulated to build a proper latrine. I helped setting up a production site for cement slabs. These are used to build a good latrine. They are sold below cost price. -There is a small clinic at the project, which provides children and their -family with medical help. When needed, transport to a hospital is offered. -Immunization programs are carried out and help is provided when an epidemic is -breaking out (measles and cholera have been a problem). +There is a clinic at the project, which provides children and their family +medical help. Since 2020 a maternity ward was added and 24/7 service is +available. When needed, transport to a hospital is offered. Immunization +programs are carried out and help is provided when an epidemic is breaking out +(measles and cholera have been a problem). *donate* Summer 1994 to summer 1995 I spent a whole year at the centre, working as a volunteer. I have helped to expand the centre and worked in the area of water @@ -211,44 +212,29 @@ Check the ICCF web site for the latest information! See |iccf| for the URL. USA: The methods mentioned below can be used. - Sending a check to the Nehemiah Group Outreach Society (NGOS) - is no longer possible, unfortunately. We are looking for - another way to get you an IRS tax receipt. - For sponsoring a child contact KCF in Canada (see below). US - checks can be sent to them to lower banking costs. - -Canada: Contact Kibaale Children's Fund (KCF) in Surrey, Canada. They - take care of the Canadian sponsors for the children in - Kibaale. KCF forwards 100% of the money to the project in - Uganda. You can send them a one time donation directly. + If you must send a check send it to our Canadian partner: + https://www.kuwasha.net/ + +Canada: Contact Kuwasha in Surrey, Canada. They take care of the + Canadian sponsors for the children in Kibaale. Kuwasha + forwards 100% of the money to the project in Uganda. You can + send them a one time donation directly. Please send me a note so that I know what has been donated - because of Vim. Ask KCF for information about sponsorship. - Kibaale Children's Fund c/o Pacific Academy - 10238-168 Street - Surrey, B.C. V4N 1Z4 - Canada - Phone: 604-581-5353 - If you make a donation to Kibaale Children's Fund (KCF) you - will receive a tax receipt which can be submitted with your - tax return. - -Holland: Transfer to the account of "Stichting ICCF Holland" in Lisse. - This will allow for tax deduction if you live in Holland. - Postbank, nr. 4548774 - IBAN: NL95 INGB 0004 5487 74 + because of Vim. Look on their site for information about + sponsorship: https://www.kuwasha.net/ + If you make a donation to Kuwasha you will receive a tax + receipt which can be submitted with your tax return. + +Holland: Transfer to the account of "Stichting ICCF Holland" in + Amersfoort. This will allow for tax deduction if you live in + Holland. ING bank, IBAN: NL95 INGB 0004 5487 74 Germany: It is possible to make donations that allow for a tax return. Check the ICCF web site for the latest information: - http://iccf-holland.org/germany.html - -World: Use a postal money order. That should be possible from any - country, mostly from the post office. Use this name (which is - in my passport): "Abraham Moolenaar". Use Euro for the - currency if possible. + https://iccf-holland.org/germany.html -Europe: Use a bank transfer if possible. Your bank should have a form - that you can use for this. See "Others" below for the swift - code and IBAN number. +Europe: Use a bank transfer if possible. See "Others" below for the + swift code and IBAN number. Any other method should work. Ask for information about sponsorship. @@ -258,28 +244,12 @@ Credit Card: You can use PayPal to send money with a Credit card. This is https://www.paypal.com/en_US/mrb/pal=XAC62PML3GF8Q The e-mail address for sending the money to is: Bram@iccf-holland.org - For amounts above 400 Euro ($500) sending a check is - preferred. - -Others: Transfer to one of these accounts if possible: - Postbank, account 4548774 - Swift code: INGB NL 2A - IBAN: NL95 INGB 0004 5487 74 - under the name "stichting ICCF Holland", Lisse - If that doesn't work: - Rabobank Lisse, account 3765.05.117 - Swift code: RABO NL 2U - under the name "Bram Moolenaar", Lisse - Otherwise, send a check in euro or US dollars to the address - below. Minimal amount: $70 (my bank does not accept smaller - amounts for foreign check, sorry) - -Address to send checks to: - Bram Moolenaar - Finsterruetihof 1 - 8134 Adliswil - Switzerland - -This address is expected to be valid for a long time. + +Others: Transfer to this account if possible: + ING bank: IBAN: NL95 INGB 0004 5487 74 + Swift code: INGBNL2A + under the name "stichting ICCF Holland", Amersfoort + Checks are not accepted. + vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/ui.txt b/runtime/doc/ui.txt index 3fb9ed1125..3110d0817c 100644 --- a/runtime/doc/ui.txt +++ b/runtime/doc/ui.txt @@ -23,40 +23,41 @@ 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) - *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). - *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|. +- `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). + *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|. + `stdin_tty` Tells if `stdin` is a `tty` or not. + `stdout_tty` Tells if `stdout` is a `tty` or not. Specifying an unknown option is an error; UIs can check the |api-metadata| `ui_options` key for supported options. @@ -120,7 +121,7 @@ for forward-compatibility. |api-contract| UI startup *ui-startup* UI embedders (clients that start Nvim with |--embed| and later call -|nvim_ui_attach()|) must start Nvim without |--headless|: > +|nvim_ui_attach()|) must start Nvim without |--headless|: >bash nvim --embed Nvim will pause before loading startup files and reading buffers, so the UI has a chance to invoke requests and do early initialization. Startup will @@ -133,14 +134,18 @@ procedure: 1. Invoke |nvim_get_api_info()|, if needed to setup the client library and/or to get the list of supported UI extensions. + 2. Do any configuration that should be happen before user config is loaded. Buffers and windows are not available at this point, but this could be used to set |g:| variables visible to init.vim + 3. If the UI wants to do additional setup after user config is loaded, - register a VimEnter autocmd: > + register a VimEnter autocmd: >vim nvim_command("autocmd VimEnter * call rpcrequest(1, 'vimenter')") -<4. Now invoke |nvim_ui_attach()|. The UI must handle user input by now: + +4. Now invoke |nvim_ui_attach()|. The UI must handle user input by now: sourcing init.vim and loading buffers might lead to blocking prompts. + 5. If step 3 was used, Nvim will send a blocking "vimenter" request to the UI. Inside this request handler, the UI can safely do any initialization before entering normal mode, for example reading variables set by init.vim. @@ -164,13 +169,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 +202,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 +229,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 +238,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 +284,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 +305,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. @@ -318,6 +324,7 @@ numerical highlight ids to the actual attributes. `underdouble`: double underlined text. The lines have `special` color. `underdotted`: underdotted text. The dots have `special` color. `underdashed`: underdashed text. The dashes have `special` color. + `altfont`: alternative font. `blend`: Blend level (0-100). Could be used by UIs to support blending floating windows to the background or to signal a transparent cursor. @@ -345,7 +352,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 +361,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 +380,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 +445,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 +488,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 +582,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 +594,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 +645,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 +657,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 +670,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 +686,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 +709,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,12 +720,12 @@ 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: > + the user defines a |:function| interactively: >vim :function Foo() : echo "foo" : @@ -726,10 +733,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 +753,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 +787,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..9c428175bb --- /dev/null +++ b/runtime/doc/userfunc.txt @@ -0,0 +1,440 @@ +*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". + Also, there is no check if the following + line contains a valid command. Forgetting the line + continuation backslash may go unnoticed: > + return 'some text' + .. ' some more text' +< Will happily return "some text" without an error. It + should have been: > + return 'some text' + \ .. ' some more text' +< + 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 + +If the file doesn't exist, Vim will also search in 'packpath' (under "start") +to allow calling packages' functions from your |vimrc| when the packages have +not been added to 'runtimepath' yet (see |packages|). + +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_01.txt b/runtime/doc/usr_01.txt index 52fbf06ec4..f0e2462fae 100644 --- a/runtime/doc/usr_01.txt +++ b/runtime/doc/usr_01.txt @@ -85,7 +85,7 @@ The Vim user manual and reference manual are Copyright (c) 1988-2003 by Bram Moolenaar. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later. The latest version is presently available at: - http://www.opencontent.org/openpub/ + https://www.opencontent.org/openpub/ People who contribute to the manuals must agree with the above copyright notice. diff --git a/runtime/doc/usr_02.txt b/runtime/doc/usr_02.txt index f822e7d4b8..11afe39742 100644 --- a/runtime/doc/usr_02.txt +++ b/runtime/doc/usr_02.txt @@ -33,7 +33,7 @@ On Unix you can type this at any command prompt. If you are running Microsoft Windows, open a Command Prompt and enter the command. In either case, Vim starts editing a file called file.txt. Because this is a new file, you get a blank window. This is what your screen will look like: - +> +---------------------------------------+ |# | |~ | @@ -43,7 +43,7 @@ blank window. This is what your screen will look like: |"file.txt" [New file] | +---------------------------------------+ ('#' is the cursor position.) - +< The tilde (~) lines indicate lines not in the file. In other words, when Vim runs out of file to display, it displays tilde lines. At the bottom of the screen, a message line indicates the file is named file.txt and shows that you @@ -83,7 +83,7 @@ limerick, this is what you type: > After typing "turtle" you press the <Enter> key to start a new line. Finally you press the <Esc> key to stop Insert mode and go back to Normal mode. You now have two lines of text in your Vim window: - +> +---------------------------------------+ |A very intelligent turtle | |Found programming Unix a hurdle | @@ -91,7 +91,7 @@ now have two lines of text in your Vim window: |~ | | | +---------------------------------------+ - +< WHAT IS THE MODE? @@ -105,7 +105,7 @@ with a colon). Finish this command by pressing the <Enter> key (all commands that start with a colon are finished this way). Now, if you type the "i" command Vim will display --INSERT-- at the bottom of the window. This indicates you are in Insert mode. - +> +---------------------------------------+ |A very intelligent turtle | |Found programming Unix a hurdle | @@ -113,7 +113,7 @@ of the window. This indicates you are in Insert mode. |~ | |-- INSERT -- | +---------------------------------------+ - +< If you press <Esc> to go back to Normal mode the last line will be made blank. @@ -182,7 +182,7 @@ throwback to the old days of the typewriter, when you deleted things by typing xxxx over them.) Move the cursor to the beginning of the first line, for example, and type xxxxxxx (seven x's) to delete "A very ". The result should look like this: - +> +---------------------------------------+ |intelligent turtle | |Found programming Unix a hurdle | @@ -190,14 +190,14 @@ look like this: |~ | | | +---------------------------------------+ - +< Now you can insert new text, for example by typing: > iA young <Esc> This begins an insert (the i), inserts the words "A young", and then exits insert mode (the final <Esc>). The result: - +> +---------------------------------------+ |A young intelligent turtle | |Found programming Unix a hurdle | @@ -205,13 +205,13 @@ insert mode (the final <Esc>). The result: |~ | | | +---------------------------------------+ - +< DELETING A LINE To delete a whole line use the "dd" command. The following line will then move up to fill the gap: - +> +---------------------------------------+ |Found programming Unix a hurdle | |~ | @@ -219,7 +219,7 @@ then move up to fill the gap: |~ | | | +---------------------------------------+ - +< DELETING A LINE BREAK diff --git a/runtime/doc/usr_03.txt b/runtime/doc/usr_03.txt index 74674fdb42..2b0d40ba32 100644 --- a/runtime/doc/usr_03.txt +++ b/runtime/doc/usr_03.txt @@ -224,7 +224,7 @@ you can see? This figure shows the three commands you can use: +---------------------------+ Hints: "H" stands for Home, "M" for Middle and "L" for Last. Alternatively, -"H" for high, "M" for Middle and "L" for low. +"H" for High, "M" for Middle and "L" for Low. ============================================================================== *03.6* Telling where you are diff --git a/runtime/doc/usr_05.txt b/runtime/doc/usr_05.txt index 0e94d9a1b1..24d6185eae 100644 --- a/runtime/doc/usr_05.txt +++ b/runtime/doc/usr_05.txt @@ -107,7 +107,7 @@ Display an incomplete command in the lower right corner of the Vim window, left of the ruler. For example, when you type "2f", Vim is waiting for you to type the character to find and "2f" is displayed. When you press "w" next, the "2fw" command is executed and the displayed "2f" is removed. - +> +-------------------------------------------------+ |text in the Vim window | |~ | @@ -119,7 +119,7 @@ the "2fw" command is executed and the displayed "2f" is removed. > set incsearch - +< Display matches for a search pattern while you type. > @@ -127,8 +127,8 @@ Display matches for a search pattern while you type. This defines a key mapping. More about that in the next section. This defines the "Q" command to do formatting with the "gq" operator. This is how -it worked before Vim 5.0. Otherwise the "Q" command starts Ex mode, but you -will not need it. +it worked before Vim 5.0. Otherwise the "Q" command repeats the last recorded +register. > vnoremap _g y:exe "grep /" .. escape(@", '\\/') .. "/ *.c *.h"<CR> @@ -320,7 +320,7 @@ Where can you find plugins? - Some are always loaded, you can see them in the directory $VIMRUNTIME/plugin. - Some come with Vim. You can find them in the directory $VIMRUNTIME/macros and its sub-directories and under $VIM/vimfiles/pack/dist/opt/. -- Download from the net. There is a large collection on http://www.vim.org. +- Download from the net. There is a large collection on https://www.vim.org. - They are sometimes posted in a Vim maillist. - You could write one yourself, see |write-plugin|. diff --git a/runtime/doc/usr_06.txt b/runtime/doc/usr_06.txt index 8eda33b4f0..755e6e816a 100644 --- a/runtime/doc/usr_06.txt +++ b/runtime/doc/usr_06.txt @@ -14,8 +14,7 @@ screen. |06.2| No or wrong colors? |06.3| Different colors |06.4| With colors or without colors -|06.5| Printing with colors -|06.6| Further reading +|06.5| Further reading Next chapter: |usr_07.txt| Editing more than one file Previous chapter: |usr_05.txt| Set your settings @@ -191,59 +190,7 @@ buffer, set the 'syntax' option: > :set syntax=ON < ============================================================================== -*06.5* Printing with colors *syntax-printing* - -In the MS-Windows version you can print the current file with this command: > - - :hardcopy - -You will get the usual printer dialog, where you can select the printer and a -few settings. If you have a color printer, the paper output should look the -same as what you see inside Vim. But when you use a dark background the -colors will be adjusted to look good on white paper. - -There are several options that change the way Vim prints: - 'printdevice' - 'printheader' - 'printfont' - 'printoptions' - -To print only a range of lines, use Visual mode to select the lines and then -type the command: > - - v100j:hardcopy - -"v" starts Visual mode. "100j" moves a hundred lines down, they will be -highlighted. Then ":hardcopy" will print those lines. You can use other -commands to move in Visual mode, of course. - -This also works on Unix, if you have a PostScript printer. Otherwise, you -will have to do a bit more work. You need to convert the text to HTML first, -and then print it from a web browser. - -Convert the current file to HTML with this command: > - - :TOhtml - -In case that doesn't work: > - - :source $VIMRUNTIME/syntax/2html.vim - -You will see it crunching away, this can take quite a while for a large file. -Some time later another window shows the HTML code. Now write this somewhere -(doesn't matter where, you throw it away later): -> - :write main.c.html - -Open this file in your favorite browser and print it from there. If all goes -well, the output should look exactly as it does in Vim. See |2html.vim| for -details. Don't forget to delete the HTML file when you are done with it. - -Instead of printing, you could also put the HTML file on a web server, and let -others look at the colored text. - -============================================================================== -*06.6* Further reading +*06.5* Further reading |usr_44.txt| Your own syntax highlighted. |syntax| All the details. diff --git a/runtime/doc/usr_08.txt b/runtime/doc/usr_08.txt index 1d20913a14..0ba03a4861 100644 --- a/runtime/doc/usr_08.txt +++ b/runtime/doc/usr_08.txt @@ -32,7 +32,7 @@ The easiest way to open a new window is to use the following command: > This command splits the screen into two windows and leaves the cursor in the top one: - +> +----------------------------------+ |/* file one.c */ | |~ | @@ -43,7 +43,7 @@ top one: |one.c=============================| | | +----------------------------------+ - +< What you see here is two windows on the same file. The line with "====" is the status line. It displays information about the window above it. (In practice the status line will be in reverse video.) @@ -87,7 +87,7 @@ The following command opens a second window and starts editing the given file: :split two.c If you were editing one.c, then the result looks like this: - +> +----------------------------------+ |/* file two.c */ | |~ | @@ -98,7 +98,7 @@ If you were editing one.c, then the result looks like this: |one.c=============================| | | +----------------------------------+ - +< To open a window on a new, empty file, use this: > :new @@ -170,7 +170,7 @@ or: > :vsplit two.c The result looks something like this: - +> +--------------------------------------+ |/* file two.c */ |/* file one.c */ | |~ |~ | @@ -179,7 +179,7 @@ The result looks something like this: |two.c===============one.c=============| | | +--------------------------------------+ - +< Actually, the | lines in the middle will be in reverse video. This is called the vertical separator. It separates the two windows left and right of it. @@ -218,7 +218,7 @@ cursor keys can also be used, if you like. You have split a few windows, but now they are in the wrong place. Then you need a command to move the window somewhere else. For example, you have three windows like this: - +> +----------------------------------+ |/* file two.c */ | |~ | @@ -233,7 +233,7 @@ windows like this: |one.c=============================| | | +----------------------------------+ - +< Clearly the last one should be at the top. Go to that window (using CTRL-W w) and then type this command: > @@ -244,7 +244,7 @@ the very top. You will notice that K is again used for moving upwards. When you have vertical splits, CTRL-W K will move the current window to the top and make it occupy the full width of the Vim window. If this is your layout: - +> +-------------------------------------------+ |/* two.c */ |/* three.c */ |/* one.c */ | |~ |~ |~ | @@ -255,9 +255,9 @@ layout: |two.c=========three.c=========one.c========| | | +-------------------------------------------+ - +< Then using CTRL-W K in the middle window (three.c) will result in: - +> +-------------------------------------------+ |/* three.c */ | |~ | @@ -268,7 +268,7 @@ Then using CTRL-W K in the middle window (three.c) will result in: |two.c==================one.c===============| | | +-------------------------------------------+ - +< The other three similar commands (you can probably guess these now): CTRL-W H move window to the far left @@ -316,7 +316,7 @@ To make Vim open a window for each file, start it with the "-o" argument: > vim -o one.txt two.txt three.txt This results in: - +> +-------------------------------+ |file one.txt | |~ | @@ -329,7 +329,7 @@ This results in: |three.txt======================| | | +-------------------------------+ - +< The "-O" argument is used to get vertically split windows. When Vim is already running, the ":all" command opens a window for each file in the argument list. ":vertical all" does it with vertical splits. @@ -347,7 +347,7 @@ Type this command in a shell to start Nvim in diff mode: > Vim will start, with two windows side by side. You will only see the line in which you added characters, and a few lines above and below it. - +> VV VV +-----------------------------------------+ |+ +--123 lines: /* a|+ +--123 lines: /* a| <- fold @@ -366,7 +366,7 @@ in which you added characters, and a few lines above and below it. |main.c~==============main.c==============| | | +-----------------------------------------+ - +< (This picture doesn't show the highlighting, use "nvim -d" for that.) The lines that were not modified have been collapsed into one line. This is @@ -519,7 +519,7 @@ Assume you are editing "thisfile". To create a new tab page use this command: > This will edit the file "thatfile" in a window that occupies the whole Vim window. And you will notice a bar at the top with the two file names: - +> +----------------------------------+ | thisfile | /thatfile/ __________X| (thatfile is bold) |/* thatfile */ | @@ -530,13 +530,13 @@ window. And you will notice a bar at the top with the two file names: |~ | | | +----------------------------------+ - +< You now have two tab pages. The first one has a window for "thisfile" and the second one a window for "thatfile". It's like two pages that are on top of each other, with a tab sticking out of each page showing the file name. Now use the mouse to click on "thisfile" in the top line. The result is - +> +----------------------------------+ | /thisfile/ | thatfile __________X| (thisfile is bold) |/* thisfile */ | @@ -547,7 +547,7 @@ Now use the mouse to click on "thisfile" in the top line. The result is |~ | | | +----------------------------------+ - +< Thus you can switch between tab pages by clicking on the label in the top line. If you don't have a mouse or don't want to use it, you can use the "gt" command. Mnemonic: Goto Tab. @@ -558,7 +558,7 @@ Now let's create another tab page with the command: > This makes a new tab page with one window that is editing the same buffer as the window we were in: - +> +-------------------------------------+ | thisfile | /thisfile/ | thatfile __X| (thisfile is bold) |/* thisfile */ | @@ -569,7 +569,7 @@ the window we were in: |~ | | | +-------------------------------------+ - +< You can put ":tab" before any Ex command that opens a window. The window will be opened in a new tab page. Another example: > diff --git a/runtime/doc/usr_10.txt b/runtime/doc/usr_10.txt index 8844671e01..3e45fda882 100644 --- a/runtime/doc/usr_10.txt +++ b/runtime/doc/usr_10.txt @@ -813,10 +813,10 @@ REDRAWING THE SCREEN If the external command produced an error message, the display may have been messed up. Vim is very efficient and only redraws those parts of the screen that it knows need redrawing. But it can't know about what another program -has written. To tell Vim to redraw the screen: > - +has written. To tell Vim to redraw the screen: +> CTRL-L - +< ============================================================================== Next chapter: |usr_11.txt| Recovering from a crash diff --git a/runtime/doc/usr_20.txt b/runtime/doc/usr_20.txt index 6a8836c8e8..2b69862fe1 100644 --- a/runtime/doc/usr_20.txt +++ b/runtime/doc/usr_20.txt @@ -338,7 +338,7 @@ Open the command line window with this command: > Vim now opens a (small) window at the bottom. It contains the command line history, and an empty line at the end: - +> +-------------------------------------+ |other window | |~ | @@ -353,7 +353,7 @@ history, and an empty line at the end: |command-line=========================| | | +-------------------------------------+ - +< You are now in Normal mode. You can use the "hjkl" keys to move around. For example, move up with "5k" to the ":e config.h.in" line. Type "$h" to go to the "i" of "in" and type "cwout". Now you have changed the line to: diff --git a/runtime/doc/usr_21.txt b/runtime/doc/usr_21.txt index add5d48073..191d333f3d 100644 --- a/runtime/doc/usr_21.txt +++ b/runtime/doc/usr_21.txt @@ -255,7 +255,8 @@ well stand for "source"). The windows that were open are restored, with the same position and size as before. Mappings and option values are like before. What exactly is restored depends on the 'sessionoptions' option. The -default value is "blank,buffers,curdir,folds,help,options,winsize". +default value is: +"blank,buffers,curdir,folds,help,options,tabpages,winsize,terminal". blank keep empty windows buffers all buffers, not only the ones in a window @@ -263,7 +264,9 @@ default value is "blank,buffers,curdir,folds,help,options,winsize". folds folds, also manually created ones help the help window options all options and mappings + tabpages all tab pages winsize window sizes + terminal include terminal windows Change this to your liking. To also restore the size of the Vim window, for example, use: > @@ -299,7 +302,7 @@ session file as a starting point. use, and save this in a session. Then you can go back to this layout whenever you want. For example, this is a nice layout to use: - +> +----------------------------------------+ | VIM - main help file | | | @@ -315,7 +318,7 @@ you want. |~/=========|[No File]===================| | | +----------------------------------------+ - +< This has a help window at the top, so that you can read this text. The narrow vertical window on the left contains a file explorer. This is a Vim plugin that lists the contents of a directory. You can select files to edit there. @@ -451,7 +454,7 @@ Use this format for the modeline: The "any-text" indicates that you can put any text before and after the part that Vim will use. This allows making it look like a comment, like what was -done above with /* and */. +done above with "/*" and "*/". The " vim:" part is what makes Vim recognize this line. There must be white space before "vim", or "vim" must be at the start of the line. Thus using something like "gvim:" will not work. 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_25.txt b/runtime/doc/usr_25.txt index 2efb67e55f..955d2ae5f0 100644 --- a/runtime/doc/usr_25.txt +++ b/runtime/doc/usr_25.txt @@ -325,16 +325,16 @@ Let's attempt to show this with one line of text. The cursor is on the "w" of currently visible. The "window"s below the text indicate the text that is visible after the command left of it. - |<-- current window -->| + `|<-- current window -->|` some long text, part of which is visible in the window ~ - ze |<-- window -->| - zH |<-- window -->| - 4zh |<-- window -->| - zh |<-- window -->| - zl |<-- window -->| - 4zl |<-- window -->| - zL |<-- window -->| - zs |<-- window -->| + ze `|<-- window -->|` + zH `|<-- window -->|` + 4zh `|<-- window -->|` + zh `|<-- window -->|` + zl `|<-- window -->|` + 4zl `|<-- window -->|` + zL `|<-- window -->|` + zs `|<-- window -->|` MOVING WITH WRAP OFF @@ -350,7 +350,7 @@ scroll: gM to middle of the text in this line g$ to last visible character in this line - |<-- window -->| + `|<-- window -->|` some long text, part of which is visible in one line ~ g0 g^ gm gM g$ @@ -365,7 +365,7 @@ broken halfway, which makes them hard to read. 'linebreak' option. Vim then breaks lines at an appropriate place when displaying the line. The text in the file remains unchanged. Without 'linebreak' text might look like this: - +> +---------------------------------+ |letter generation program for a b| |ank. They wanted to send out a s| @@ -373,12 +373,13 @@ displaying the line. The text in the file remains unchanged. |eir richest 1000 customers. Unfo| |rtunately for the programmer, he | +---------------------------------+ +< After: > :set linebreak it looks like this: - +> +---------------------------------+ |letter generation program for a | |bank. They wanted to send out a | @@ -386,7 +387,7 @@ it looks like this: |their richest 1000 customers. | |Unfortunately for the programmer,| +---------------------------------+ - +< Related options: 'breakat' specifies the characters where a break can be inserted. 'showbreak' specifies a string to show at the start of broken line. @@ -425,7 +426,7 @@ That looks complicated. Let's break it up in pieces: into one line. Starting with this text, containing eight lines broken at column 30: - +> +----------------------------------+ |A letter generation program | |for a bank. They wanted to | @@ -436,9 +437,9 @@ Starting with this text, containing eight lines broken at column 30: |customers. Unfortunately for | |the programmer, | +----------------------------------+ - +< You end up with two lines: - +> +----------------------------------+ |A letter generation program for a | |bank. They wanted to send out a s| @@ -446,7 +447,7 @@ You end up with two lines: |To their richest 1000 customers. | |Unfortunately for the programmer, | +----------------------------------+ - +< Note that this doesn't work when the separating line is blank but not empty; when it contains spaces and/or tabs. This command does work with blank lines: > diff --git a/runtime/doc/usr_29.txt b/runtime/doc/usr_29.txt index d8c556c281..751cb9a902 100644 --- a/runtime/doc/usr_29.txt +++ b/runtime/doc/usr_29.txt @@ -33,9 +33,8 @@ following command: > ctags *.c "ctags" is a separate program. Most Unix systems already have it installed. -If you do not have it yet, you can find Universal/Exuberant ctags at: - http://ctags.io ~ - http://ctags.sf.net ~ +If you do not have it yet, you can find Universal ctags at: + https://ctags.io ~ Universal ctags is preferred, Exuberant ctags is no longer being developed. @@ -54,7 +53,7 @@ function. The "write_line" function calls "write_char". You need to figure out what it does. So you position the cursor over the call to "write_char" and press CTRL-]. Now you are at the definition of "write_char". - +> +-------------------------------------+ |void write_block(char **s; int cnt) | |{ | @@ -80,7 +79,7 @@ CTRL-]. Now you are at the definition of "write_char". | putchar((int)(unsigned char)c); | |} | +------------------------------------+ - +< The ":tags" command shows the list of tags that you traversed through: :tags @@ -268,9 +267,6 @@ doesn't work if the tags file isn't sorted. The 'taglength' option can be used to tell Vim the number of significant characters in a tag. -Cscope is a free program. It does not only find places where an identifier is -declared, but also where it is used. See |cscope|. - ============================================================================== *29.2* The preview window @@ -429,7 +425,7 @@ MOVING IN COMMENTS To move back to the start of a comment use "[/". Move forward to the end of a comment with "]/". This only works for /* - */ comments. - +> +-> +-> /* | [/ | * A comment about --+ [/ | +-- * wonderful life. | ]/ @@ -438,7 +434,7 @@ comment with "]/". This only works for /* - */ comments. +-- foo = bar * 3; --+ | ]/ /* a short comment */ <-+ - +< ============================================================================== *29.4* Finding global identifiers @@ -579,7 +575,7 @@ and jump to the first place where the word under the cursor is used: > Hint: Goto Definition. This command is very useful to find a variable or function that was declared locally ("static", in C terms). Example (cursor on "counter"): - +> +-> static int counter = 0; | | int get_counter(void) @@ -587,7 +583,7 @@ function that was declared locally ("static", in C terms). Example (cursor on | ++counter; +-- return counter; } - +< To restrict the search even further, and look only in the current function, use this command: > @@ -597,7 +593,7 @@ This will go back to the start of the current function and find the first occurrence of the word under the cursor. Actually, it searches backwards to an empty line above a "{" in the first column. From there it searches forward for the identifier. Example (cursor on "idx"): - +> int find_entry(char *name) { +-> int idx; @@ -606,7 +602,7 @@ for the identifier. Example (cursor on "idx"): | if (strcmp(table[idx].name, name) == 0) +-- return idx; } - +< ============================================================================== Next chapter: |usr_30.txt| Editing programs diff --git a/runtime/doc/usr_30.txt b/runtime/doc/usr_30.txt index 98d1780cc4..7e7b3b21f4 100644 --- a/runtime/doc/usr_30.txt +++ b/runtime/doc/usr_30.txt @@ -56,7 +56,7 @@ From this you can see that you have errors in the file "main.c". When you press <Enter>, Vim displays the file "main.c", with the cursor positioned on line 6, the first line with an error. You did not need to specify the file or the line number, Vim knew where to go by looking in the error messages. - +> +---------------------------------------------------+ |int main() | |{ | @@ -69,7 +69,7 @@ the line number, Vim knew where to go by looking in the error messages. | ~ | |(3 of 12): too many arguments to function 'do_sub' | +---------------------------------------------------+ - +< The following command goes to where the next error occurs: > :cnext diff --git a/runtime/doc/usr_32.txt b/runtime/doc/usr_32.txt index 8b489ea1e0..324efccf25 100644 --- a/runtime/doc/usr_32.txt +++ b/runtime/doc/usr_32.txt @@ -169,10 +169,10 @@ To travel forward in time again use the |:later| command: > The arguments are "s", "m" and "h", just like with |:earlier|. If you want even more details, or want to manipulate the information, you can -use the |undotree()| function. To see what it returns: > - +use the |undotree()| function. To see what it returns: +> :echo undotree() - +< ============================================================================== Next chapter: |usr_40.txt| Make new commands diff --git a/runtime/doc/usr_40.txt b/runtime/doc/usr_40.txt index f47c933124..8befb15528 100644 --- a/runtime/doc/usr_40.txt +++ b/runtime/doc/usr_40.txt @@ -226,7 +226,7 @@ When using a space inside a mapping, use <Space> (seven characters): > This makes the spacebar move a blank-separated word forward. It is not possible to put a comment directly after a mapping, because the " -character is considered to be part of the mapping. You can use |", this +character is considered to be part of the mapping. You can use `|"`, this starts a new, empty command with a comment. Example: > :map <Space> W| " Use spacebar to move forward a word @@ -657,10 +657,10 @@ To ignore all events, use the following command: > :set eventignore=all -To set it back to the normal behavior, make 'eventignore' empty: > - +To set it back to the normal behavior, make 'eventignore' empty: +> :set eventignore= - +< ============================================================================== Next chapter: |usr_41.txt| Write a Vim script diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index 0c907bfb68..910aebae70 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 @@ -617,10 +619,12 @@ String manipulation: *string-functions* stridx() first index of a short string in a long string strridx() last index of a short string in a long string strlen() length of a string in bytes - strchars() length of a string in characters + strcharlen() length of a string in characters + strchars() number of characters in a string strwidth() size of string when displayed strdisplaywidth() size of string when displayed, deals with tabs setcellwidths() set character cell width overrides + getcellwidths() get character cell width overrides substitute() substitute a pattern match with a string submatch() get a specific match in ":s" and substitute() strpart() get part of a string using byte index @@ -637,6 +641,7 @@ String manipulation: *string-functions* execute() execute an Ex command and get the output win_execute() like execute() but in a specified window trim() trim characters from a string + gettext() lookup message translation List manipulation: *list-functions* get() get an item without error for wrong index @@ -745,6 +750,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. @@ -780,6 +786,13 @@ Working with text in the current buffer: *text-functions* getcharsearch() return character search information setcharsearch() set character search information +Working with text in another buffer: + getbufline() get a list of lines from the specified buffer + getbufoneline() get a one line from the specified buffer + setbufline() replace a line in the specified buffer + appendbufline() append a list of lines in the specified buffer + deletebufline() delete lines from a specified buffer + *system-functions* *file-functions* System functions and manipulation of files: glob() expand wildcards @@ -814,6 +827,7 @@ System functions and manipulation of files: setenv() set an environment variable hostname() name of the system readfile() read a file into a List of lines + readblob() read a file into a Blob readdir() get a List of file names in a directory writefile() write a List of lines or Blob into a file @@ -832,8 +846,10 @@ Buffers, windows and the argument list: argidx() current position in the argument list arglistid() get id of the argument list argv() get one entry from the argument list + bufadd() add a file to the list of buffers bufexists() check if a buffer exists buflisted() check if a buffer exists and is listed + bufload() ensure a buffer is loaded bufloaded() check if a buffer exists and is loaded bufname() get the name of a specific buffer bufnr() get the buffer number of a specific buffer @@ -844,10 +860,6 @@ Buffers, windows and the argument list: bufwinid() get the window ID of a specific buffer bufwinnr() get the window number of a specific buffer winbufnr() get the buffer number of a specific window - getbufline() get a list of lines from the specified buffer - setbufline() replace a line in the specified buffer - appendbufline() append a list of lines in the specified buffer - deletebufline() delete lines from a specified buffer win_findbuf() find windows containing a buffer win_getid() get window ID of a window win_gettype() get type of window @@ -872,6 +884,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 +1025,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 @@ -1046,7 +1060,6 @@ Various: *various-functions* exists() check if a variable, function, etc. exists has() check if a feature is supported in Vim changenr() return number of most recent change - cscope_connection() check if a cscope connection exists did_filetype() check if a FileType autocommand was used eventhandler() check if invoked by an event handler getpid() get process ID of Vim @@ -1069,8 +1082,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 +1719,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 +1770,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 @@ -2619,7 +2632,7 @@ Further reading: |autoload|. ============================================================================== *41.16* Distributing Vim scripts *distribute-script* -Vim users will look for scripts on the Vim website: http://www.vim.org. +Vim users will look for scripts on the Vim website: https://www.vim.org. If you made something that is useful for others, share it! Vim scripts can be used on any system. There might not be a tar or gzip diff --git a/runtime/doc/usr_42.txt b/runtime/doc/usr_42.txt index 470f4e0fe5..9c5e3db72c 100644 --- a/runtime/doc/usr_42.txt +++ b/runtime/doc/usr_42.txt @@ -81,7 +81,7 @@ the far right. The second number (340) determines the location of the item within the pull-down menu. Lower numbers go on top, higher number on the bottom. These are the priorities in the File menu: - +> +-----------------+ 10.310 |Open... | 10.320 |Split-Open... | @@ -99,7 +99,7 @@ are the priorities in the File menu: 10.610 |Save-Exit | 10.620 |Exit | +-----------------+ - +< Notice that there is room in between the numbers. This is where you can insert your own items, if you really want to (it's often better to leave the standard menus alone and add a new menu for your own items). @@ -168,11 +168,11 @@ inserts a CTRL-C or CTRL-O for you. For example, if you use this command: Then the resulting menu commands will be: - Normal mode: * - Visual mode: CTRL-C * - Operator-pending mode: CTRL-C * - Insert mode: CTRL-O * - Command-line mode: CTRL-C * + Normal mode: `*` + Visual mode: CTRL-C `*` + Operator-pending mode: CTRL-C `*` + Insert mode: CTRL-O `*` + Command-line mode: CTRL-C `*` When in Command-line mode the CTRL-C will abandon the command typed so far. In Visual and Operator-pending mode CTRL-C will stop the mode. The CTRL-O in diff --git a/runtime/doc/usr_45.txt b/runtime/doc/usr_45.txt index 3199c4d8ea..95a2bc8f79 100644 --- a/runtime/doc/usr_45.txt +++ b/runtime/doc/usr_45.txt @@ -71,8 +71,8 @@ directory src/po/README.txt. programmer. You must know both English and the language you are translating to, of course. When you are satisfied with the translation, consider making it available -to others. Upload it at vim-online (http://vim.sf.net) or e-mail it to -the Vim maintainer <maintainer@vim.org>. Or both. +to others. Upload it to https://github.com/vim/vim or e-mail it to the Vim +maintainer <maintainer@vim.org>. Or both. ============================================================================== *45.2* Language for Menus @@ -166,10 +166,7 @@ script files, etc. You can regard 'encoding' as the setting for the internals of Vim. This example assumes you have this font on your system. The name in the example is for the X Window System. This font is in a package that is used to -enhance xterm with Unicode support. If you don't have this font, you might -find it here: - - http://www.cl.cam.ac.uk/~mgk25/download/ucs-fonts.tar.gz ~ +enhance xterm with Unicode support. For MS-Windows, some fonts have a limited number of Unicode characters. Try using the "Courier New" font. You can use the Edit/Select Font... menu to @@ -178,10 +175,7 @@ though. Example: > :set guifont=courier_new:h12 -If it doesn't work well, try getting a fontpack. If Microsoft didn't move it, -you can find it here: - - http://www.microsoft.com/typography/fonts/default.aspx ~ +If it doesn't work well, try getting a fontpack. Now you have told Vim to use Unicode internally and display text with a Unicode font. @@ -300,8 +294,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..dd0d5784f5 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. @@ -111,8 +111,7 @@ Read this from start to end to learn the essential commands. |06.2| No or wrong colors? |06.3| Different colors |06.4| With colors or without colors - |06.5| Printing with colors - |06.6| Further reading + |06.5| Further reading |usr_07.txt| Editing more than one file |07.1| Edit another file @@ -167,7 +166,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 +274,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..e13d892fd6 100644 --- a/runtime/doc/various.txt +++ b/runtime/doc/various.txt @@ -102,9 +102,7 @@ g8 Print the hex values of the bytes used in the *:p* *:pr* *:print* *E749* :[range]p[rint] [flags] Print [range] lines (default current line). - Note: If you are looking for a way to print your text - on paper see |:hardcopy|. In the GUI you can use the - File.Print menu entry. + In the GUI you can use the File.Print menu entry. See |ex-flags| for [flags]. The |:filter| command can be used to only show lines matching a pattern. @@ -260,6 +258,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/vi_diff.txt b/runtime/doc/vi_diff.txt index cef2859eb5..afabddb7f9 100644 --- a/runtime/doc/vi_diff.txt +++ b/runtime/doc/vi_diff.txt @@ -337,10 +337,6 @@ Viminfo. The 'viminfo' option can be set to select which items to store in the .viminfo file. This is off by default. -Printing. |printing| - The |:hardcopy| command sends text to the printer. This can include - syntax highlighting. - Mouse support. |mouse-using| The mouse is supported in the GUI version, in an xterm for Unix, for BSDs with sysmouse, for Linux with gpm, and for Win32. It can be used diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index 53effa1443..bb3b670b24 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -36,9 +36,8 @@ centralized reference of the differences. - 'belloff' defaults to "all" - 'compatible' is always disabled - '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,42 +72,41 @@ centralized reference of the differences. - 'wildmenu' is enabled - 'wildoptions' defaults to "pum,tagfile" -- |man.vim| plugin is enabled, so |:Man| is available by default. -- |matchit| plugin is enabled. To disable it in your config: > +- |man.lua| plugin is enabled, so |:Man| is available by default. +- |matchit| plugin is enabled. To disable it in your config: >vim :let loaded_matchit = 1 - |g:vimsyn_embed| defaults to "l" to enable Lua highlighting - 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: >vim set mouse= -< -- no |popup-menu| but the right button extends selection > +- Pressing <RightMouse> extends selection instead of showing popup-menu: >vim 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: >vim + 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. - +To remove the "How-to disable mouse" menu item and the separator above it: >vim + aunmenu PopUp.How-to\ disable\ mouse + aunmenu PopUp.-1- +< Default Mappings ~ *default-mappings* Nvim creates the following default mappings at |startup|. You can disable any of these in your config by simply removing the mapping, e.g. ":unmap Y". -> +>vim nnoremap Y y$ nnoremap <C-L> <Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR> inoremap <C-U> <C-G>u<C-U> @@ -131,7 +129,7 @@ nvim_cmdwin: ============================================================================== 3. New Features *nvim-features* -MAJOR COMPONENTS ~ +MAJOR COMPONENTS API |API| Job control |job-control| @@ -149,7 +147,7 @@ Terminal emulator |terminal| Vimscript parser |nvim_parse_expression()| XDG base directories |xdg| -USER EXPERIENCE ~ +USER EXPERIENCE Working intuitively and consistently is a major goal of Nvim. @@ -162,7 +160,7 @@ Working intuitively and consistently is a major goal of Nvim. - Nvim avoids features that cannot be provided on all platforms; instead that is delegated to external plugins/extensions. E.g. the `-X` platform-specific option is "sometimes" available in Vim (with potential surprises: - http://stackoverflow.com/q/14635295). + https://stackoverflow.com/q/14635295). - Vim's internal test functions (test_autochdir(), test_settime(), etc.) are not exposed (nor implemented); instead Nvim has a robust API. @@ -180,7 +178,7 @@ Some features are built in that otherwise required external plugins: - Highlighting the yanked region, see |lua-highlight|. -ARCHITECTURE ~ +ARCHITECTURE External plugins run in separate processes. |remote-plugin| This improves stability and allows those plugins to work without blocking the editor. Even @@ -191,7 +189,7 @@ Platform and I/O facilities are built upon libuv. Nvim benefits from libuv features and bug fixes, and other projects benefit from improvements to libuv by Nvim developers. -FEATURES ~ +FEATURES Command-line highlighting: The expression prompt (|@=|, |c_CTRL-R_=|, |i_CTRL-R_=|) is highlighted @@ -210,6 +208,7 @@ Commands: |:match| can be invoked before highlight group is defined |:source| works with Lua User commands can support |:command-preview| to show results as you type + |:write| with "++p" flag creates parent directories. Events: |RecordingEnter| @@ -230,6 +229,7 @@ Functions: |stdpath()| |system()|, |systemlist()| can run {cmd} directly (without 'shell') |matchadd()| can be called before highlight group is defined + |writefile()| with "p" flag creates parent directories. Highlight groups: |highlight-blend| controls blend level for a highlight group @@ -256,9 +256,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 @@ -272,6 +271,7 @@ Options: 'tabline' %@Func@foo%X can call any function on mouse-click 'winblend' pseudo-transparency in floating windows |api-floatwin| 'winhighlight' window-local highlights + 'diffopt' has the option `linematch`. Signs: Signs are removed if the associated line is deleted. @@ -281,7 +281,20 @@ Variables: |v:windowid| is always available (for use by external UIs) ============================================================================== -4. Changed features *nvim-features-changed* +4. Upstreamed features *nvim-upstreamed* + +These Nvim features were later integrated into Vim. + +- 'fillchars' flags: "eob" +- 'wildoptions' flags: "pum" enables popupmenu for wildmode completion +- |<Cmd>| +- |WinClosed| +- |WinScrolled| +- |:sign-define| "numhl" argument +- |:source| works with anonymous (no file) scripts + +============================================================================== +5. Changed features *nvim-features-changed* Nvim always builds with all features, in contrast to Vim which may have certain features removed/added at compile-time. |feature-compile| @@ -306,7 +319,7 @@ are always available and may be used simultaneously. See |provider-python|. structures. 2. |string()| fails immediately on nested containers, not when recursion limit was exceeded. -2. When |:echo| encounters duplicate containers like > +2. When |:echo| encounters duplicate containers like >vim let l = [] echo [l, l] @@ -372,6 +385,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 +404,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,10 +430,12 @@ 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 + 'exrc' searches for ".nvim.lua", ".nvimrc", or ".exrc" files. The user is + prompted whether to trust the file. Shell: Shell output (|:!|, |:make|, …) is always routed through the UI, so it @@ -460,7 +479,7 @@ TUI: < *'term'* *E529* *E530* *E531* 'term' reflects the terminal type derived from |$TERM| and other environment - checks. For debugging only; not reliable during startup. > + checks. For debugging only; not reliable during startup. >vim :echo &term < "builtin_x" means one of the |builtin-terms| was chosen, because the expected terminfo file was not found on the system. @@ -475,6 +494,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| @@ -492,17 +516,20 @@ Working directory (Vim implemented some of these later than Nvim): working directory. Use `getcwd(-1, -1)` to get the global working directory. ============================================================================== -5. Missing legacy features *nvim-features-missing* +6. 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* +7. Removed features *nvim-features-removed* These Vim features were intentionally removed from Nvim. @@ -522,6 +549,7 @@ Aliases: Commands: :fixdel + :hardcopy :helpfind :mode (no longer accepts an argument) :open @@ -533,6 +561,10 @@ Commands: :sleep! (does not hide the cursor; same as :sleep) :smile :tearoff + :cstag + :cscope + :lcscope + :scscope Compile-time features: Emacs tags support @@ -540,6 +572,7 @@ Compile-time features: Eval: Vim9script + *cscope_connection()* *js_encode()* *js_decode()* *v:none* (used by Vim to represent JavaScript "undefined"); use |v:null| instead. @@ -553,7 +586,7 @@ Events: Highlight groups: *hl-StatusLineTerm* *hl-StatusLineTermNC* are unnecessary because Nvim supports 'winhighlight' window-local highlights. - For example, to mimic Vim's StatusLineTerm: > + For example, to mimic Vim's StatusLineTerm: >vim hi StatusLineTerm ctermfg=black ctermbg=green hi StatusLineTermNC ctermfg=green autocmd TermOpen,WinEnter * if &buftype=='terminal' @@ -562,18 +595,25 @@ 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) + cscopepathcomp + cscopeprg + cscopequickfix + cscoperelative + cscopetag + cscopetagorder + cscopeverbose *'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.) @@ -582,7 +622,7 @@ Options: *'imactivatekey'* *'imak'* *'imstatusfunc'* *'imsf'* *'insertmode'* *'im'* Use the following script to emulate 'insertmode': -> +>vim autocmd BufWinEnter * startinsert inoremap <Esc> <C-X><C-Z><C-]> inoremap <C-C> <C-X><C-Z> @@ -614,18 +654,27 @@ 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. + *'printdevice'* + *'printencoding'* + *'printexpr'* + *'printfont'* + *'printheader'* + *'printmbcharset'* *'prompt'* *'noprompt'* *'remap'* *'noremap'* *'restorescreen'* *'rs'* *'norestorescreen'* *'nors'* - 'shelltype' + *'secure'* + Everything is allowed in 'exrc' files since they must be explicitly marked + trusted. + *'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 +682,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 @@ -683,5 +735,14 @@ TUI: at how the terminal is sending CSI. Nvim does not issue such a sequence and always uses 7-bit control sequences. +Cscope: + *cscope* + Cscope support has been removed in favour of LSP based solutions. + +Hardcopy: + *hardcopy* + `:hardcopy` was removed. Instead, use `:TOhtml` and print the resulting HTML + using a web browser or some other HTML viewer. + ============================================================================== vim:tw=78:ts=8:sw=2:et:ft=help:norl: diff --git a/runtime/doc/visual.txt b/runtime/doc/visual.txt index 5383ea4f72..0c6bd4f3a1 100644 --- a/runtime/doc/visual.txt +++ b/runtime/doc/visual.txt @@ -103,7 +103,7 @@ gn Search forward for the last used search pattern, like E.g., "dgn" deletes the text of the next match. If Visual mode is active, extends the selection until the end of the next match. - 'wrapscan' applies + 'wrapscan' applies. Note: Unlike `n` the search direction does not depend on the previous search command. @@ -501,11 +501,11 @@ mode Vim automatically switches to Visual mode, so that the same behavior as in Visual mode is effective. If you don't want this use |:xmap| or |:smap|. One particular edge case: > - :vnoremap <C-K> <Esc> + :vnoremap <C-K> <Esc> This ends Visual mode when in Visual mode, but in Select mode it does not work, because Select mode is restored after executing the mapped keys. You need to use: > - :snoremap <C-K> <Esc> + :snoremap <C-K> <Esc> < Users will expect printable characters to replace the selected area. Therefore avoid mapping printable characters in Select mode. Or use diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 7355cec522..61f5013f47 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, @@ -275,16 +284,15 @@ Opens a vertically split, full-height window on the "tags" file at the far left of the Vim window. +------------------------------------------------------------------------------ Closing a window ----------------- :q[uit] :{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). @@ -595,6 +607,53 @@ it). The minimal height and width of a window is set with 'winminheight' and 'winminwidth'. These are hard values, a window will never become smaller. + +WinScrolled and WinResized autocommands ~ + *win-scrolled-resized* +If you want to get notified of changes in window sizes, the |WinResized| +autocommand event can be used. +If you want to get notified of text in windows scrolling vertically or +horizontally, the |WinScrolled| autocommand event can be used. This will also +trigger in window size changes. +Exception: the events will not be triggered when the text scrolls for +'incsearch'. + *WinResized-event* +The |WinResized| event is triggered after updating the display, several +windows may have changed size then. A list of the IDs of windows that changed +since last time is provided in the v:event.windows variable, for example: + [1003, 1006] + *WinScrolled-event* +The |WinScrolled| event is triggered after |WinResized|, and also if a window +was scrolled. That can be vertically (the text at the top of the window +changed) or horizontally (when 'wrap' is off or when the first displayed part +of the first line changes). Note that |WinScrolled| will trigger many more +times than |WinResized|, it may slow down editing a bit. + +The information provided by |WinScrolled| is a dictionary for each window that +has changes, using the window ID as the key, and a total count of the changes +with the key "all". Example value for |v:event|: + { + all: {width: 0, height: 2, leftcol: 0, skipcol: 0, topline: 1, topfill: 0}, + 1003: {width: 0, height: -1, leftcol: 0, skipcol: 0, topline: 0, topfill: 0}, + 1006: {width: 0, height: 1, leftcol: 0, skipcol: 0, topline: 1, topfill: 0}, + } + +Note that the "all" entry has the absolute values of the individual windows +accumulated. + +If you need more information about what changed, or you want to "debounce" the +events (not handle every event to avoid doing too much work), you may want to +use the `winlayout()` and `getwininfo()` functions. + +|WinScrolled| and |WinResized| do not trigger when the first autocommand is +added, only after the first scroll or resize. They may trigger when switching +to another tab page. + +The commands executed are expected to not cause window size or scroll changes. +If this happens anyway, the event will trigger again very soon. In other +words: Just before triggering the event, the current sizes and scroll +positions are stored and used to decide whether there was a change. + ============================================================================== 7. Argument and buffer list commands *buffer-list* @@ -634,8 +693,8 @@ Note: ":next" is an exception, because it must accept a list of file names for compatibility with Vi. +------------------------------------------------------------------------------ The argument list and multiple windows --------------------------------------- The current position in the argument list can be different for each window. Remember that when doing ":e file", the position in the argument list stays @@ -738,6 +797,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 +825,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..f772785d21 100644 --- a/runtime/filetype.lua +++ b/runtime/filetype.lua @@ -1,12 +1,11 @@ --- Skip if legacy filetype is enabled or filetype detection is disabled -if vim.g.do_legacy_filetype or vim.g.did_load_filetypes then +if vim.g.did_load_filetypes then return end 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 +13,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 deleted file mode 100644 index 52a20d5c10..0000000000 --- a/runtime/filetype.vim +++ /dev/null @@ -1,2612 +0,0 @@ -" Vim support file to detect file types -" -" Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2022 Jul 5 - -" Only run this if enabled -if !exists("do_legacy_filetype") - finish -endif - -" Listen very carefully, I will say this only once -if exists("did_load_filetypes") - finish -endif -let did_load_filetypes = 1 - -" Line continuation is used here, remove 'C' from 'cpoptions' -let s:cpo_save = &cpo -set cpo&vim - -augroup filetypedetect - -" Ignored extensions -if exists("*fnameescape") -au BufNewFile,BufRead ?\+.orig,?\+.bak,?\+.old,?\+.new,?\+.dpkg-dist,?\+.dpkg-old,?\+.dpkg-new,?\+.dpkg-bak,?\+.rpmsave,?\+.rpmnew,?\+.pacsave,?\+.pacnew - \ exe "doau filetypedetect BufRead " . fnameescape(expand("<afile>:r")) -au BufNewFile,BufRead *~ - \ let s:name = expand("<afile>") | - \ let s:short = substitute(s:name, '\~$', '', '') | - \ if s:name != s:short && s:short != "" | - \ exe "doau filetypedetect BufRead " . fnameescape(s:short) | - \ endif | - \ unlet! s:name s:short -au BufNewFile,BufRead ?\+.in - \ if expand("<afile>:t") != "configure.in" | - \ exe "doau filetypedetect BufRead " . fnameescape(expand("<afile>:r")) | - \ endif -elseif &verbose > 0 - echomsg "Warning: some filetypes will not be recognized because this version of Vim does not have fnameescape()" -endif - -" Pattern used to match file names which should not be inspected. -" Currently finds compressed files. -if !exists("g:ft_ignore_pat") - let g:ft_ignore_pat = '\.\(Z\|gz\|bz2\|zip\|tgz\)$' -endif - -" Function used for patterns that end in a star: don't set the filetype if the -" file name matches ft_ignore_pat. -" When using this, the entry should probably be further down below with the -" other StarSetf() calls. -func s:StarSetf(ft) - if expand("<amatch>") !~ g:ft_ignore_pat - exe 'setf ' . a:ft - endif -endfunc - -" Vim help file -au BufNewFile,BufRead $VIMRUNTIME/doc/*.txt setf help - -" Abaqus or Trasys -au BufNewFile,BufRead *.inp call dist#ft#Check_inp() - -" 8th (Firth-derivative) -au BufNewFile,BufRead *.8th setf 8th - -" A-A-P recipe -au BufNewFile,BufRead *.aap setf aap - -" A2ps printing utility -au BufNewFile,BufRead */etc/a2ps.cfg,*/etc/a2ps/*.cfg,a2psrc,.a2psrc setf a2ps - -" ABAB/4 -au BufNewFile,BufRead *.abap setf abap - -" ABC music notation -au BufNewFile,BufRead *.abc setf abc - -" ABEL -au BufNewFile,BufRead *.abl setf abel - -" AceDB -au BufNewFile,BufRead *.wrm setf acedb - -" Ada (83, 9X, 95) -au BufNewFile,BufRead *.adb,*.ads,*.ada setf ada -au BufNewFile,BufRead *.gpr setf ada - -" AHDL -au BufNewFile,BufRead *.tdf setf ahdl - -" AIDL -au BufNewFile,BufRead *.aidl setf aidl - -" AMPL -au BufNewFile,BufRead *.run setf ampl - -" Ant -au BufNewFile,BufRead build.xml setf ant - -" Arduino -au BufNewFile,BufRead *.ino,*.pde setf arduino - -" Apache config file -au BufNewFile,BufRead .htaccess,*/etc/httpd/*.conf setf apache -au BufNewFile,BufRead */etc/apache2/sites-*/*.com setf apache - -" XA65 MOS6510 cross assembler -au BufNewFile,BufRead *.a65 setf a65 - -" Applescript -au BufNewFile,BufRead *.scpt setf applescript - -" Applix ELF -au BufNewFile,BufRead *.am - \ if expand("<afile>") !~? 'Makefile.am\>' | setf elf | endif - -" ALSA configuration -au BufNewFile,BufRead .asoundrc,*/usr/share/alsa/alsa.conf,*/etc/asound.conf setf alsaconf - -" Arc Macro Language -au BufNewFile,BufRead *.aml setf aml - -" APT config file -au BufNewFile,BufRead apt.conf setf aptconf -au BufNewFile,BufRead */.aptitude/config setf aptconf -" more generic pattern far down - -" Arch Inventory file -au BufNewFile,BufRead .arch-inventory,=tagging-method setf arch - -" ART*Enterprise (formerly ART-IM) -au BufNewFile,BufRead *.art setf art - -" AsciiDoc -au BufNewFile,BufRead *.asciidoc,*.adoc setf asciidoc - -" ASN.1 -au BufNewFile,BufRead *.asn,*.asn1 setf asn - -" Active Server Pages (with Visual Basic Script) -au BufNewFile,BufRead *.asa - \ if exists("g:filetype_asa") | - \ exe "setf " . g:filetype_asa | - \ else | - \ setf aspvbs | - \ endif - -" Active Server Pages (with Perl or Visual Basic Script) -au BufNewFile,BufRead *.asp - \ if exists("g:filetype_asp") | - \ exe "setf " . g:filetype_asp | - \ elseif getline(1) . getline(2) . getline(3) =~? "perlscript" | - \ setf aspperl | - \ else | - \ setf aspvbs | - \ endif - -" Grub (must be before pattern *.lst) -au BufNewFile,BufRead */boot/grub/menu.lst,*/boot/grub/grub.conf,*/etc/grub.conf setf grub - -" Maxima, see: -" https://maxima.sourceforge.io/docs/manual/maxima_71.html#file_005ftype_005fmaxima -" Must be before the pattern *.mac. -" *.dem omitted - also used by gnuplot demos -" *.mc omitted - used by dist#ft#McSetf() -au BufNewFile,BufRead *.demo,*.dm{1,2,3,t},*.wxm,maxima-init.mac setf maxima - -" Assembly (all kinds) -" *.lst is not pure assembly, it has two extra columns (address, byte codes) -au BufNewFile,BufRead *.asm,*.[sS],*.[aA],*.mac,*.lst call dist#ft#FTasm() - -" Assembly - Macro (VAX) -au BufNewFile,BufRead *.mar setf vmasm - -" Astro -au BufNewFile,BufRead *.astro setf astro - -" Atlas -au BufNewFile,BufRead *.atl,*.as setf atlas - -" Atom is based on XML -au BufNewFile,BufRead *.atom setf xml - -" Autoit v3 -au BufNewFile,BufRead *.au3 setf autoit - -" Autohotkey -au BufNewFile,BufRead *.ahk setf autohotkey - -" Automake -au BufNewFile,BufRead [mM]akefile.am,GNUmakefile.am setf automake - -" Autotest .at files are actually m4 -au BufNewFile,BufRead *.at setf m4 - -" Avenue -au BufNewFile,BufRead *.ave setf ave - -" Awk -au BufNewFile,BufRead *.awk,*.gawk setf awk - -" B -au BufNewFile,BufRead *.mch,*.ref,*.imp setf b - -" BASIC or Visual Basic -au BufNewFile,BufRead *.bas call dist#ft#FTbas() -au BufNewFile,BufRead *.bi,*.bm call dist#ft#FTbas() - -" Visual Basic Script (close to Visual Basic) or Visual Basic .NET -au BufNewFile,BufRead *.vb,*.vbs,*.dsm,*.ctl setf vb - -" IBasic file (similar to QBasic) -au BufNewFile,BufRead *.iba,*.ibi setf ibasic - -" FreeBasic file (similar to QBasic) -au BufNewFile,BufRead *.fb setf freebasic - -" Batch file for MSDOS. See dist#ft#FTsys for *.sys -au BufNewFile,BufRead *.bat setf dosbatch -" *.cmd is close to a Batch file, but on OS/2 Rexx files also use *.cmd. -au BufNewFile,BufRead *.cmd - \ if getline(1) =~ '^/\*' | setf rexx | else | setf dosbatch | endif -" ABB RAPID or Batch file for MSDOS. -au BufNewFile,BufRead *.sys\c call dist#ft#FTsys() - -" Batch file for 4DOS -au BufNewFile,BufRead *.btm call dist#ft#FTbtm() - -" BC calculator -au BufNewFile,BufRead *.bc setf bc - -" BDF font -au BufNewFile,BufRead *.bdf setf bdf - -" Beancount -au BufNewFile,BufRead *.beancount setf beancount - -" BibTeX bibliography database file -au BufNewFile,BufRead *.bib setf bib - -" BibTeX Bibliography Style -au BufNewFile,BufRead *.bst setf bst - -" Bicep -au BufNewFile,BufRead *.bicep setf bicep - -" BIND configuration -" sudoedit uses namedXXXX.conf -au BufNewFile,BufRead named*.conf,rndc*.conf,rndc*.key setf named - -" BIND zone -au BufNewFile,BufRead named.root setf bindzone -au BufNewFile,BufRead *.db call dist#ft#BindzoneCheck('') - -" Blank -au BufNewFile,BufRead *.bl setf blank - -" Bitbake -au BufNewFile,BufRead *.bb,*.bbappend,*.bbclass,*/build/conf/*.conf,*/meta{-*,}/conf/*.conf setf bitbake - -" Blkid cache file -au BufNewFile,BufRead */etc/blkid.tab,*/etc/blkid.tab.old setf xml - -" BSDL -au BufNewFile,BufRead *.bsd,*.bsdl setf bsdl - -" Bazel (http://bazel.io) -autocmd BufRead,BufNewFile *.bzl,*.bazel,WORKSPACE setf bzl -if has("fname_case") - " There is another check for BUILD further below. - autocmd BufRead,BufNewFile *.BUILD,BUILD setf bzl -endif - -" C or lpc -au BufNewFile,BufRead *.c call dist#ft#FTlpc() -au BufNewFile,BufRead *.lpc,*.ulpc setf lpc - -" Calendar -au BufNewFile,BufRead calendar setf calendar - -" C# -au BufNewFile,BufRead *.cs,*.csx setf cs - -" CSDL -au BufNewFile,BufRead *.csdl setf csdl - -" Cabal -au BufNewFile,BufRead *.cabal setf cabal - -" Cdrdao TOC -au BufNewFile,BufRead *.toc setf cdrtoc - -" Cdrdao config -au BufNewFile,BufRead */etc/cdrdao.conf,*/etc/defaults/cdrdao,*/etc/default/cdrdao,.cdrdao setf cdrdaoconf - -" Cfengine -au BufNewFile,BufRead cfengine.conf setf cfengine - -" ChaiScript -au BufRead,BufNewFile *.chai setf chaiscript - -" Comshare Dimension Definition Language -au BufNewFile,BufRead *.cdl setf cdl - -" Conary Recipe -au BufNewFile,BufRead *.recipe setf conaryrecipe - -" Controllable Regex Mutilator -au BufNewFile,BufRead *.crm setf crm - -" Cyn++ -au BufNewFile,BufRead *.cyn setf cynpp - -" Cynlib -" .cc and .cpp files can be C++ or Cynlib. -au BufNewFile,BufRead *.cc - \ if exists("cynlib_syntax_for_cc")|setf cynlib|else|setf cpp|endif -au BufNewFile,BufRead *.cpp - \ if exists("cynlib_syntax_for_cpp")|setf cynlib|else|setf cpp|endif - -" C++ -au BufNewFile,BufRead *.cxx,*.c++,*.hh,*.hxx,*.hpp,*.ipp,*.moc,*.tcc,*.inl setf cpp -if has("fname_case") - au BufNewFile,BufRead *.C,*.H setf cpp -endif - -" .h files can be C, Ch C++, ObjC or ObjC++. -" Set c_syntax_for_h if you want C, ch_syntax_for_h if you want Ch. ObjC is -" detected automatically. -au BufNewFile,BufRead *.h call dist#ft#FTheader() - -" Ch (CHscript) -au BufNewFile,BufRead *.chf setf ch - -" TLH files are C++ headers generated by Visual C++'s #import from typelibs -au BufNewFile,BufRead *.tlh setf cpp - -" Cascading Style Sheets -au BufNewFile,BufRead *.css setf css - -" Century Term Command Scripts (*.cmd too) -au BufNewFile,BufRead *.con setf cterm - -" Changelog -au BufNewFile,BufRead changelog.Debian,changelog.dch,NEWS.Debian,NEWS.dch,*/debian/changelog - \ setf debchangelog - -au BufNewFile,BufRead [cC]hange[lL]og - \ if getline(1) =~ '; urgency=' - \| setf debchangelog - \| else - \| setf changelog - \| endif - -au BufNewFile,BufRead NEWS - \ if getline(1) =~ '; urgency=' - \| setf debchangelog - \| endif - -" CHILL -au BufNewFile,BufRead *..ch setf chill - -" Changes for WEB and CWEB or CHILL -au BufNewFile,BufRead *.ch call dist#ft#FTchange() - -" ChordPro -au BufNewFile,BufRead *.chopro,*.crd,*.cho,*.crdpro,*.chordpro setf chordpro - -" Clean -au BufNewFile,BufRead *.dcl,*.icl setf clean - -" Clever -au BufNewFile,BufRead *.eni setf cl - -" Clever or dtd -au BufNewFile,BufRead *.ent call dist#ft#FTent() - -" Clipper, FoxPro, ABB RAPID or eviews -au BufNewFile,BufRead *.prg\c call dist#ft#FTprg() - -" Clojure -au BufNewFile,BufRead *.clj,*.cljs,*.cljx,*.cljc setf clojure - -" Cmake -au BufNewFile,BufRead CMakeLists.txt,*.cmake,*.cmake.in setf cmake - -" Cmusrc -au BufNewFile,BufRead */.cmus/{autosave,rc,command-history,*.theme} setf cmusrc -au BufNewFile,BufRead */cmus/{rc,*.theme} setf cmusrc - -" Cobol -au BufNewFile,BufRead *.cbl,*.cob,*.lib setf cobol -" cobol or zope form controller python script? (heuristic) -au BufNewFile,BufRead *.cpy - \ if getline(1) =~ '^##' | - \ setf python | - \ else | - \ setf cobol | - \ endif - -" Coco/R -au BufNewFile,BufRead *.atg setf coco - -" Cold Fusion -au BufNewFile,BufRead *.cfm,*.cfi,*.cfc setf cf - -" Configure scripts -au BufNewFile,BufRead configure.in,configure.ac setf config - -" Cooklang -au BufNewFile,BufRead *.cook setf cook - -" CSV Files -au BufNewFile,BufRead *.csv setf csv - -" CUDA Compute Unified Device Architecture -au BufNewFile,BufRead *.cu,*.cuh setf cuda - -" Dockerfile; Podman uses the same syntax with name Containerfile -" Also see Dockerfile.* below. -au BufNewFile,BufRead Containerfile,Dockerfile,dockerfile,*.[dD]ockerfile setf dockerfile - -" WildPackets EtherPeek Decoder -au BufNewFile,BufRead *.dcd setf dcd - -" Enlightenment configuration files -au BufNewFile,BufRead *enlightenment/*.cfg setf c - -" Eterm -au BufNewFile,BufRead *Eterm/*.cfg setf eterm - -" Elixir or Euphoria -au BufNewFile,BufRead *.ex call dist#ft#ExCheck() - -" Elixir -au BufRead,BufNewFile mix.lock,*.exs setf elixir -au BufRead,BufNewFile *.eex,*.leex setf eelixir - -" Elvish -au BufRead,BufNewFile *.elv setf elvish - -" Euphoria 3 or 4 -au BufNewFile,BufRead *.eu,*.ew,*.exu,*.exw call dist#ft#EuphoriaCheck() -if has("fname_case") - au BufNewFile,BufRead *.EU,*.EW,*.EX,*.EXU,*.EXW call dist#ft#EuphoriaCheck() -endif - -" Lynx config files -au BufNewFile,BufRead lynx.cfg setf lynx - -" 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 - -" Quake -au BufNewFile,BufRead *baseq[2-3]/*.cfg,*id1/*.cfg setf quake -au BufNewFile,BufRead *quake[1-3]/*.cfg setf quake - -" Quake C -au BufNewFile,BufRead *.qc setf c - -" Configure files -au BufNewFile,BufRead *.cfg\c call dist#ft#FTcfg() - -" Cucumber -au BufNewFile,BufRead *.feature setf cucumber - -" Communicating Sequential Processes -au BufNewFile,BufRead *.csp,*.fdr setf csp - -" CUPL logic description and simulation -au BufNewFile,BufRead *.pld setf cupl -au BufNewFile,BufRead *.si setf cuplsim - -" Dart -au BufRead,BufNewfile *.dart,*.drt setf dart - -" Debian Control -au BufNewFile,BufRead */debian/control setf debcontrol -au BufNewFile,BufRead control - \ if getline(1) =~ '^Source:' - \| setf debcontrol - \| endif - -" Debian Copyright -au BufNewFile,BufRead */debian/copyright setf debcopyright -au BufNewFile,BufRead copyright - \ if getline(1) =~ '^Format:' - \| setf debcopyright - \| endif - -" Debian Sources.list -au BufNewFile,BufRead */etc/apt/sources.list setf debsources -au BufNewFile,BufRead */etc/apt/sources.list.d/*.list setf debsources - -" Deny hosts -au BufNewFile,BufRead denyhosts.conf setf denyhosts - -" dnsmasq(8) configuration files -au BufNewFile,BufRead */etc/dnsmasq.conf setf dnsmasq - -" ROCKLinux package description -au BufNewFile,BufRead *.desc setf desc - -" the D language or dtrace -au BufNewFile,BufRead */dtrace/*.d setf dtrace -au BufNewFile,BufRead *.d call dist#ft#DtraceCheck() - -" Desktop files -au BufNewFile,BufRead *.desktop,*.directory setf desktop - -" Dict config -au BufNewFile,BufRead dict.conf,.dictrc setf dictconf - -" Dictd config -au BufNewFile,BufRead dictd*.conf setf dictdconf - -" DEP3 formatted patch files -au BufNewFile,BufRead */debian/patches/* call dist#ft#Dep3patch() - -" Diff files -au BufNewFile,BufRead *.diff,*.rej setf diff -au BufNewFile,BufRead *.patch - \ if getline(1) =~# '^From [0-9a-f]\{40,\} Mon Sep 17 00:00:00 2001$' | - \ setf gitsendemail | - \ else | - \ setf diff | - \ endif - -" Dircolors -au BufNewFile,BufRead .dir_colors,.dircolors,*/etc/DIR_COLORS setf dircolors - -" Diva (with Skill) or InstallShield -au BufNewFile,BufRead *.rul - \ if getline(1).getline(2).getline(3).getline(4).getline(5).getline(6) =~? 'InstallShield' | - \ setf ishd | - \ else | - \ setf diva | - \ endif - -" DCL (Digital Command Language - vms) or DNS zone file -au BufNewFile,BufRead *.com call dist#ft#BindzoneCheck('dcl') - -" DOT -au BufNewFile,BufRead *.dot,*.gv setf dot - -" Dune -au BufNewFile,BufRead jbuild,dune,dune-project,dune-workspace setf dune - -" Dylan - lid files -au BufNewFile,BufRead *.lid setf dylanlid - -" Dylan - intr files (melange) -au BufNewFile,BufRead *.intr setf dylanintr - -" Dylan -au BufNewFile,BufRead *.dylan setf dylan - -" Microsoft Module Definition -au BufNewFile,BufRead *.def setf def - -" Dracula -au BufNewFile,BufRead *.drac,*.drc,*lvs,*lpe setf dracula - -" Datascript -au BufNewFile,BufRead *.ds setf datascript - -" dsl: DSSSL or Structurizr -au BufNewFile,BufRead *.dsl - \ if getline(1) =~ '^\s*<\!' | - \ setf dsl | - \ else | - \ setf structurizr | - \ endif - -" DTD (Document Type Definition for XML) -au BufNewFile,BufRead *.dtd setf dtd - -" DTS/DSTI (device tree files) -au BufNewFile,BufRead *.dts,*.dtsi setf dts - -" EDIF (*.edf,*.edif,*.edn,*.edo) or edn -au BufNewFile,BufRead *.ed\(f\|if\|o\) setf edif -au BufNewFile,BufRead *.edn - \ if getline(1) =~ '^\s*(\s*edif\>' | - \ setf edif | - \ else | - \ setf clojure | - \ endif - -" EditorConfig (close enough to dosini) -au BufNewFile,BufRead .editorconfig setf dosini - -" Embedix Component Description -au BufNewFile,BufRead *.ecd setf ecd - -" Eiffel or Specman or Euphoria -au BufNewFile,BufRead *.e,*.E call dist#ft#FTe() - -" Elinks configuration -au BufNewFile,BufRead elinks.conf setf elinks - -" ERicsson LANGuage; Yaws is erlang too -au BufNewFile,BufRead *.erl,*.hrl,*.yaws setf erlang - -" Elm -au BufNewFile,BufRead *.elm setf elm - -" Elm Filter Rules file -au BufNewFile,BufRead filter-rules setf elmfilt - -" ESMTP rc file -au BufNewFile,BufRead *esmtprc setf esmtprc - -" ESQL-C -au BufNewFile,BufRead *.ec,*.EC setf esqlc - -" Esterel -au BufNewFile,BufRead *.strl setf esterel - -" Essbase script -au BufNewFile,BufRead *.csc setf csc - -" Exim -au BufNewFile,BufRead exim.conf setf exim - -" Expect -au BufNewFile,BufRead *.exp setf expect - -" Exports -au BufNewFile,BufRead exports setf exports - -" Falcon -au BufNewFile,BufRead *.fal setf falcon - -" Fantom -au BufNewFile,BufRead *.fan,*.fwt setf fan - -" Factor -au BufNewFile,BufRead *.factor setf factor - -" Fennel -autocmd BufRead,BufNewFile *.fnl setf fennel - -" Fetchmail RC file -au BufNewFile,BufRead .fetchmailrc setf fetchmail - -" Fish shell -au BufNewFile,BufRead *.fish setf fish - -" FlexWiki - disabled, because it has side effects when a .wiki file -" is not actually FlexWiki -"au BufNewFile,BufRead *.wiki setf flexwiki - -" Focus Executable -au BufNewFile,BufRead *.fex,*.focexec setf focexec - -" Focus Master file (but not for auto.master) -au BufNewFile,BufRead auto.master setf conf -au BufNewFile,BufRead *.mas,*.master setf master - -" Forth -au BufNewFile,BufRead *.ft,*.fth setf forth - -" Reva Forth -au BufNewFile,BufRead *.frt setf reva - -" Fortran -if has("fname_case") - au BufNewFile,BufRead *.F,*.FOR,*.FPP,*.FTN,*.F77,*.F90,*.F95,*.F03,*.F08 setf fortran -endif -au BufNewFile,BufRead *.f,*.for,*.fortran,*.fpp,*.ftn,*.f77,*.f90,*.f95,*.f03,*.f08 setf fortran - -" Framescript -au BufNewFile,BufRead *.fsl setf framescript - -" FStab -au BufNewFile,BufRead fstab,mtab setf fstab - -" Fusion -au BufRead,BufNewFile *.fusion setf fusion - -" F# or Forth -au BufNewFile,BufRead *.fs call dist#ft#FTfs() - -" F# -au BufNewFile,BufRead *.fsi,*.fsx setf fsharp - -" GDB command files -au BufNewFile,BufRead .gdbinit,gdbinit,.gdbearlyinit,gdbearlyinit,*.gdb setf gdb - -" GDMO -au BufNewFile,BufRead *.mo,*.gdmo setf gdmo - -" GDscript -au BufNewFile,BufRead *.gd setf gdscript - -" Godot resource -au BufRead,BufNewFile *.tscn,*.tres setf gdresource - -" Gedcom -au BufNewFile,BufRead *.ged,lltxxxxx.txt setf gedcom - -" Gemtext -au BufNewFile,BufRead *.gmi,*.gemini setf gemtext - -" Gift (Moodle) -autocmd BufRead,BufNewFile *.gift setf gift - -" Git -au BufNewFile,BufRead COMMIT_EDITMSG,MERGE_MSG,TAG_EDITMSG setf gitcommit -au BufNewFile,BufRead NOTES_EDITMSG,EDIT_DESCRIPTION setf gitcommit -au BufNewFile,BufRead *.git/config,.gitconfig,*/etc/gitconfig setf gitconfig -au BufNewFile,BufRead */.config/git/config setf gitconfig -au BufNewFile,BufRead *.git/config.worktree setf gitconfig -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 -endif -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 | - \ endif - -" Gkrellmrc -au BufNewFile,BufRead gkrellmrc,gkrellmrc_? setf gkrellmrc - -" Gleam -au BufNewFile,BufRead *.gleam setf gleam - -" GLSL -au BufNewFile,BufRead *.glsl setf glsl - -" GP scripts (2.0 and onward) -au BufNewFile,BufRead *.gp,.gprc setf gp - -" GPG -au BufNewFile,BufRead */.gnupg/options setf gpg -au BufNewFile,BufRead */.gnupg/gpg.conf setf gpg -au BufNewFile,BufRead */usr/*/gnupg/options.skel setf gpg -if !empty($GNUPGHOME) - au BufNewFile,BufRead $GNUPGHOME/options setf gpg - au BufNewFile,BufRead $GNUPGHOME/gpg.conf setf gpg -endif - -" gnash(1) configuration files -au BufNewFile,BufRead gnashrc,.gnashrc,gnashpluginrc,.gnashpluginrc setf gnash - -" Gitolite -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 - -" Gnuplot scripts -au BufNewFile,BufRead *.gpi,.gnuplot setf gnuplot - -" Go (Google) -au BufNewFile,BufRead *.go setf go -au BufNewFile,BufRead Gopkg.lock setf toml -au BufRead,BufNewFile go.work setf gowork - -" GrADS scripts -au BufNewFile,BufRead *.gs setf grads - -" GraphQL -au BufNewFile,BufRead *.graphql,*.graphqls,*.gql setf graphql - -" Gretl -au BufNewFile,BufRead *.gretl setf gretl - -" Groovy -au BufNewFile,BufRead *.gradle,*.groovy setf groovy - -" GNU Server Pages -au BufNewFile,BufRead *.gsp setf gsp - -" Group file -au BufNewFile,BufRead */etc/group,*/etc/group-,*/etc/group.edit,*/etc/gshadow,*/etc/gshadow-,*/etc/gshadow.edit,*/var/backups/group.bak,*/var/backups/gshadow.bak setf group - -" GTK RC -au BufNewFile,BufRead .gtkrc,gtkrc setf gtkrc - -" Hack -au BufRead,BufNewFile *.hack,*.hackpartial setf hack - -" Haml -au BufNewFile,BufRead *.haml setf haml - -" Hamster Classic | Playground files -au BufNewFile,BufRead *.hsm setf hamster - -" Handlebars -au BufNewFile,BufRead *.hbs setf handlebars - -" Hare -au BufNewFile,BufRead *.ha setf hare - -" Haskell -au BufNewFile,BufRead *.hs,*.hsc,*.hs-boot,*.hsig setf haskell -au BufNewFile,BufRead *.lhs setf lhaskell -au BufNewFile,BufRead *.chs setf chaskell -au BufNewFile,BufRead cabal.project setf cabalproject -au BufNewFile,BufRead $HOME/.cabal/config setf cabalconfig -au BufNewFile,BufRead cabal.config setf cabalconfig - -" Haste -au BufNewFile,BufRead *.ht setf haste -au BufNewFile,BufRead *.htpp setf hastepreproc - -" HCL -au BufRead,BufNewFile *.hcl setf hcl - -" Hercules -au BufNewFile,BufRead *.vc,*.ev,*.sum,*.errsum setf hercules - -" HEEx -au BufRead,BufNewFile *.heex setf heex - -" HEX (Intel) -au BufNewFile,BufRead *.hex,*.h32 setf hex - -" Hjson -au BufNewFile,BufRead *.hjson setf hjson - -" Hollywood -au BufRead,BufNewFile *.hws setf hollywood - -" Hoon -au BufRead,BufNewFile *.hoon setf hoon - -" Tilde (must be before HTML) -au BufNewFile,BufRead *.t.html setf tilde - -" HTML (.shtml and .stm for server side) -au BufNewFile,BufRead *.html,*.htm,*.shtml,*.stm call dist#ft#FThtml() -au BufNewFile,BufRead *.cshtml setf html - -" HTML with Ruby - eRuby -au BufNewFile,BufRead *.erb,*.rhtml setf eruby - -" HTML with M4 -au BufNewFile,BufRead *.html.m4 setf htmlm4 - -" Some template. Used to be HTML Cheetah. -au BufNewFile,BufRead *.tmpl setf template - -" Host config -au BufNewFile,BufRead */etc/host.conf setf hostconf - -" Hosts access -au BufNewFile,BufRead */etc/hosts.allow,*/etc/hosts.deny setf hostsaccess - -" Hyper Builder -au BufNewFile,BufRead *.hb setf hb - -" Httest -au BufNewFile,BufRead *.htt,*.htb setf httest - -" i3 -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 - -" Icon -au BufNewFile,BufRead *.icn setf icon - -" IDL (Interface Description Language) -au BufNewFile,BufRead *.idl call dist#ft#FTidl() - -" Microsoft IDL (Interface Description Language) Also *.idl -" MOF = WMI (Windows Management Instrumentation) Managed Object Format -au BufNewFile,BufRead *.odl,*.mof setf msidl - -" Icewm menu -au BufNewFile,BufRead */.icewm/menu setf icemenu - -" Indent profile (must come before IDL *.pro!) -au BufNewFile,BufRead .indent.pro setf indent -au BufNewFile,BufRead indent.pro call dist#ft#ProtoCheck('indent') - -" IDL (Interactive Data Language) -au BufNewFile,BufRead *.pro call dist#ft#ProtoCheck('idlang') - -" Indent RC -au BufNewFile,BufRead indentrc setf indent - -" Inform -au BufNewFile,BufRead *.inf,*.INF setf inform - -" Initng -au BufNewFile,BufRead */etc/initng/*/*.i,*.ii setf initng - -" Innovation Data Processing -au BufRead,BufNewFile upstream.dat\c,upstream.*.dat\c,*.upstream.dat\c setf upstreamdat -au BufRead,BufNewFile fdrupstream.log,upstream.log\c,upstream.*.log\c,*.upstream.log\c,UPSTREAM-*.log\c setf upstreamlog -au BufRead,BufNewFile upstreaminstall.log\c,upstreaminstall.*.log\c,*.upstreaminstall.log\c setf upstreaminstalllog -au BufRead,BufNewFile usserver.log\c,usserver.*.log\c,*.usserver.log\c setf usserverlog -au BufRead,BufNewFile usw2kagt.log\c,usw2kagt.*.log\c,*.usw2kagt.log\c setf usw2kagtlog - -" Ipfilter -au BufNewFile,BufRead ipf.conf,ipf6.conf,ipf.rules setf ipfilter - -" Informix 4GL (source - canonical, include file, I4GL+M4 preproc.) -au BufNewFile,BufRead *.4gl,*.4gh,*.m4gl setf fgl - -" .INI file for MSDOS -au BufNewFile,BufRead *.ini setf dosini - -" SysV Inittab -au BufNewFile,BufRead inittab setf inittab - -" Inno Setup -au BufNewFile,BufRead *.iss setf iss - -" J -au BufNewFile,BufRead *.ijs setf j - -" JAL -au BufNewFile,BufRead *.jal,*.JAL setf jal - -" Jam -au BufNewFile,BufRead *.jpl,*.jpr setf jam - -" Java -au BufNewFile,BufRead *.java,*.jav setf java - -" JavaCC -au BufNewFile,BufRead *.jj,*.jjt setf javacc - -" JavaScript, ECMAScript, ES module script, CommonJS script -au BufNewFile,BufRead *.js,*.javascript,*.es,*.mjs,*.cjs setf javascript - -" JavaScript with React -au BufNewFile,BufRead *.jsx setf javascriptreact - -" Java Server Pages -au BufNewFile,BufRead *.jsp setf jsp - -" Java Properties resource file (note: doesn't catch font.properties.pl) -au BufNewFile,BufRead *.properties,*.properties_??,*.properties_??_?? setf jproperties - -" Jess -au BufNewFile,BufRead *.clp setf jess - -" Jgraph -au BufNewFile,BufRead *.jgr setf jgraph - -" Jovial -au BufNewFile,BufRead *.jov,*.j73,*.jovial setf jovial - -" JSON -au BufNewFile,BufRead *.json,*.jsonp,*.webmanifest setf json - -" JSON5 -au BufNewFile,BufRead *.json5 setf json5 - -" JSON Patch (RFC 6902) -au BufNewFile,BufRead *.json-patch setf json - -" Jupyter Notebook is also json -au BufNewFile,BufRead *.ipynb setf json - -" Other files that look like json -au BufNewFile,BufRead .babelrc,.eslintrc,.prettierrc,.firebaserc setf json - -" JSONC -au BufNewFile,BufRead *.jsonc setf jsonc - -" Julia -au BufNewFile,BufRead *.jl setf julia - -" Kixtart -au BufNewFile,BufRead *.kix setf kix - -" Kuka Robot Language -au BufNewFile,BufRead *.src\c call dist#ft#FTsrc() -au BufNewFile,BufRead *.dat\c call dist#ft#FTdat() -au BufNewFile,BufRead *.sub\c setf krl - -" Kimwitu[++] -au BufNewFile,BufRead *.k setf kwt - -" Kivy -au BufNewFile,BufRead *.kv setf kivy - -" Kotlin -au BufNewFile,BufRead *.kt,*.ktm,*.kts setf kotlin - -" KDE script -au BufNewFile,BufRead *.ks setf kscript - -" Kconfig -au BufNewFile,BufRead Kconfig,Kconfig.debug setf kconfig - -" Lace (ISE) -au BufNewFile,BufRead *.ace,*.ACE setf lace - -" Latte -au BufNewFile,BufRead *.latte,*.lte setf latte - -" Limits -au BufNewFile,BufRead */etc/limits,*/etc/*limits.conf,*/etc/*limits.d/*.conf setf limits - -" LambdaProlog or SML (see dist#ft#FTmod for *.mod) -au BufNewFile,BufRead *.sig call dist#ft#FTsig() - -" LDAP LDIF -au BufNewFile,BufRead *.ldif setf ldif - -" Ld loader -au BufNewFile,BufRead *.ld setf ld - -" Ledger -au BufRead,BufNewFile *.ldg,*.ledger,*.journal setf ledger - -" Less -au BufNewFile,BufRead *.less setf less - -" Lex -au BufNewFile,BufRead *.lex,*.l,*.lxx,*.l++ setf lex - -" Libao -au BufNewFile,BufRead */etc/libao.conf,*/.libao setf libao - -" Libsensors -au BufNewFile,BufRead */etc/sensors.conf,*/etc/sensors3.conf setf sensors - -" LFTP -au BufNewFile,BufRead lftp.conf,.lftprc,*lftp/rc setf lftp - -" Lifelines (or Lex for C++!) -au BufNewFile,BufRead *.ll setf lifelines - -" Lilo: Linux loader -au BufNewFile,BufRead lilo.conf setf lilo - -" Lilypond -au BufNewFile,BufRead *.ly,*.ily setf lilypond - -" Lisp (*.el = ELisp, *.cl = Common Lisp) -" *.jl was removed, it's also used for Julia, better skip than guess wrong. -if has("fname_case") - au BufNewFile,BufRead *.lsp,*.lisp,*.asd,*.el,*.cl,*.L,.emacs,.sawfishrc setf lisp -else - au BufNewFile,BufRead *.lsp,*.lisp,*.asd,*.el,*.cl,.emacs,.sawfishrc setf lisp -endif - -" SBCL implementation of Common Lisp -au BufNewFile,BufRead sbclrc,.sbclrc setf lisp - -" Liquid -au BufNewFile,BufRead *.liquid setf liquid - -" Lite -au BufNewFile,BufRead *.lite,*.lt setf lite - -" LiteStep RC files -au BufNewFile,BufRead */LiteStep/*/*.rc setf litestep - -" Login access -au BufNewFile,BufRead */etc/login.access setf loginaccess - -" Login defs -au BufNewFile,BufRead */etc/login.defs setf logindefs - -" Logtalk -au BufNewFile,BufRead *.lgt setf logtalk - -" LOTOS -au BufNewFile,BufRead *.lot,*.lotos setf lotos - -" Lout (also: *.lt) -au BufNewFile,BufRead *.lou,*.lout setf lout - -" Lua -au BufNewFile,BufRead *.lua setf lua - -" Luarocks -au BufNewFile,BufRead *.rockspec setf lua - -" Linden Scripting Language (Second Life) -au BufNewFile,BufRead *.lsl setf lsl - -" Lynx style file (or LotusScript!) -au BufNewFile,BufRead *.lss setf lss - -" M4 -au BufNewFile,BufRead *.m4 - \ if expand("<afile>") !~? 'html.m4$\|fvwm2rc' | setf m4 | endif - -" MaGic Point -au BufNewFile,BufRead *.mgp setf mgp - -" Mail (for Elm, trn, mutt, muttng, rn, slrn, neomutt) -au BufNewFile,BufRead snd.\d\+,.letter,.letter.\d\+,.followup,.article,.article.\d\+,pico.\d\+,mutt{ng,}-*-\w\+,mutt[[:alnum:]_-]\\\{6\},neomutt-*-\w\+,neomutt[[:alnum:]_-]\\\{6\},ae\d\+.txt,/tmp/SLRN[0-9A-Z.]\+,*.eml setf mail - -" Mail aliases -au BufNewFile,BufRead */etc/mail/aliases,*/etc/aliases setf mailaliases - -" Mailcap configuration file -au BufNewFile,BufRead .mailcap,mailcap setf mailcap - -" Makefile -au BufNewFile,BufRead *[mM]akefile,*.mk,*.mak,*.dsp setf make - -" MakeIndex -au BufNewFile,BufRead *.ist,*.mst setf ist - -" Mallard -au BufNewFile,BufRead *.page setf mallard - -" Manpage -au BufNewFile,BufRead *.man setf nroff - -" Man config -au BufNewFile,BufRead */etc/man.conf,man.config setf manconf - -" Maple V -au BufNewFile,BufRead *.mv,*.mpl,*.mws setf maple - -" Map (UMN mapserver config file) -au BufNewFile,BufRead *.map setf map - -" Markdown -au BufNewFile,BufRead *.markdown,*.mdown,*.mkd,*.mkdn,*.mdwn,*.md setf markdown - -" Mason -au BufNewFile,BufRead *.mason,*.mhtml,*.comp setf mason - -" Mathematica, Matlab, Murphi, Objective C or Octave -au BufNewFile,BufRead *.m call dist#ft#FTm() - -" Mathematica notebook -au BufNewFile,BufRead *.nb setf mma - -" Maya Extension Language -au BufNewFile,BufRead *.mel setf mel - -" Mercurial (hg) commit file -au BufNewFile,BufRead hg-editor-*.txt setf hgcommit - -" Mercurial config (looks like generic config file) -au BufNewFile,BufRead *.hgrc,*hgrc setf cfg - -" Meson Build system config -au BufNewFile,BufRead meson.build,meson_options.txt setf meson -au BufNewFile,BufRead *.wrap setf dosini - -" Messages (logs mostly) -au BufNewFile,BufRead */log/{auth,cron,daemon,debug,kern,lpr,mail,messages,news/news,syslog,user}{,.log,.err,.info,.warn,.crit,.notice}{,.[0-9]*,-[0-9]*} setf messages - -" Metafont -au BufNewFile,BufRead *.mf setf mf - -" MetaPost -au BufNewFile,BufRead *.mp setf mp -au BufNewFile,BufRead *.mpxl,*.mpiv,*.mpvi let b:mp_metafun = 1 | setf mp - -" MGL -au BufNewFile,BufRead *.mgl setf mgl - -" MIX - Knuth assembly -au BufNewFile,BufRead *.mix,*.mixal setf mix - -" MMIX or VMS makefile -au BufNewFile,BufRead *.mms call dist#ft#FTmms() - -" Symbian meta-makefile definition (MMP) -au BufNewFile,BufRead *.mmp setf mmp - -" ABB Rapid, Modula-2, Modsim III or LambdaProlog -au BufNewFile,BufRead *.mod\c call dist#ft#FTmod() - -" Modula-2 (.md removed in favor of Markdown, see dist#ft#FTmod for *.MOD) -au BufNewFile,BufRead *.m2,*.DEF,*.mi setf modula2 - -" Modula-3 (.m3, .i3, .mg, .ig) -au BufNewFile,BufRead *.[mi][3g] setf modula3 - -" Monk -au BufNewFile,BufRead *.isc,*.monk,*.ssc,*.tsc setf monk - -" MOO -au BufNewFile,BufRead *.moo setf moo - -" Moonscript -au BufNewFile,BufRead *.moon setf moonscript - -" Modconf -au BufNewFile,BufRead */etc/modules.conf,*/etc/modules,*/etc/conf.modules setf modconf - -" MPD is based on XML -au BufNewFile,BufRead *.mpd setf xml - -" Mplayer config -au BufNewFile,BufRead mplayer.conf,*/.mplayer/config setf mplayerconf - -" Motorola S record -au BufNewFile,BufRead *.s19,*.s28,*.s37,*.mot,*.srec setf srec - -" Mrxvtrc -au BufNewFile,BufRead mrxvtrc,.mrxvtrc setf mrxvtrc - -" Msql -au BufNewFile,BufRead *.msql setf msql - -" Mysql -au BufNewFile,BufRead *.mysql setf mysql - -" Tcl Shell RC file -au BufNewFile,BufRead tclsh.rc setf tcl - -" M$ Resource files -" /etc/Muttrc.d/file.rc is muttrc -au BufNewFile,BufRead *.rc,*.rch - \ if expand("<afile>") !~ "/etc/Muttrc.d/" | - \ setf rc | - \ endif - -" MuPAD source -au BufRead,BufNewFile *.mu setf mupad - -" Mush -au BufNewFile,BufRead *.mush setf mush - -" Mutt setup file (also for Muttng) -au BufNewFile,BufRead Mutt{ng,}rc setf muttrc - -" N1QL -au BufRead,BufNewfile *.n1ql,*.nql setf n1ql - -" Nano -au BufNewFile,BufRead */etc/nanorc,*.nanorc setf nanorc - -" Nastran input/DMAP -"au BufNewFile,BufRead *.dat setf nastran - -" Natural -au BufNewFile,BufRead *.NS[ACGLMNPS] setf natural - -" Noemutt setup file -au BufNewFile,BufRead Neomuttrc setf neomuttrc - -" Netrc -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 - -" Ninja file -au BufNewFile,BufRead *.ninja setf ninja - -" Nix -au BufRead,BufNewFile *.nix setf nix - -" NPM RC file -au BufNewFile,BufRead npmrc,.npmrc setf dosini - -" Novell netware batch files -au BufNewFile,BufRead *.ncf setf ncf - -" Nroff/Troff (*.ms and *.t are checked below) -au BufNewFile,BufRead *.me - \ if expand("<afile>") != "read.me" && expand("<afile>") != "click.me" | - \ setf nroff | - \ endif -au BufNewFile,BufRead *.tr,*.nr,*.roff,*.tmac,*.mom setf nroff -au BufNewFile,BufRead *.[1-9] call dist#ft#FTnroff() - -" Nroff or Objective C++ -au BufNewFile,BufRead *.mm call dist#ft#FTmm() - -" Not Quite C -au BufNewFile,BufRead *.nqc setf nqc - -" NSE - Nmap Script Engine - uses Lua syntax -au BufNewFile,BufRead *.nse setf lua - -" NSIS -au BufNewFile,BufRead *.nsi,*.nsh setf nsis - -" OCaml -au BufNewFile,BufRead *.ml,*.mli,*.mll,*.mly,.ocamlinit,*.mlt,*.mlp,*.mlip,*.mli.cppo,*.ml.cppo setf ocaml - -" Occam -au BufNewFile,BufRead *.occ setf occam - -" Octave -au BufNewFile,BufRead octave.conf,.octaverc,octaverc setf octave - -" Omnimark -au BufNewFile,BufRead *.xom,*.xin setf omnimark - -" OPAM -au BufNewFile,BufRead opam,*.opam,*.opam.template setf opam - -" OpenFOAM -au BufNewFile,BufRead [a-zA-Z0-9]*Dict\(.*\)\=,[a-zA-Z]*Properties\(.*\)\=,*Transport\(.*\),fvSchemes,fvSolution,fvConstrains,fvModels,*/constant/g,*/0\(\.orig\)\=/* call dist#ft#FTfoam() - -" OpenROAD -au BufNewFile,BufRead *.or setf openroad - -" OPL -au BufNewFile,BufRead *.[Oo][Pp][Ll] setf opl - -" OpenSCAD -au BufNewFile,BufRead *.scad setf openscad - -" Oracle config file -au BufNewFile,BufRead *.ora setf ora - -" Org -au BufNewFile,BufRead *.org,*.org_archive setf org - -" Packet filter conf -au BufNewFile,BufRead pf.conf setf pf - -" ini style config files, using # comments -au BufNewFile,BufRead */etc/pacman.conf,mpv.conf setf confini - -" Pacman hooks -au BufNewFile,BufRead *.hook - \ if getline(1) == '[Trigger]' | - \ setf conf | - \ endif - -" Pam conf -au BufNewFile,BufRead */etc/pam.conf setf pamconf - -" Pam environment -au BufNewFile,BufRead pam_env.conf,.pam_environment setf pamenv - -" PApp -au BufNewFile,BufRead *.papp,*.pxml,*.pxsl setf papp - -" Password file -au BufNewFile,BufRead */etc/passwd,*/etc/passwd-,*/etc/passwd.edit,*/etc/shadow,*/etc/shadow-,*/etc/shadow.edit,*/var/backups/passwd.bak,*/var/backups/shadow.bak setf passwd - -" Pascal (also *.p, *.pp, *.inc) -au BufNewFile,BufRead *.pas setf pascal - -" Pascal or Puppet manifest -au BufNewFile,BufRead *.pp call dist#ft#FTpp() - -" Delphi or Lazarus program file -au BufNewFile,BufRead *.dpr,*.lpr setf pascal - -" Free Pascal makefile definition file -au BufNewFile,BufRead *.fpc setf fpcmake - -" PDF -au BufNewFile,BufRead *.pdf setf pdf - -" PCMK - HAE - crm configure edit -au BufNewFile,BufRead *.pcmk setf pcmk - -" Perl -if has("fname_case") - au BufNewFile,BufRead *.pl,*.PL call dist#ft#FTpl() -else - au BufNewFile,BufRead *.pl call dist#ft#FTpl() -endif -au BufNewFile,BufRead *.plx,*.al,*.psgi setf perl - -" Perl, XPM or XPM2 -au BufNewFile,BufRead *.pm - \ if getline(1) =~ "XPM2" | - \ setf xpm2 | - \ elseif getline(1) =~ "XPM" | - \ setf xpm | - \ else | - \ setf perl | - \ endif - -" Perl POD -au BufNewFile,BufRead *.pod setf pod - -" Php, php3, php4, etc. -" 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 - -" PHP config -au BufNewFile,BufRead php.ini-* setf dosini - -" Pike and Cmod -au BufNewFile,BufRead *.pike,*.pmod setf pike -au BufNewFile,BufRead *.cmod setf cmod - -" Pinfo config -au BufNewFile,BufRead */etc/pinforc,*/.pinforc setf pinfo - -" Palm Resource compiler -au BufNewFile,BufRead *.rcp setf pilrc - -" Pine config -au BufNewFile,BufRead .pinerc,pinerc,.pinercex,pinercex setf pine - -" Pipenv Pipfiles -au BufNewFile,BufRead Pipfile setf toml -au BufNewFile,BufRead Pipfile.lock setf json - -" PL/1, PL/I -au BufNewFile,BufRead *.pli,*.pl1 setf pli - -" PL/M (also: *.inp) -au BufNewFile,BufRead *.plm,*.p36,*.pac setf plm - -" PL/SQL -au BufNewFile,BufRead *.pls,*.plsql setf plsql - -" PLP -au BufNewFile,BufRead *.plp setf plp - -" PO and PO template (GNU gettext) -au BufNewFile,BufRead *.po,*.pot setf po - -" Postfix main config -au BufNewFile,BufRead main.cf setf pfmain - -" PostScript (+ font files, encapsulated PostScript, Adobe Illustrator) -au BufNewFile,BufRead *.ps,*.pfa,*.afm,*.eps,*.epsf,*.epsi,*.ai setf postscr - -" PostScript Printer Description -au BufNewFile,BufRead *.ppd setf ppd - -" Povray -au BufNewFile,BufRead *.pov setf pov - -" Povray configuration -au BufNewFile,BufRead .povrayrc setf povini - -" Povray, Pascal, PHP or assembly -au BufNewFile,BufRead *.inc call dist#ft#FTinc() - -" PowerShell -au BufNewFile,BufRead *.ps1,*.psd1,*.psm1,*.pssc setf ps1 -au BufNewFile,BufRead *.ps1xml setf ps1xml -au BufNewFile,BufRead *.cdxml,*.psc1 setf xml - -" Printcap and Termcap -au BufNewFile,BufRead *printcap - \ let b:ptcap_type = "print" | setf ptcap -au BufNewFile,BufRead *termcap - \ let b:ptcap_type = "term" | setf ptcap - -" Prisma -au BufRead,BufNewFile *.prisma setf prisma - -" PCCTS / ANTLR -"au BufNewFile,BufRead *.g setf antlr -au BufNewFile,BufRead *.g setf pccts - -" PPWizard -au BufNewFile,BufRead *.it,*.ih setf ppwiz - -" Pug -au BufRead,BufNewFile *.pug setf pug - -" Puppet -au BufNewFile,BufRead Puppetfile setf ruby - -" Embedded Puppet -au BufNewFile,BufRead *.epp setf epuppet - -" Obj 3D file format -" TODO: is there a way to avoid MS-Windows Object files? -au BufNewFile,BufRead *.obj setf obj - -" Oracle Pro*C/C++ -au BufNewFile,BufRead *.pc setf proc - -" Privoxy actions file -au BufNewFile,BufRead *.action setf privoxy - -" Procmail -au BufNewFile,BufRead .procmail,.procmailrc setf procmail - -" Progress or CWEB -au BufNewFile,BufRead *.w call dist#ft#FTprogress_cweb() - -" Progress or assembly -au BufNewFile,BufRead *.i call dist#ft#FTprogress_asm() - -" Progress or Pascal -au BufNewFile,BufRead *.p call dist#ft#FTprogress_pascal() - -" Software Distributor Product Specification File (POSIX 1387.2-1995) -au BufNewFile,BufRead *.psf setf psf -au BufNewFile,BufRead INDEX,INFO - \ if getline(1) =~ '^\s*\(distribution\|installed_software\|root\|bundle\|product\)\s*$' | - \ setf psf | - \ endif - -" Prolog -au BufNewFile,BufRead *.pdb setf prolog - -" Promela -au BufNewFile,BufRead *.pml setf promela - -" Property Specification Language (PSL) -au BufNewFile,BufRead *.psl setf psl - -" Google protocol buffers -au BufNewFile,BufRead *.proto setf proto -au BufNewFile,BufRead *.pbtxt setf pbtxt - -" Poke -au BufNewFile,BufRead *.pk setf poke - -" Protocols -au BufNewFile,BufRead */etc/protocols setf protocols - -" Pyret -au BufNewFile,BufRead *.arr setf pyret - -" Pyrex -au BufNewFile,BufRead *.pyx,*.pxd setf pyrex - -" Python, Python Shell Startup and Python Stub Files -" Quixote (Python-based web framework) -au BufNewFile,BufRead *.py,*.pyw,.pythonstartup,.pythonrc setf python -au BufNewFile,BufRead *.ptl,*.pyi,SConstruct setf python - -" QL -au BufRead,BufNewFile *.ql,*.qll setf ql - -" Quarto -au BufRead,BufNewFile *.qmd setf quarto - -" Radiance -au BufNewFile,BufRead *.rad,*.mat setf radiance - -" Raku (formerly Perl6) -au BufNewFile,BufRead *.pm6,*.p6,*.t6,*.pod6,*.raku,*.rakumod,*.rakudoc,*.rakutest setf raku - -" Ratpoison config/command files -au BufNewFile,BufRead .ratpoisonrc,ratpoisonrc setf ratpoison - -" RCS file -au BufNewFile,BufRead *\,v setf rcs - -" Readline -au BufNewFile,BufRead .inputrc,inputrc setf readline - -" Registry for MS-Windows -au BufNewFile,BufRead *.reg - \ if getline(1) =~? '^REGEDIT[0-9]*\s*$\|^Windows Registry Editor Version \d*\.\d*\s*$' | setf registry | endif - -" Renderman Interface Bytestream -au BufNewFile,BufRead *.rib setf rib - -" Rego Policy Language -au BufNewFile,BufRead *.rego setf rego - -" Rexx -au BufNewFile,BufRead *.rex,*.orx,*.rxo,*.rxj,*.jrexx,*.rexxj,*.rexx,*.testGroup,*.testUnit setf rexx - -" R Help file -if has("fname_case") - au BufNewFile,BufRead *.rd,*.Rd setf rhelp -else - au BufNewFile,BufRead *.rd setf rhelp -endif - -" R noweb file -if has("fname_case") - au BufNewFile,BufRead *.Rnw,*.rnw,*.Snw,*.snw setf rnoweb -else - au BufNewFile,BufRead *.rnw,*.snw setf rnoweb -endif - -" R Markdown file -if has("fname_case") - au BufNewFile,BufRead *.Rmd,*.rmd,*.Smd,*.smd setf rmd -else - au BufNewFile,BufRead *.rmd,*.smd setf rmd -endif - -" RSS looks like XML -au BufNewFile,BufRead *.rss setf xml - -" R reStructuredText file -if has("fname_case") - au BufNewFile,BufRead *.Rrst,*.rrst,*.Srst,*.srst setf rrst -else - au BufNewFile,BufRead *.rrst,*.srst setf rrst -endif - -" Rexx, Rebol or R -au BufNewFile,BufRead *.r,*.R call dist#ft#FTr() - -" Remind -au BufNewFile,BufRead .reminders,*.remind,*.rem setf remind - -" ReScript -au BufNewFile,BufRead *.res,*.resi setf rescript - -" Resolv.conf -au BufNewFile,BufRead resolv.conf setf resolv - -" Relax NG Compact -au BufNewFile,BufRead *.rnc setf rnc - -" Relax NG XML -au BufNewFile,BufRead *.rng setf rng - -" RPL/2 -au BufNewFile,BufRead *.rpl setf rpl - -" Robot Framework -au BufNewFile,BufRead *.robot,*.resource setf robot - -" Robots.txt -au BufNewFile,BufRead robots.txt setf robots - -" Rpcgen -au BufNewFile,BufRead *.x setf rpcgen - -" MikroTik RouterOS script -au BufRead,BufNewFile *.rsc setf routeros - -" reStructuredText Documentation Format -au BufNewFile,BufRead *.rst setf rst - -" RTF -au BufNewFile,BufRead *.rtf setf rtf - -" Interactive Ruby shell -au BufNewFile,BufRead .irbrc,irbrc setf ruby - -" Ruby -au BufNewFile,BufRead *.rb,*.rbw setf ruby - -" RubyGems -au BufNewFile,BufRead *.gemspec setf ruby - -" RBS (Ruby Signature) -au BufNewFile,BufRead *.rbs setf rbs - -" Rackup -au BufNewFile,BufRead *.ru setf ruby - -" Bundler -au BufNewFile,BufRead Gemfile setf ruby - -" Ruby on Rails -au BufNewFile,BufRead *.builder,*.rxml,*.rjs setf ruby - -" Rantfile and Rakefile is like Ruby -au BufNewFile,BufRead [rR]antfile,*.rant,[rR]akefile,*.rake setf ruby - -" Rust -au BufNewFile,BufRead *.rs setf rust -au BufNewFile,BufRead Cargo.lock,*/.cargo/config,*/.cargo/credentials setf toml - -" S-lang (or shader language, or SmallLisp) -au BufNewFile,BufRead *.sl setf slang - -" Samba config -au BufNewFile,BufRead smb.conf setf samba - -" SAS script -au BufNewFile,BufRead *.sas setf sas - -" Sass -au BufNewFile,BufRead *.sass setf sass - -" Sather -au BufNewFile,BufRead *.sa setf sather - -" Scala -au BufNewFile,BufRead *.scala setf scala - -" SBT - Scala Build Tool -au BufNewFile,BufRead *.sbt setf sbt - -" SuperCollider -au BufNewFile,BufRead *.sc call dist#ft#FTsc() - -au BufNewFile,BufRead *.quark setf supercollider - -" scdoc -au BufNewFile,BufRead *.scd call dist#ft#FTscd() - -" Scilab -au BufNewFile,BufRead *.sci,*.sce setf scilab - - -" SCSS -au BufNewFile,BufRead *.scss setf scss - -" SD: Streaming Descriptors -au BufNewFile,BufRead *.sd setf sd - -" SDL -au BufNewFile,BufRead *.sdl,*.pr setf sdl - -" sed -au BufNewFile,BufRead *.sed setf sed - -" svelte -au BufNewFile,BufRead *.svelte setf svelte - -" Sieve (RFC 3028, 5228) -au BufNewFile,BufRead *.siv,*.sieve setf sieve - -" Sendmail -au BufNewFile,BufRead sendmail.cf setf sm - -" Sendmail .mc files are actually m4. Could also be MS Message text file or -" Maxima. -au BufNewFile,BufRead *.mc call dist#ft#McSetf() - -" Services -au BufNewFile,BufRead */etc/services setf services - -" Service Location config -au BufNewFile,BufRead */etc/slp.conf setf slpconf - -" Service Location registration -au BufNewFile,BufRead */etc/slp.reg setf slpreg - -" Service Location SPI -au BufNewFile,BufRead */etc/slp.spi setf slpspi - -" Setserial config -au BufNewFile,BufRead */etc/serial.conf setf setserial - -" SGML -au BufNewFile,BufRead *.sgm,*.sgml - \ if getline(1).getline(2).getline(3).getline(4).getline(5) =~? 'linuxdoc' | - \ setf sgmllnx | - \ elseif getline(1) =~ '<!DOCTYPE.*DocBook' || getline(2) =~ '<!DOCTYPE.*DocBook' | - \ let b:docbk_type = "sgml" | - \ let b:docbk_ver = 4 | - \ setf docbk | - \ else | - \ setf sgml | - \ endif - -" SGMLDECL -au BufNewFile,BufRead *.decl,*.dcl,*.dec - \ if getline(1).getline(2).getline(3) =~? '^<!SGML' | - \ setf sgmldecl | - \ endif - -" SGML catalog file -au BufNewFile,BufRead catalog setf catalog - -" Shell scripts (sh, ksh, bash, bash2, csh); Allow .profile_foo etc. -" Gentoo ebuilds, Arch Linux PKGBUILDs and Alpine Linux APKBUILDs are actually -" bash scripts. -" NOTE: Patterns ending in a star are further down, these have lower priority. -au BufNewFile,BufRead .bashrc,bashrc,bash.bashrc,.bash[_-]profile,.bash[_-]logout,.bash[_-]aliases,bash-fc[-.],*.ebuild,*.bash,*.eclass,PKGBUILD,APKBUILD call dist#ft#SetFileTypeSH("bash") -au BufNewFile,BufRead .kshrc,*.ksh call dist#ft#SetFileTypeSH("ksh") -au BufNewFile,BufRead */etc/profile,.profile,*.sh,*.env call dist#ft#SetFileTypeSH(getline(1)) - -" Shell script (Arch Linux) or PHP file (Drupal) -au BufNewFile,BufRead *.install - \ if getline(1) =~ '<?php' | - \ setf php | - \ else | - \ call dist#ft#SetFileTypeSH("bash") | - \ endif - -" tcsh scripts (patterns ending in a star further below) -au BufNewFile,BufRead .tcshrc,*.tcsh,tcsh.tcshrc,tcsh.login call dist#ft#SetFileTypeShell("tcsh") - -" csh scripts, but might also be tcsh scripts (on some systems csh is tcsh) -" (patterns ending in a start further below) -au BufNewFile,BufRead .login,.cshrc,csh.cshrc,csh.login,csh.logout,*.csh,.alias call dist#ft#CSH() - -" Zig -au BufNewFile,BufRead *.zig setf zig - -" Z-Shell script (patterns ending in a star further below) -au BufNewFile,BufRead .zprofile,*/etc/zprofile,.zfbfmarks setf zsh -au BufNewFile,BufRead .zshrc,.zshenv,.zlogin,.zlogout,.zcompdump setf zsh -au BufNewFile,BufRead *.zsh setf zsh - -" Scheme -au BufNewFile,BufRead *.scm,*.ss,*.sld,*.rkt,*.rktd,*.rktl setf scheme - -" Screen RC -au BufNewFile,BufRead .screenrc,screenrc setf screen - -" Sexplib -au BufNewFile,BufRead *.sexp setf sexplib - -" Simula -au BufNewFile,BufRead *.sim setf simula - -" SINDA -au BufNewFile,BufRead *.sin,*.s85 setf sinda - -" SiSU -au BufNewFile,BufRead *.sst,*.ssm,*.ssi,*.-sst,*._sst setf sisu -au BufNewFile,BufRead *.sst.meta,*.-sst.meta,*._sst.meta setf sisu - -" SKILL -au BufNewFile,BufRead *.il,*.ils,*.cdf setf skill - -" SLRN -au BufNewFile,BufRead .slrnrc setf slrnrc -au BufNewFile,BufRead *.score setf slrnsc - -" Smalltalk -au BufNewFile,BufRead *.st setf st - -" Smalltalk (and Rexx, TeX, and Visual Basic) -au BufNewFile,BufRead *.cls call dist#ft#FTcls() - -" Smarty templates -au BufNewFile,BufRead *.tpl setf smarty - -" SMIL or XML -au BufNewFile,BufRead *.smil - \ if getline(1) =~ '<?\s*xml.*?>' | - \ setf xml | - \ else | - \ setf smil | - \ endif - -" SMIL or SNMP MIB file -au BufNewFile,BufRead *.smi - \ if getline(1) =~ '\<smil\>' | - \ setf smil | - \ else | - \ setf mib | - \ endif - -" SMITH -au BufNewFile,BufRead *.smt,*.smith setf smith - -" Snobol4 and spitbol -au BufNewFile,BufRead *.sno,*.spt setf snobol4 - -" SNMP MIB files -au BufNewFile,BufRead *.mib,*.my setf mib - -" Snort Configuration -au BufNewFile,BufRead *.hog,snort.conf,vision.conf setf hog -au BufNewFile,BufRead *.rules call dist#ft#FTRules() - -" Solidity -au BufRead,BufNewFile *.sol setf solidity - -" SPARQL queries -au BufNewFile,BufRead *.rq,*.sparql setf sparql - -" Spec (Linux RPM) -au BufNewFile,BufRead *.spec setf spec - -" Speedup (AspenTech plant simulator) -au BufNewFile,BufRead *.speedup,*.spdata,*.spd setf spup - -" Slice -au BufNewFile,BufRead *.ice setf slice - -" Microsoft Visual Studio Solution -au BufNewFile,BufRead *.sln setf solution -au BufNewFile,BufRead *.slnf setf json - -" Spice -au BufNewFile,BufRead *.sp,*.spice setf spice - -" Spyce -au BufNewFile,BufRead *.spy,*.spi setf spyce - -" Squid -au BufNewFile,BufRead squid.conf setf squid - -" SQL for Oracle Designer -au BufNewFile,BufRead *.tyb,*.typ,*.tyc,*.pkb,*.pks setf sql - -" SQL -au BufNewFile,BufRead *.sql call dist#ft#SQL() - -" SQLJ -au BufNewFile,BufRead *.sqlj setf sqlj - -" SQR -au BufNewFile,BufRead *.sqr,*.sqi setf sqr - -" Squirrel -au BufNewFile,BufRead *.nut setf squirrel - -" OpenSSH configuration -au BufNewFile,BufRead ssh_config,*/.ssh/config,*/.ssh/*.conf setf sshconfig -au BufNewFile,BufRead */etc/ssh/ssh_config.d/*.conf setf sshconfig - -" OpenSSH server configuration -au BufNewFile,BufRead sshd_config setf sshdconfig -au BufNewFile,BufRead */etc/ssh/sshd_config.d/*.conf setf sshdconfig - -" Stata -au BufNewFile,BufRead *.ado,*.do,*.imata,*.mata setf stata -" Also *.class, but not when it's a Java bytecode file -au BufNewFile,BufRead *.class - \ if getline(1) !~ "^\xca\xfe\xba\xbe" | setf stata | endif - -" SMCL -au BufNewFile,BufRead *.hlp,*.ihlp,*.smcl setf smcl - -" Stored Procedures -au BufNewFile,BufRead *.stp setf stp - -" Standard ML -au BufNewFile,BufRead *.sml setf sml - -" Sratus VOS command macro -au BufNewFile,BufRead *.cm setf voscm - -" Swift -au BufNewFile,BufRead *.swift setf swift -au BufNewFile,BufRead *.swift.gyb setf swiftgyb - -" Swift Intermediate Language -au BufNewFile,BufRead *.sil setf sil - -" Sysctl -au BufNewFile,BufRead */etc/sysctl.conf,*/etc/sysctl.d/*.conf setf sysctl - -" Systemd unit files -au BufNewFile,BufRead */systemd/*.{automount,dnssd,link,mount,netdev,network,nspawn,path,service,slice,socket,swap,target,timer} setf systemd -" Systemd overrides -au BufNewFile,BufRead */etc/systemd/*.conf.d/*.conf setf systemd -au BufNewFile,BufRead */etc/systemd/system/*.d/*.conf setf systemd -au BufNewFile,BufRead */.config/systemd/user/*.d/*.conf setf systemd -" Systemd temp files -au BufNewFile,BufRead */etc/systemd/system/*.d/.#* setf systemd -au BufNewFile,BufRead */etc/systemd/system/.#* setf systemd -au BufNewFile,BufRead */.config/systemd/user/*.d/.#* setf systemd -au BufNewFile,BufRead */.config/systemd/user/.#* setf systemd - -" Synopsys Design Constraints -au BufNewFile,BufRead *.sdc setf sdc - -" Sudoers -au BufNewFile,BufRead */etc/sudoers,sudoers.tmp setf sudoers - -" SVG (Scalable Vector Graphics) -au BufNewFile,BufRead *.svg setf svg - -" Surface -au BufRead,BufNewFile *.sface setf surface - -" Tads (or Nroff or Perl test file) -au BufNewFile,BufRead *.t - \ if !dist#ft#FTnroff() && !dist#ft#FTperl() | setf tads | endif - -" Tags -au BufNewFile,BufRead tags setf tags - -" TAK -au BufNewFile,BufRead *.tak setf tak - -" Task -au BufRead,BufNewFile {pending,completed,undo}.data setf taskdata -au BufRead,BufNewFile *.task setf taskedit - -" Tcl (JACL too) -au BufNewFile,BufRead *.tcl,*.tm,*.tk,*.itcl,*.itk,*.jacl,.tclshrc,.wishrc setf tcl - -" Teal -au BufRead,BufNewFile *.tl setf teal - -" TealInfo -au BufNewFile,BufRead *.tli setf tli - -" Telix Salt -au BufNewFile,BufRead *.slt setf tsalt - -" Tera Term Language or Turtle -au BufRead,BufNewFile *.ttl - \ if getline(1) =~ '^@\?\(prefix\|base\)' | - \ setf turtle | - \ else | - \ setf teraterm | - \ endif - -" Terminfo -au BufNewFile,BufRead *.ti setf terminfo - -" Terraform variables -au BufRead,BufNewFile *.tfvars setf terraform-vars - -" TeX -au BufNewFile,BufRead *.latex,*.sty,*.dtx,*.ltx,*.bbl setf tex -au BufNewFile,BufRead *.tex call dist#ft#FTtex() - -" ConTeXt -au BufNewFile,BufRead *.mkii,*.mkiv,*.mkvi,*.mkxl,*.mklx setf context - -" Texinfo -au BufNewFile,BufRead *.texinfo,*.texi,*.txi setf texinfo - -" TeX configuration -au BufNewFile,BufRead texmf.cnf setf texmf - -" Tidy config -au BufNewFile,BufRead .tidyrc,tidyrc,tidy.conf setf tidy - -" TF mud client -au BufNewFile,BufRead .tfrc,tfrc setf tf - -" TF mud client or terraform -au BufNewFile,BufRead *.tf call dist#ft#FTtf() - -" TLA+ -au BufNewFile,BufRead *.tla setf tla - -" tmux configuration -au BufNewFile,BufRead {.,}tmux*.conf setf tmux - -" TOML -au BufNewFile,BufRead *.toml setf toml - -" TPP - Text Presentation Program -au BufNewFile,BufRead *.tpp setf tpp - -" Treetop -au BufRead,BufNewFile *.treetop setf treetop - -" Trustees -au BufNewFile,BufRead trustees.conf setf trustees - -" TSS - Geometry -au BufNewFile,BufReadPost *.tssgm setf tssgm - -" TSS - Optics -au BufNewFile,BufReadPost *.tssop setf tssop - -" TSS - Command Line (temporary) -au BufNewFile,BufReadPost *.tsscl setf tsscl - -" TSV Files -au BufNewFile,BufRead *.tsv setf tsv - -" Tutor mode -au BufNewFile,BufReadPost *.tutor setf tutor - -" TWIG files -au BufNewFile,BufReadPost *.twig setf twig - -" Typescript or Qt translation file (which is XML) -au BufNewFile,BufReadPost *.ts - \ if getline(1) =~ '<?xml' | - \ setf xml | - \ else | - \ setf typescript | - \ endif - -" TypeScript with React -au BufNewFile,BufRead *.tsx setf typescriptreact - -" Motif UIT/UIL files -au BufNewFile,BufRead *.uit,*.uil setf uil - -" Udev conf -au BufNewFile,BufRead */etc/udev/udev.conf setf udevconf - -" Udev permissions -au BufNewFile,BufRead */etc/udev/permissions.d/*.permissions setf udevperm -" -" Udev symlinks config -au BufNewFile,BufRead */etc/udev/cdsymlinks.conf setf sh - -" UnrealScript -au BufNewFile,BufRead *.uc setf uc - -" Updatedb -au BufNewFile,BufRead */etc/updatedb.conf setf updatedb - -" Upstart (init(8)) config files -au BufNewFile,BufRead */usr/share/upstart/*.conf setf upstart -au BufNewFile,BufRead */usr/share/upstart/*.override setf upstart -au BufNewFile,BufRead */etc/init/*.conf,*/etc/init/*.override setf upstart -au BufNewFile,BufRead */.init/*.conf,*/.init/*.override setf upstart -au BufNewFile,BufRead */.config/upstart/*.conf setf upstart -au BufNewFile,BufRead */.config/upstart/*.override setf upstart - -" Vala -au BufNewFile,BufRead *.vala setf vala - -" Vera -au BufNewFile,BufRead *.vr,*.vri,*.vrh setf vera - -" Vagrant (uses Ruby syntax) -au BufNewFile,BufRead Vagrantfile setf ruby - -" Verilog HDL -au BufNewFile,BufRead *.v setf verilog - -" Verilog-AMS HDL -au BufNewFile,BufRead *.va,*.vams setf verilogams - -" SystemVerilog -au BufNewFile,BufRead *.sv,*.svh setf systemverilog - -" VHDL -au BufNewFile,BufRead *.hdl,*.vhd,*.vhdl,*.vbe,*.vst,*.vho setf vhdl - -" Vim script -au BufNewFile,BufRead *.vim,*.vba,.exrc,_exrc setf vim - -" Viminfo file -au BufNewFile,BufRead .viminfo,_viminfo setf viminfo - -" Virata Config Script File or Drupal module -au BufRead,BufNewFile *.hw,*.module,*.pkg - \ if getline(1) =~ '<?php' | - \ setf php | - \ else | - \ setf virata | - \ endif - -" Visual Basic (also uses *.bas) or FORM -au BufNewFile,BufRead *.frm call dist#ft#FTfrm() - -" SaxBasic is close to Visual Basic -au BufNewFile,BufRead *.sba setf vb - -" Vgrindefs file -au BufNewFile,BufRead vgrindefs setf vgrindefs - -" VRML V1.0c -au BufNewFile,BufRead *.wrl setf vrml - -" Vroom (vim testing and executable documentation) -au BufNewFile,BufRead *.vroom setf vroom - -" Vue.js Single File Component -au BufNewFile,BufRead *.vue setf vue - -" WebAssembly -au BufNewFile,BufRead *.wast,*.wat setf wast - -" Webmacro -au BufNewFile,BufRead *.wm setf webmacro - -" Wget config -au BufNewFile,BufRead .wgetrc,wgetrc setf wget - -" Wget2 config -au BufNewFile,BufRead .wget2rc,wget2rc setf wget2 - -" Website MetaLanguage -au BufNewFile,BufRead *.wml setf wml - -" Winbatch -au BufNewFile,BufRead *.wbt setf winbatch - -" WSML -au BufNewFile,BufRead *.wsml setf wsml - -" WPL -au BufNewFile,BufRead *.wpl setf xml - -" WvDial -au BufNewFile,BufRead wvdial.conf,.wvdialrc setf wvdial - -" CVS RC file -au BufNewFile,BufRead .cvsrc setf cvsrc - -" CVS commit file -au BufNewFile,BufRead cvs\d\+ setf cvs - -" WEB (*.web is also used for Winbatch: Guess, based on expecting "%" comment -" lines in a WEB file). -au BufNewFile,BufRead *.web - \ if getline(1)[0].getline(2)[0].getline(3)[0].getline(4)[0].getline(5)[0] =~ "%" | - \ setf web | - \ else | - \ setf winbatch | - \ endif - -" Windows Scripting Host and Windows Script Component -au BufNewFile,BufRead *.ws[fc] setf wsh - -" XHTML -au BufNewFile,BufRead *.xhtml,*.xht setf xhtml - -" X Pixmap (dynamically sets colors, this used to trigger on BufEnter to make -" it work better, but that breaks setting 'filetype' manually) -au BufNewFile,BufRead *.xpm - \ if getline(1) =~ "XPM2" | - \ setf xpm2 | - \ else | - \ setf xpm | - \ endif -au BufNewFile,BufRead *.xpm2 setf xpm2 - -" XFree86 config -au BufNewFile,BufRead XF86Config - \ if getline(1) =~ '\<XConfigurator\>' | - \ let b:xf86conf_xfree86_version = 3 | - \ endif | - \ setf xf86conf -au BufNewFile,BufRead */xorg.conf.d/*.conf - \ let b:xf86conf_xfree86_version = 4 | - \ setf xf86conf - -" Xorg config -au BufNewFile,BufRead xorg.conf,xorg.conf-4 let b:xf86conf_xfree86_version = 4 | setf xf86conf - -" Xinetd conf -au BufNewFile,BufRead */etc/xinetd.conf setf xinetd - -" XS Perl extension interface language -au BufNewFile,BufRead *.xs setf xs - -" X resources file -au BufNewFile,BufRead .Xdefaults,.Xpdefaults,.Xresources,xdm-config,*.ad setf xdefaults - -" Xmath -au BufNewFile,BufRead *.msc,*.msf setf xmath -au BufNewFile,BufRead *.ms - \ if !dist#ft#FTnroff() | setf xmath | endif - -" XML specific variants: docbk and xbl -au BufNewFile,BufRead *.xml call dist#ft#FTxml() - -" XMI (holding UML models) is also XML -au BufNewFile,BufRead *.xmi setf xml - -" CSPROJ files are Visual Studio.NET's XML-based C# project config files -au BufNewFile,BufRead *.csproj,*.csproj.user setf xml - -" FSPROJ files are Visual Studio.NET's XML-based F# project config files -au BufNewFile,BufRead *.fsproj,*.fsproj.user setf xml - -" VBPROJ files are Visual Studio.NET's XML-based Visual Basic project config files -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. -au BufNewFile,BufRead *.ui setf xml - -" TPM's are RDF-based descriptions of TeX packages (Nikolai Weibull) -au BufNewFile,BufRead *.tpm setf xml - -" Xdg menus -au BufNewFile,BufRead */etc/xdg/menus/*.menu setf xml - -" ATI graphics driver configuration -au BufNewFile,BufRead fglrxrc setf xml - -" Web Services Description Language (WSDL) -au BufNewFile,BufRead *.wsdl setf xml - -" XLIFF (XML Localisation Interchange File Format) is also XML -au BufNewFile,BufRead *.xlf setf xml -au BufNewFile,BufRead *.xliff setf xml - -" XML User Interface Language -au BufNewFile,BufRead *.xul setf xml - -" X11 xmodmap (also see below) -au BufNewFile,BufRead *Xmodmap setf xmodmap - -" Xquery -au BufNewFile,BufRead *.xq,*.xql,*.xqm,*.xquery,*.xqy setf xquery - -" XSD -au BufNewFile,BufRead *.xsd setf xsd - -" Xslt -au BufNewFile,BufRead *.xsl,*.xslt setf xslt - -" Yacc -au BufNewFile,BufRead *.yy,*.yxx,*.y++ setf yacc - -" Yacc or racc -au BufNewFile,BufRead *.y call dist#ft#FTy() - -" Yaml -au BufNewFile,BufRead *.yaml,*.yml setf yaml - -" Raml -au BufNewFile,BufRead *.raml setf raml - -" yum conf (close enough to dosini) -au BufNewFile,BufRead */etc/yum.conf setf dosini - -" YANG -au BufRead,BufNewFile *.yang setf yang - -" Zimbu -au BufNewFile,BufRead *.zu setf zimbu -" Zimbu Templates -au BufNewFile,BufRead *.zut setf zimbutempl - -" Zope -" dtml (zope dynamic template markup language), pt (zope page template), -" cpt (zope form controller page template) -au BufNewFile,BufRead *.dtml,*.pt,*.cpt call dist#ft#FThtml() -" zsql (zope sql method) -au BufNewFile,BufRead *.zsql call dist#ft#SQL() - -" Z80 assembler asz80 -au BufNewFile,BufRead *.z8a setf z8a - -augroup END - - -" Source the user-specified filetype file, for backwards compatibility with -" Vim 5.x. -if exists("myfiletypefile") && filereadable(expand(myfiletypefile)) - execute "source " . myfiletypefile -endif - - -" Check for "*" after loading myfiletypefile, so that scripts.vim is only used -" when there are no matching file name extensions. -" Don't do this for compressed files. -augroup filetypedetect -au BufNewFile,BufRead * - \ if !did_filetype() && expand("<amatch>") !~ g:ft_ignore_pat - \ | runtime! scripts.vim | endif -au StdinReadPost * if !did_filetype() | runtime! scripts.vim | endif - - -" Plain text files, needs to be far down to not override others. This avoids -" the "conf" type being used if there is a line starting with '#'. -" But before patterns matching everything in a directory. -au BufNewFile,BufRead *.text,README,LICENSE,COPYING,AUTHORS setf text - - -" Extra checks for when no filetype has been detected now. Mostly used for -" patterns that end in "*". E.g., "zsh*" matches "zsh.vim", but that's a Vim -" script file. -" Most of these should call s:StarSetf() to avoid names ending in .gz and the -" like are used. - -" More Apache style config files -au BufNewFile,BufRead */etc/proftpd/*.conf*,*/etc/proftpd/conf.*/* call s:StarSetf('apachestyle') -au BufNewFile,BufRead proftpd.conf* call s:StarSetf('apachestyle') - -" More Apache config files -au BufNewFile,BufRead access.conf*,apache.conf*,apache2.conf*,httpd.conf*,srm.conf* call s:StarSetf('apache') -au BufNewFile,BufRead */etc/apache2/*.conf*,*/etc/apache2/conf.*/*,*/etc/apache2/mods-*/*,*/etc/apache2/sites-*/*,*/etc/httpd/conf.*/*,*/etc/httpd/mods-*/*,*/etc/httpd/sites-*/*,*/etc/httpd/conf.d/*.conf* call s:StarSetf('apache') - -" APT config file -au BufNewFile,BufRead */etc/apt/apt.conf.d/{[-_[:alnum:]]\+,[-_.[:alnum:]]\+.conf} call s:StarSetf('aptconf') - -" Asterisk config file -au BufNewFile,BufRead *asterisk/*.conf* call s:StarSetf('asterisk') -au BufNewFile,BufRead *asterisk*/*voicemail.conf* call s:StarSetf('asteriskvm') - -" Bazaar version control -au BufNewFile,BufRead bzr_log.* setf bzr - -" Bazel build file -if !has("fname_case") - au BufNewFile,BufRead *.BUILD,BUILD setf bzl -endif - -" BIND zone -au BufNewFile,BufRead */named/db.*,*/bind/db.* call s:StarSetf('bindzone') - -au BufNewFile,BufRead cabal.project.* call s:StarSetf('cabalproject') - -" Calendar -au BufNewFile,BufRead */.calendar/*, - \*/share/calendar/*/calendar.*,*/share/calendar/calendar.* - \ call s:StarSetf('calendar') - -" Changelog -au BufNewFile,BufRead [cC]hange[lL]og* - \ if getline(1) =~ '; urgency=' - \| call s:StarSetf('debchangelog') - \|else - \| call s:StarSetf('changelog') - \|endif - -" Crontab -au BufNewFile,BufRead crontab,crontab.*,*/etc/cron.d/* call s:StarSetf('crontab') - -" dnsmasq(8) configuration -au BufNewFile,BufRead */etc/dnsmasq.d/* call s:StarSetf('dnsmasq') - -" Dockerfile -au BufNewFile,BufRead Dockerfile.*,Containerfile.* call s:StarSetf('dockerfile') - -" Dracula -au BufNewFile,BufRead drac.* call s:StarSetf('dracula') - -" Fvwm -au BufNewFile,BufRead */.fvwm/* call s:StarSetf('fvwm') -au BufNewFile,BufRead *fvwmrc*,*fvwm95*.hook - \ let b:fvwm_version = 1 | call s:StarSetf('fvwm') -au BufNewFile,BufRead *fvwm2rc* - \ if expand("<afile>:e") == "m4" - \| call s:StarSetf('fvwm2m4') - \|else - \| let b:fvwm_version = 2 | call s:StarSetf('fvwm') - \|endif - -" Gedcom -au BufNewFile,BufRead */tmp/lltmp* call s:StarSetf('gedcom') - -" Git -au BufNewFile,BufRead */.gitconfig.d/*,*/etc/gitconfig.d/* call s:StarSetf('gitconfig') - -" Gitolite -au BufNewFile,BufRead */gitolite-admin/conf/* call s:StarSetf('gitolite') - -" GTK RC -au BufNewFile,BufRead .gtkrc*,gtkrc* call s:StarSetf('gtkrc') - -" Jam -au BufNewFile,BufRead Prl*.*,JAM*.* call s:StarSetf('jam') - -" Jargon -au! BufNewFile,BufRead *jarg* - \ if getline(1).getline(2).getline(3).getline(4).getline(5) =~? 'THIS IS THE JARGON FILE' - \| call s:StarSetf('jargon') - \|endif - -" Java Properties resource file (note: doesn't catch font.properties.pl) -au BufNewFile,BufRead *.properties_??_??_* call s:StarSetf('jproperties') - -" Kconfig -au BufNewFile,BufRead Kconfig.* call s:StarSetf('kconfig') - -" Lilo: Linux loader -au BufNewFile,BufRead lilo.conf* call s:StarSetf('lilo') - -" Libsensors -au BufNewFile,BufRead */etc/sensors.d/[^.]* call s:StarSetf('sensors') - -" Logcheck -au BufNewFile,BufRead */etc/logcheck/*.d*/* call s:StarSetf('logcheck') - -" Makefile -au BufNewFile,BufRead [mM]akefile* call s:StarSetf('make') - -" Ruby Makefile -au BufNewFile,BufRead [rR]akefile* call s:StarSetf('ruby') - -" Mail (also matches muttrc.vim, so this is below the other checks) -au BufNewFile,BufRead {neo,}mutt[[:alnum:]._-]\\\{6\} setf mail - -au BufNewFile,BufRead reportbug-* call s:StarSetf('mail') - -" Modconf -au BufNewFile,BufRead */etc/modutils/* - \ if executable(expand("<afile>")) != 1 - \| call s:StarSetf('modconf') - \|endif -au BufNewFile,BufRead */etc/modprobe.* call s:StarSetf('modconf') - -" Mutt setup files (must be before catch *.rc) -au BufNewFile,BufRead */etc/Muttrc.d/* call s:StarSetf('muttrc') - -" Mutt setup file -au BufNewFile,BufRead .mutt{ng,}rc*,*/.mutt{ng,}/mutt{ng,}rc* call s:StarSetf('muttrc') -au BufNewFile,BufRead mutt{ng,}rc*,Mutt{ng,}rc* call s:StarSetf('muttrc') - -" Neomutt setup file -au BufNewFile,BufRead .neomuttrc*,*/.neomutt/neomuttrc* call s:StarSetf('neomuttrc') -au BufNewFile,BufRead neomuttrc*,Neomuttrc* call s:StarSetf('neomuttrc') - -" Nroff macros -au BufNewFile,BufRead tmac.* call s:StarSetf('nroff') - -" OpenBSD hostname.if -au BufNewFile,BufRead */etc/hostname.* call s:StarSetf('config') - -" Pam conf -au BufNewFile,BufRead */etc/pam.d/* call s:StarSetf('pamconf') - -" Printcap and Termcap -au BufNewFile,BufRead *printcap* - \ if !did_filetype() - \| let b:ptcap_type = "print" | call s:StarSetf('ptcap') - \|endif -au BufNewFile,BufRead *termcap* - \ if !did_filetype() - \| let b:ptcap_type = "term" | call s:StarSetf('ptcap') - \|endif - -" ReDIF -" Only used when the .rdf file was not detected to be XML. -au BufRead,BufNewFile *.rdf call dist#ft#Redif() - -" Remind -au BufNewFile,BufRead .reminders* call s:StarSetf('remind') - -" SGML catalog file -au BufNewFile,BufRead sgml.catalog* call s:StarSetf('catalog') - -" avoid doc files being recognized a shell files -au BufNewFile,BufRead */doc/{,.}bash[_-]completion{,.d,.sh}{,/*} setf text - -" Shell scripts ending in a star -au BufNewFile,BufRead .bashrc*,.bash[_-]profile*,.bash[_-]logout*,.bash[_-]aliases*,bash-fc[-.]*,PKGBUILD*,APKBUILD*,*/{,.}bash[_-]completion{,.d,.sh}{,/*} call dist#ft#SetFileTypeSH("bash") -au BufNewFile,BufRead .kshrc* call dist#ft#SetFileTypeSH("ksh") -au BufNewFile,BufRead .profile* call dist#ft#SetFileTypeSH(getline(1)) - -" Sudoers -au BufNewFile,BufRead */etc/sudoers.d/* call s:StarSetf('sudoers') - -" tcsh scripts ending in a star -au BufNewFile,BufRead .tcshrc* call dist#ft#SetFileTypeShell("tcsh") - -" csh scripts ending in a star -au BufNewFile,BufRead .login*,.cshrc* call dist#ft#CSH() - -" tmux configuration with arbitrary extension -au BufNewFile,BufRead {.,}tmux*.conf* setf tmux - -" VHDL -au BufNewFile,BufRead *.vhdl_[0-9]* call s:StarSetf('vhdl') - -" Vim script -au BufNewFile,BufRead *vimrc* call s:StarSetf('vim') - -" Subversion commit file -au BufNewFile,BufRead svn-commit*.tmp setf svn - -" X resources file -au BufNewFile,BufRead Xresources*,*/app-defaults/*,*/Xresources/* call s:StarSetf('xdefaults') - -" XFree86 config -au BufNewFile,BufRead XF86Config-4* - \ let b:xf86conf_xfree86_version = 4 | call s:StarSetf('xf86conf') -au BufNewFile,BufRead XF86Config* - \ if getline(1) =~ '\<XConfigurator\>' - \| let b:xf86conf_xfree86_version = 3 - \|endif - \|call s:StarSetf('xf86conf') - -" X11 xmodmap -au BufNewFile,BufRead *xmodmap* call s:StarSetf('xmodmap') - -" Xinetd conf -au BufNewFile,BufRead */etc/xinetd.d/* call s:StarSetf('xinetd') - -" yum conf (close enough to dosini) -au BufNewFile,BufRead */etc/yum.repos.d/* call s:StarSetf('dosini') - -" Z-Shell script ending in a star -au BufNewFile,BufRead .zsh*,.zlog*,.zcompdump* call s:StarSetf('zsh') -au BufNewFile,BufRead zsh*,zlog* call s:StarSetf('zsh') - - -" Help files match *.txt but should have a last line that is a modeline. -au BufNewFile,BufRead *.txt - \ if getline('$') !~ 'vim:.*ft=help' - \| setf text - \| endif - -if !exists('g:did_load_ftdetect') - " Use the filetype detect plugins. They may overrule any of the previously - " detected filetypes. - runtime! ftdetect/*.vim - runtime! ftdetect/*.lua -endif - -" NOTE: The above command could have ended the filetypedetect autocmd group -" and started another one. Let's make sure it has ended to get to a consistent -" state. -augroup END - -" Generic configuration file. Use FALLBACK, it's just guessing! -au filetypedetect BufNewFile,BufRead,StdinReadPost * - \ if !did_filetype() && expand("<amatch>") !~ g:ft_ignore_pat - \ && (getline(1) =~ '^#' || getline(2) =~ '^#' || getline(3) =~ '^#' - \ || getline(4) =~ '^#' || getline(5) =~ '^#') | - \ setf FALLBACK conf | - \ endif - - -" If the GUI is already running, may still need to install the Syntax menu. -" Don't do it when the 'M' flag is included in 'guioptions'. -if has("menu") && has("gui_running") - \ && !exists("did_install_syntax_menu") && &guioptions !~# "M" - source <sfile>:p:h/menu.vim -endif - -" Function called for testing all functions defined here. These are -" script-local, thus need to be executed here. -" Returns a string with error messages (hopefully empty). -func TestFiletypeFuncs(testlist) - let output = '' - for f in a:testlist - try - exe f - catch - let output = output . "\n" . f . ": " . v:exception - endtry - endfor - return output -endfunc - -" Restore 'cpoptions' -let &cpo = s:cpo_save -unlet s:cpo_save diff --git a/runtime/ftplugin/abaqus.vim b/runtime/ftplugin/abaqus.vim index 3faeff621a..5931cd921d 100644 --- a/runtime/ftplugin/abaqus.vim +++ b/runtime/ftplugin/abaqus.vim @@ -1,7 +1,7 @@ " Vim filetype plugin file " Language: Abaqus finite element input file (www.abaqus.com) " Maintainer: Carl Osterwisch <costerwi@gmail.com> -" Last Change: 2022 Aug 03 +" Last Change: 2022 Oct 08 " Only do this when not done yet for this buffer if exists("b:did_ftplugin") | finish | endif @@ -66,25 +66,44 @@ if exists("loaded_matchit") && !exists("b:match_words") endif if !exists("no_plugin_maps") && !exists("no_abaqus_maps") - " Define keys used to move [count] keywords backward or forward. - noremap <silent><buffer> [[ ?^\*\a<CR>:nohlsearch<CR> - noremap <silent><buffer> ]] /^\*\a<CR>:nohlsearch<CR> + " Map [[ and ]] keys to move [count] keywords backward or forward + nnoremap <silent><buffer> ]] :call <SID>Abaqus_NextKeyword(1)<CR> + nnoremap <silent><buffer> [[ :call <SID>Abaqus_NextKeyword(-1)<CR> + function! <SID>Abaqus_NextKeyword(direction) + .mark ' + if a:direction < 0 + let flags = 'b' + else + let flags = '' + endif + let l:count = abs(a:direction) * v:count1 + while l:count > 0 && search("^\\*\\a", flags) + let l:count -= 1 + endwhile + endfunction - " Define key to toggle commenting of the current line or range + " Map \\ to toggle commenting of the current line or range noremap <silent><buffer> <LocalLeader><LocalLeader> \ :call <SID>Abaqus_ToggleComment()<CR>j function! <SID>Abaqus_ToggleComment() range - if strpart(getline(a:firstline), 0, 2) == "**" - " Un-comment all lines in range - silent execute a:firstline . ',' . a:lastline . 's/^\*\*//' - else - " Comment all lines in range - silent execute a:firstline . ',' . a:lastline . 's/^/**/' - endif + if strpart(getline(a:firstline), 0, 2) == "**" + " Un-comment all lines in range + silent execute a:firstline . ',' . a:lastline . 's/^\*\*//' + else + " Comment all lines in range + silent execute a:firstline . ',' . a:lastline . 's/^/**/' + endif + endfunction + + " Map \s to swap first two comma separated fields + noremap <silent><buffer> <LocalLeader>s :call <SID>Abaqus_Swap()<CR> + function! <SID>Abaqus_Swap() range + silent execute a:firstline . ',' . a:lastline . 's/\([^*,]*\),\([^,]*\)/\2,\1/' endfunction let b:undo_ftplugin .= "|unmap <buffer> [[|unmap <buffer> ]]" \ . "|unmap <buffer> <LocalLeader><LocalLeader>" + \ . "|unmap <buffer> <LocalLeader>s" endif " Undo must be done in nocompatible mode for <LocalLeader>. diff --git a/runtime/ftplugin/apache.vim b/runtime/ftplugin/apache.vim new file mode 100644 index 0000000000..9f612f5447 --- /dev/null +++ b/runtime/ftplugin/apache.vim @@ -0,0 +1,16 @@ +" Vim filetype plugin +" Language: apache configuration file +" Maintainer: Per Juchtmans <dubgeiser+vimNOSPAM@gmail.com> +" Last Change: 2022 Oct 22 + +if exists("b:did_ftplugin") + finish +endif +let b:did_ftplugin = 1 + +setlocal comments=:# +setlocal commentstring=#\ %s + +let b:undo_ftplugin = "setlocal comments< commentstring<" + +" vim: nowrap sw=2 sts=2 ts=8 noet: 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/checkhealth.vim b/runtime/ftplugin/checkhealth.vim index 3d8e9ace1a..62a1970b4a 100644 --- a/runtime/ftplugin/checkhealth.vim +++ b/runtime/ftplugin/checkhealth.vim @@ -1,20 +1,18 @@ " Vim filetype plugin -" Language: Neovim checkhealth buffer -" Last Change: 2021 Dec 15 +" Language: Nvim :checkhealth buffer +" Last Change: 2022 Nov 10 if exists("b:did_ftplugin") finish endif -runtime! ftplugin/markdown.vim ftplugin/markdown_*.vim ftplugin/markdown/*.vim +runtime! ftplugin/help.vim setlocal wrap breakindent linebreak -setlocal conceallevel=2 concealcursor=nc -setlocal keywordprg=:help let &l:iskeyword='!-~,^*,^|,^",192-255' if exists("b:undo_ftplugin") - let b:undo_ftplugin .= "|setl wrap< bri< lbr< cole< cocu< kp< isk<" + let b:undo_ftplugin .= "|setl wrap< bri< lbr< kp< isk<" else - let b:undo_ftplugin = "setl wrap< bri< lbr< cole< cocu< kp< isk<" + let b:undo_ftplugin = "setl wrap< bri< lbr< kp< isk<" endif 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/cs.vim b/runtime/ftplugin/cs.vim index f53ffcbc8e..0734d11d22 100644 --- a/runtime/ftplugin/cs.vim +++ b/runtime/ftplugin/cs.vim @@ -2,7 +2,7 @@ " Language: C# " Maintainer: Nick Jensen <nickspoon@gmail.com> " Former Maintainer: Johannes Zellner <johannes@zellner.org> -" Last Change: 2021-12-07 +" Last Change: 2022-11-16 " License: Vim (see :h license) " Repository: https://github.com/nickspoons/vim-cs @@ -25,8 +25,9 @@ let b:undo_ftplugin = 'setl com< fo<' if exists('loaded_matchit') && !exists('b:match_words') " #if/#endif support included by default + let b:match_ignorecase = 0 let b:match_words = '\%(^\s*\)\@<=#\s*region\>:\%(^\s*\)\@<=#\s*endregion\>,' - let b:undo_ftplugin .= ' | unlet! b:match_words' + let b:undo_ftplugin .= ' | unlet! b:match_ignorecase b:match_words' endif if (has('gui_win32') || has('gui_gtk')) && !exists('b:browsefilter') 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..88b1fc9d44 100644 --- a/runtime/ftplugin/lua.vim +++ b/runtime/ftplugin/lua.vim @@ -1,46 +1,49 @@ " 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> +" C.D. MacEachern <craig.daniel.maceachern@gmail.com> +" Last Change: 2022 Nov 19 -" 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\)\=' + +" TODO: handle init.lua +setlocal includeexpr=tr(v:fname,'.','/') setlocal suffixesadd=.lua -let b:undo_ftplugin = "setlocal fo< com< cms< sua<" +let b:undo_ftplugin = "setlocal cms< com< def< fo< inex< 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/markdown.vim b/runtime/ftplugin/markdown.vim index fc1d9e068b..2b963f139d 100644 --- a/runtime/ftplugin/markdown.vim +++ b/runtime/ftplugin/markdown.vim @@ -1,7 +1,7 @@ " Vim filetype plugin -" Language: Markdown -" Maintainer: Tim Pope <vimNOSPAM@tpope.org> -" Last Change: 2019 Dec 05 +" Language: Markdown +" Maintainer: Tim Pope <https://github.com/tpope/vim-markdown> +" Last Change: 2022 Oct 13 if exists("b:did_ftplugin") finish @@ -9,18 +9,33 @@ endif runtime! ftplugin/html.vim ftplugin/html_*.vim ftplugin/html/*.vim +let s:keepcpo= &cpo +set cpo&vim + setlocal comments=fb:*,fb:-,fb:+,n:> commentstring=<!--%s--> setlocal formatoptions+=tcqln formatoptions-=r formatoptions-=o -setlocal formatlistpat=^\\s*\\d\\+\\.\\s\\+\\\|^[-*+]\\s\\+\\\|^\\[^\\ze[^\\]]\\+\\]: +setlocal formatlistpat=^\\s*\\d\\+\\.\\s\\+\\\|^\\s*[-*+]\\s\\+\\\|^\\[^\\ze[^\\]]\\+\\]:\\&^.\\{4\\} if exists('b:undo_ftplugin') - let b:undo_ftplugin .= "|setl cms< com< fo< flp<" + let b:undo_ftplugin .= "|setl cms< com< fo< flp< et< ts< sts< sw<" else - let b:undo_ftplugin = "setl cms< com< fo< flp<" + let b:undo_ftplugin = "setl cms< com< fo< flp< et< ts< sts< sw<" +endif + +if get(g:, 'markdown_recommended_style', 1) + setlocal expandtab tabstop=4 softtabstop=4 shiftwidth=4 +endif + +if !exists("g:no_plugin_maps") && !exists("g:no_markdown_maps") + nnoremap <silent><buffer> [[ :<C-U>call search('\%(^#\{1,5\}\s\+\S\\|^\S.*\n^[=-]\+$\)', "bsW")<CR> + nnoremap <silent><buffer> ]] :<C-U>call search('\%(^#\{1,5\}\s\+\S\\|^\S.*\n^[=-]\+$\)', "sW")<CR> + xnoremap <silent><buffer> [[ :<C-U>exe "normal! gv"<Bar>call search('\%(^#\{1,5\}\s\+\S\\|^\S.*\n^[=-]\+$\)', "bsW")<CR> + xnoremap <silent><buffer> ]] :<C-U>exe "normal! gv"<Bar>call search('\%(^#\{1,5\}\s\+\S\\|^\S.*\n^[=-]\+$\)', "sW")<CR> + let b:undo_ftplugin .= '|sil! nunmap <buffer> [[|sil! nunmap <buffer> ]]|sil! xunmap <buffer> [[|sil! xunmap <buffer> ]]' endif function! s:NotCodeBlock(lnum) abort - return synIDattr(synID(v:lnum, 1, 1), 'name') !=# 'markdownCode' + return synIDattr(synID(a:lnum, 1, 1), 'name') !=# 'markdownCode' endfunction function! MarkdownFold() abort @@ -64,11 +79,14 @@ function! MarkdownFoldText() abort return hash_indent.' '.title.' '.linecount endfunction -if has("folding") && exists("g:markdown_folding") +if has("folding") && get(g:, "markdown_folding", 0) setlocal foldexpr=MarkdownFold() setlocal foldmethod=expr setlocal foldtext=MarkdownFoldText() - let b:undo_ftplugin .= " foldexpr< foldmethod< foldtext<" + let b:undo_ftplugin .= "|setl foldexpr< foldmethod< foldtext<" endif +let &cpo = s:keepcpo +unlet s:keepcpo + " vim:set sw=2: diff --git a/runtime/ftplugin/mermaid.vim b/runtime/ftplugin/mermaid.vim new file mode 100644 index 0000000000..fe84ab37cf --- /dev/null +++ b/runtime/ftplugin/mermaid.vim @@ -0,0 +1,49 @@ +" Vim filetype plugin +" Language: Mermaid +" Maintainer: Craig MacEachern <https://github.com/craigmac/vim-mermaid> +" Last Change: 2022 Oct 13 + +if exists("b:did_ftplugin") + finish +endif + +let s:keepcpo= &cpo +set cpo&vim + +" Use mermaid live editor's style +setlocal expandtab +setlocal shiftwidth=2 +setlocal softtabstop=-1 +setlocal tabstop=4 + +" TODO: comments, formatlist stuff, based on what? +setlocal comments=b:#,fb:- +setlocal commentstring=#\ %s +setlocal formatoptions+=tcqln formatoptions-=r formatoptions-=o +setlocal formatlistpat=^\\s*\\d\\+\\.\\s\\+\\\|^\\s*[-*+]\\s\\+\\\|^\\[^\\ze[^\\]]\\+\\]:\\&^.\\{4\\} + +if exists('b:undo_ftplugin') + let b:undo_ftplugin .= "|setl cms< com< fo< flp< et< ts< sts< sw<" +else + let b:undo_ftplugin = "setl cms< com< fo< flp< et< ts< sts< sw<" +endif + +if !exists("g:no_plugin_maps") && !exists("g:no_markdown_maps") + nnoremap <silent><buffer> [[ :<C-U>call search('\%(^#\{1,5\}\s\+\S\\|^\S.*\n^[=-]\+$\)', "bsW")<CR> + nnoremap <silent><buffer> ]] :<C-U>call search('\%(^#\{1,5\}\s\+\S\\|^\S.*\n^[=-]\+$\)', "sW")<CR> + xnoremap <silent><buffer> [[ :<C-U>exe "normal! gv"<Bar>call search('\%(^#\{1,5\}\s\+\S\\|^\S.*\n^[=-]\+$\)', "bsW")<CR> + xnoremap <silent><buffer> ]] :<C-U>exe "normal! gv"<Bar>call search('\%(^#\{1,5\}\s\+\S\\|^\S.*\n^[=-]\+$\)', "sW")<CR> + let b:undo_ftplugin .= '|sil! nunmap <buffer> [[|sil! nunmap <buffer> ]]|sil! xunmap <buffer> [[|sil! xunmap <buffer> ]]' +endif + +" if has("folding") && get(g:, "markdown_folding", 0) +" setlocal foldexpr=MarkdownFold() +" setlocal foldmethod=expr +" setlocal foldtext=MarkdownFoldText() +" let b:undo_ftplugin .= "|setl foldexpr< foldmethod< foldtext<" +" endif + +let &cpo = s:keepcpo +unlet s:keepcpo + +" vim:set sw=2: diff --git a/runtime/ftplugin/obse.vim b/runtime/ftplugin/obse.vim new file mode 100644 index 0000000000..6d865f05ee --- /dev/null +++ b/runtime/ftplugin/obse.vim @@ -0,0 +1,70 @@ +" Vim filetype plugin file +" Language: Oblivion Language (obl) +" Original Creator: Kat <katisntgood@gmail.com> +" Maintainer: Kat <katisntgood@gmail.com> +" Created: August 08, 2021 +" Last Change: 13 November 2022 + +if exists("b:did_ftplugin") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +let b:undo_ftplugin = "setl com< cms<" + +noremap <script> <buffer> <silent> [[ <nop> +noremap <script> <buffer> <silent> ]] <nop> + +noremap <script> <buffer> <silent> [] <nop> +noremap <script> <buffer> <silent> ][ <nop> + +setlocal commentstring=;%s +setlocal comments=:; + +function s:NextSection(type, backwards, visual) + if a:visual + normal! gv + endif + + if a:type == 1 + let pattern = '\v(\n\n^\S|%^)' + let flags = 'e' + elseif a:type == 2 + let pattern = '\v^\S.*' + let flags = '' + endif + + if a:backwards + let dir = '?' + else + let dir = '/' + endif + + execute 'silent normal! ' . dir . pattern . dir . flags . "\r" +endfunction + +noremap <script> <buffer> <silent> ]] + \ :call <SID>NextSection(1, 0, 0)<cr> + +noremap <script> <buffer> <silent> [[ + \ :call <SID>NextSection(1, 1, 0)<cr> + +noremap <script> <buffer> <silent> ][ + \ :call <SID>NextSection(2, 0, 0)<cr> + +noremap <script> <buffer> <silent> [] + \ :call <SID>NextSection(2, 1, 0)<cr> + +vnoremap <script> <buffer> <silent> ]] + \ :<c-u>call <SID>NextSection(1, 0, 1)<cr> +vnoremap <script> <buffer> <silent> [[ + \ :<c-u>call <SID>NextSection(1, 1, 1)<cr> +vnoremap <script> <buffer> <silent> ][ + \ :<c-u>call <SID>NextSection(2, 0, 1)<cr> +vnoremap <script> <buffer> <silent> [] + \ :<c-u>call <SID>NextSection(2, 1, 1)<cr> + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/ftplugin/openvpn.vim b/runtime/ftplugin/openvpn.vim new file mode 100644 index 0000000000..56c0f25b39 --- /dev/null +++ b/runtime/ftplugin/openvpn.vim @@ -0,0 +1,14 @@ +" Vim filetype plugin +" Language: OpenVPN +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Oct 16 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setlocal iskeyword+=-,.,/ +setlocal comments=:#,:; commentstring=#%s + +let b:undo_ftplugin = 'setl isk< com< cms<' diff --git a/runtime/ftplugin/poefilter.vim b/runtime/ftplugin/poefilter.vim new file mode 100644 index 0000000000..92c2def630 --- /dev/null +++ b/runtime/ftplugin/poefilter.vim @@ -0,0 +1,13 @@ +" Vim filetype plugin +" Language: PoE item filter +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Oct 07 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setlocal comments=:# commentstring=#\ %s + +let b:undo_ftplugin = 'setl com< cms<' 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/readline.vim b/runtime/ftplugin/readline.vim index e9ef93ec7f..eba7122347 100644 --- a/runtime/ftplugin/readline.vim +++ b/runtime/ftplugin/readline.vim @@ -1,7 +1,8 @@ " Vim filetype plugin file -" Language: readline(3) configuration file -" Previous Maintainer: Nikolai Weibull <now@bitwi.se> -" Latest Revision: 2008-07-09 +" Language: readline(3) configuration file +" Maintainer: Doug Kearns <dougkearns@gmail.com> +" Previous Maintainer: Nikolai Weibull <now@bitwi.se> +" Last Change: 2022 Dec 09 if exists("b:did_ftplugin") finish @@ -11,9 +12,25 @@ 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 com< cms< fo<" -setlocal comments=:# commentstring=#\ %s formatoptions-=t formatoptions+=croql +if exists("loaded_matchit") && !exists("b:match_words") + let b:match_ignorecase = 0 + let b:match_words = '$if:$else:$endif' + let b:undo_ftplugin ..= " | unlet! b:match_ignorecase b:match_words" +endif + +if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter") + let b:browsefilter = "Readline Intialization Files (inputrc .inputrc)\tinputrc;*.inputrc\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/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/ssa.vim b/runtime/ftplugin/ssa.vim new file mode 100644 index 0000000000..04cc7a9bde --- /dev/null +++ b/runtime/ftplugin/ssa.vim @@ -0,0 +1,13 @@ +" Vim filetype plugin +" Language: SubStation Alpha +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Last Change: 2022 Oct 10 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setlocal comments=:;,:!: commentstring=;\ %s + +let b:undo_ftplugin = 'setl com< cms<' 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..b64bb55d68 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 Nov 27 " Only do this when not done yet for this buffer if exists("b:did_ftplugin") @@ -98,7 +98,7 @@ if exists("loaded_matchit") " func name " require a parenthesis following, then there can be an "endfunc". let b:match_words = - \ '\<\%(fu\%[nction]\|def\)!\=\s\+\S\+(:\%(\%(^\||\)\s*\)\@<=\<retu\%[rn]\>:\%(\%(^\||\)\s*\)\@<=\<\%(endf\%[unction]\|enddef\)\>,' . + \ '\<\%(fu\%[nction]\|def\)!\=\s\+\S\+\s*(:\%(\%(^\||\)\s*\)\@<=\<retu\%[rn]\>:\%(\%(^\||\)\s*\)\@<=\<\%(endf\%[unction]\|enddef\)\>,' . \ '\<\(wh\%[ile]\|for\)\>:\%(\%(^\||\)\s*\)\@<=\<brea\%[k]\>:\%(\%(^\||\)\s*\)\@<=\<con\%[tinue]\>:\%(\%(^\||\)\s*\)\@<=\<end\(w\%[hile]\|fo\%[r]\)\>,' . \ '\<if\>:\%(\%(^\||\)\s*\)\@<=\<el\%[seif]\>:\%(\%(^\||\)\s*\)\@<=\<en\%[dif]\>,' . \ '{:},' . diff --git a/runtime/ftplugin/zig.vim b/runtime/ftplugin/zig.vim new file mode 100644 index 0000000000..e740a52849 --- /dev/null +++ b/runtime/ftplugin/zig.vim @@ -0,0 +1,66 @@ +" Vim filetype plugin file +" Language: Zig +" Upstream: https://github.com/ziglang/zig.vim + +" Only do this when not done yet for this buffer +if exists("b:did_ftplugin") + finish +endif + +let b:did_ftplugin = 1 + +let s:cpo_orig = &cpo +set cpo&vim + +compiler zig_build + +" Match Zig builtin fns +setlocal iskeyword+=@-@ + +" Recomended code style, no tabs and 4-space indentation +setlocal expandtab +setlocal tabstop=8 +setlocal softtabstop=4 +setlocal shiftwidth=4 + +setlocal formatoptions-=t formatoptions+=croql + +setlocal suffixesadd=.zig,.zir + +if has('comments') + setlocal comments=:///,://!,://,:\\\\ + setlocal commentstring=//\ %s +endif + +if has('find_in_path') + let &l:includeexpr='substitute(v:fname, "^([^.])$", "\1.zig", "")' + let &l:include='\v(\@import>|\@cInclude>|^\s*\#\s*include)' +endif + +let &l:define='\v(<fn>|<const>|<var>|^\s*\#\s*define)' + +if !exists('g:zig_std_dir') && exists('*json_decode') && executable('zig') + silent let s:env = system('zig env') + if v:shell_error == 0 + let g:zig_std_dir = json_decode(s:env)['std_dir'] + endif + unlet! s:env +endif + +if exists('g:zig_std_dir') + let &l:path = &l:path . ',' . g:zig_std_dir +endif + +let b:undo_ftplugin = + \ 'setl isk< et< ts< sts< sw< fo< sua< mp< com< cms< inex< inc< pa<' + +augroup vim-zig + autocmd! * <buffer> + autocmd BufWritePre <buffer> if get(g:, 'zig_fmt_autosave', 1) | call zig#fmt#Format() | endif +augroup END + +let b:undo_ftplugin .= '|au! vim-zig * <buffer>' + +let &cpo = s:cpo_orig +unlet s:cpo_orig +" vim: tabstop=8 shiftwidth=4 softtabstop=4 expandtab 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/nginx.vim b/runtime/indent/nginx.vim index 8cef7662e0..65506099f4 100644 --- a/runtime/indent/nginx.vim +++ b/runtime/indent/nginx.vim @@ -1,19 +1,78 @@ " Vim indent file " Language: nginx.conf " Maintainer: Chris Aumann <me@chr4.org> -" Last Change: 2022 Apr 06 +" Last Change: 2022 Dec 01 -if exists("b:did_indent") - finish +" Only load this indent file when no other was loaded. +if exists('b:did_indent') + finish endif let b:did_indent = 1 -setlocal indentexpr= +setlocal indentexpr=GetNginxIndent() -" cindent actually works for nginx' simple file structure -setlocal cindent +setlocal indentkeys=0{,0},0#,!^F,o,O -" Just make sure that the comments are not reset as defs would be. -setlocal cinkeys-=0# +let b:undo_indent = 'setl inde< indk<' -let b:undo_indent = "setl inde< cin< cink<" +" Only define the function once. +if exists('*GetNginxIndent') + finish +endif + +function GetNginxIndent() abort + let plnum = s:PrevNotAsBlank(v:lnum - 1) + + " Hit the start of the file, use zero indent. + if plnum == 0 + return 0 + endif + + let ind = indent(plnum) + + " Add a 'shiftwidth' after '{' + if s:AsEndWith(getline(plnum), '{') + let ind = ind + shiftwidth() + end + + " Subtract a 'shiftwidth' on '}' + " This is the part that requires 'indentkeys'. + if getline(v:lnum) =~ '^\s*}' + let ind = ind - shiftwidth() + endif + + let pplnum = s:PrevNotAsBlank(plnum - 1) + + if s:IsLineContinuation(plnum) + if !s:IsLineContinuation(pplnum) + let ind = ind + shiftwidth() + end + else + if s:IsLineContinuation(pplnum) + let ind = ind - shiftwidth() + end + endif + + return ind +endfunction + +" Find the first line at or above {lnum} that is non-blank and not a comment. +function s:PrevNotAsBlank(lnum) abort + let lnum = prevnonblank(a:lnum) + while lnum > 0 + if getline(lnum) !~ '^\s*#' + break + endif + let lnum = prevnonblank(lnum - 1) + endwhile + return lnum +endfunction + +" Check whether {line} ends with {pat}, ignoring trailing comments. +function s:AsEndWith(line, pat) abort + return a:line =~ a:pat . '\m\s*\%(#.*\)\?$' +endfunction + +function s:IsLineContinuation(lnum) abort + return a:lnum > 0 && !s:AsEndWith(getline(a:lnum), '[;{}]') +endfunction diff --git a/runtime/indent/obse.vim b/runtime/indent/obse.vim new file mode 100644 index 0000000000..6603723dba --- /dev/null +++ b/runtime/indent/obse.vim @@ -0,0 +1,55 @@ +" Vim indent file +" Language: Oblivion Language (obl) +" Original Creator: Kat <katisntgood@gmail.com> +" Maintainer: Kat <katisntgood@gmail.com> +" Created: 01 November 2021 +" Last Change: 13 November 2022 + +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 +let b:undo_indent = 'setlocal indentkeys< indentexpr<' + +setlocal indentexpr=GetOblIndent() +setlocal indentkeys+==~endif,=~else,=~loop,=~end + +if exists("*GetOblIndent") + finish +endif +let s:keepcpo = &cpo +set cpo&vim + +let s:SKIP_LINES = '^\s*\(;.*\)' +function! GetOblIndent() + + let lnum = prevnonblank(v:lnum - 1) + let cur_text = getline(v:lnum) + if lnum == 0 + return 0 + endif + let prev_text = getline(lnum) + let found_cont = 0 + let ind = indent(lnum) + + " indent next line on start terms + let i = match(prev_text, '\c^\s*\(\s\+\)\?\(\(if\|while\|foreach\|begin\|else\%[if]\)\>\)') + if i >= 0 + let ind += shiftwidth() + if strpart(prev_text, i, 1) == '|' && has('syntax_items') + \ && synIDattr(synID(lnum, i, 1), "name") =~ '\(Comment\|String\)$' + let ind -= shiftwidth() + endif + endif + " indent current line on end/else terms + if cur_text =~ '\c^\s*\(\s\+\)\?\(\(loop\|endif\|else\%[if]\)\>\)' + let ind = ind - shiftwidth() + " if we are at a begin block just go to column 0 + elseif cur_text =~ '\c^\s*\(\s\+\)\?\(\(begin\|end\)\>\)' + let ind = 0 + endif + return ind +endfunction + +let &cpo = s:keepcpo +unlet s:keepcpo 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/vb.in b/runtime/indent/testdir/vb.in new file mode 100644 index 0000000000..1653ae6f80 --- /dev/null +++ b/runtime/indent/testdir/vb.in @@ -0,0 +1,134 @@ +' vim: filetype=vb shiftwidth=4 expandtab +' +' START_INDENT +Public Type GEmployeeRecord ' Create user-defined type. +ID As Integer ' Define elements of data type. +Name As String * 20 +Address As String * 30 +Phone As Long +HireDate As Date +End Type + +Public Enum InterfaceColors +icMistyRose = &HE1E4FF& +icSlateGray = &H908070& +icDodgerBlue = &HFF901E& +icDeepSkyBlue = &HFFBF00& +icSpringGreen = &H7FFF00& +icForestGreen = &H228B22& +icGoldenrod = &H20A5DA& +icFirebrick = &H2222B2& +End Enum + +Enum SecurityLevel +IllegalEntry = -1 +SecurityLevel1 = 0 +SecurityLevel2 = 1 +End Enum + +Public Function TestConditional (number As Integer, ext As String) As Boolean +Dim inRange As Boolean + +Select Case number +Case <= 0 +inRange = False +Case > 10 +inRange = False +Case Else +inRange = True +End Select + +' This is a special case identified in the indent script. +Select Case number +End Select + +If ext = ".xlm" Then +If inRange Then +TestConditional = True +Else +TestConditional = False +End If +ElseIf ext = ".xlsx" Then +If inRange Then +TestConditional = False +Else +TestConditional = True +End If +Else +TestConditional = False +End If +End Function + +Private Sub TestIterators (lLimit As Integer, uLimit As Integer) +Dim a() As Variant +Dim elmt As Variant +Dim found As Boolean +Dim indx As Integer +Const specialValue As Integer = 5 + +If uLimit < lLimit Then +Exit Sub +End If + +ReDim a(lLimit To uLimit) +For indx=lLimit To Ulimit +a(indx) = 2 * indx +Next indx + +found = False +For Each elmt in a +If elmt = specialValue Then +found = True +End If +Next elmt + +If found then +indx = uLimit +Do While indx >= lLimit +indx = indx - 1 +Loop +End If + +End Sub + +Public Sub TestMultiline (cellAddr As String, rowNbr As Long) +Dim rng As Range + +Set rng = Range(cellAddr) +With rng +.Cells(1,1).Value = _ +"Line 1 of multiline string; " & _ +"Line 2 of multiline string; " & _ +"Line 3 of multiline string" +End With + +' The following lines have whitespace after the underscore character +' and therefore do not form a valid multiline statement. The indent +' script correctly treats them as four single line statements contrary +' to the author's obvious indent. +rng..Cells(1,1).Value = _ +"Line 1 of multiline string; " & _ +"Line 2 of multiline string; " & _ +"Line 3 of multiline string" + +End Sub + +Private Sub TestStmtLabel() +GoTo stmtLabel + +' Statement labels are never indented +stmtLabel: + +End Sub + +Sub TestTypeKeyword() +Type EmployeeRecord ' Create user-defined type. +ID As Integer ' Define elements of data type. +Name As String * 20 +Address As String * 30 +Phone As Long +HireDate As Date +End Type +Dim varType As EmployeeRecord +End Sub +' END_INDENT diff --git a/runtime/indent/testdir/vb.ok b/runtime/indent/testdir/vb.ok new file mode 100644 index 0000000000..143c688708 --- /dev/null +++ b/runtime/indent/testdir/vb.ok @@ -0,0 +1,134 @@ +' vim: filetype=vb shiftwidth=4 expandtab +' +' START_INDENT +Public Type GEmployeeRecord ' Create user-defined type. + ID As Integer ' Define elements of data type. + Name As String * 20 + Address As String * 30 + Phone As Long + HireDate As Date +End Type + +Public Enum InterfaceColors + icMistyRose = &HE1E4FF& + icSlateGray = &H908070& + icDodgerBlue = &HFF901E& + icDeepSkyBlue = &HFFBF00& + icSpringGreen = &H7FFF00& + icForestGreen = &H228B22& + icGoldenrod = &H20A5DA& + icFirebrick = &H2222B2& +End Enum + +Enum SecurityLevel + IllegalEntry = -1 + SecurityLevel1 = 0 + SecurityLevel2 = 1 +End Enum + +Public Function TestConditional (number As Integer, ext As String) As Boolean + Dim inRange As Boolean + + Select Case number + Case <= 0 + inRange = False + Case > 10 + inRange = False + Case Else + inRange = True + End Select + + ' This is a special case identified in the indent script. + Select Case number + End Select + + If ext = ".xlm" Then + If inRange Then + TestConditional = True + Else + TestConditional = False + End If + ElseIf ext = ".xlsx" Then + If inRange Then + TestConditional = False + Else + TestConditional = True + End If + Else + TestConditional = False + End If +End Function + +Private Sub TestIterators (lLimit As Integer, uLimit As Integer) + Dim a() As Variant + Dim elmt As Variant + Dim found As Boolean + Dim indx As Integer + Const specialValue As Integer = 5 + + If uLimit < lLimit Then + Exit Sub + End If + + ReDim a(lLimit To uLimit) + For indx=lLimit To Ulimit + a(indx) = 2 * indx + Next indx + + found = False + For Each elmt in a + If elmt = specialValue Then + found = True + End If + Next elmt + + If found then + indx = uLimit + Do While indx >= lLimit + indx = indx - 1 + Loop + End If + +End Sub + +Public Sub TestMultiline (cellAddr As String, rowNbr As Long) + Dim rng As Range + + Set rng = Range(cellAddr) + With rng + .Cells(1,1).Value = _ + "Line 1 of multiline string; " & _ + "Line 2 of multiline string; " & _ + "Line 3 of multiline string" + End With + + ' The following lines have whitespace after the underscore character + ' and therefore do not form a valid multiline statement. The indent + ' script correctly treats them as four single line statements contrary + ' to the author's obvious indent. + rng..Cells(1,1).Value = _ + "Line 1 of multiline string; " & _ + "Line 2 of multiline string; " & _ + "Line 3 of multiline string" + +End Sub + +Private Sub TestStmtLabel() + GoTo stmtLabel + + ' Statement labels are never indented +stmtLabel: + +End Sub + +Sub TestTypeKeyword() + Type EmployeeRecord ' Create user-defined type. + ID As Integer ' Define elements of data type. + Name As String * 20 + Address As String * 30 + Phone As Long + HireDate As Date + End Type + Dim varType As EmployeeRecord +End Sub +' END_INDENT 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/vb.vim b/runtime/indent/vb.vim index 4d05345565..bc7142f428 100644 --- a/runtime/indent/vb.vim +++ b/runtime/indent/vb.vim @@ -1,8 +1,12 @@ " Vim indent file " Language: VisualBasic (ft=vb) / Basic (ft=basic) / SaxBasic (ft=vb) " Author: Johannes Zellner <johannes@zellner.org> +" Maintainer: Michael Soyka (mssr953@gmail.com) " Last Change: Fri, 18 Jun 2004 07:22:42 CEST " Small update 2010 Jul 28 by Maxim Kim +" 2022/12/15: add support for multiline statements. +" 2022/12/21: move VbGetIndent from global to script-local scope +" 2022/12/26: recognize "Type" keyword if exists("b:did_indent") finish @@ -10,28 +14,33 @@ endif let b:did_indent = 1 setlocal autoindent -setlocal indentexpr=VbGetIndent(v:lnum) +setlocal indentexpr=s:VbGetIndent(v:lnum) setlocal indentkeys& -setlocal indentkeys+==~else,=~elseif,=~end,=~wend,=~case,=~next,=~select,=~loop,<:> +setlocal indentkeys+==~else,=~elseif,=~end,=~wend,=~case,=~next,=~select,=~loop let b:undo_indent = "set ai< indentexpr< indentkeys<" " Only define the function once. -if exists("*VbGetIndent") +if exists("*s:VbGetIndent") finish endif -fun! VbGetIndent(lnum) +function s:VbGetIndent(lnum) + let this_lnum = a:lnum + let this_line = getline(this_lnum) + " labels and preprocessor get zero indent immediately - let this_line = getline(a:lnum) let LABELS_OR_PREPROC = '^\s*\(\<\k\+\>:\s*$\|#.*\)' if this_line =~? LABELS_OR_PREPROC return 0 endif + + " Get the current value of "shiftwidth" + let bShiftwidth = shiftwidth() " Find a non-blank line above the current line. " Skip over labels and preprocessor directives. - let lnum = a:lnum + let lnum = this_lnum while lnum > 0 let lnum = prevnonblank(lnum - 1) let previous_line = getline(lnum) @@ -45,34 +54,102 @@ fun! VbGetIndent(lnum) return 0 endif - let ind = indent(lnum) + " Variable "previous_line" now contains the text in buffer line "lnum". + + " Multi-line statements have the underscore character at end-of-line: + " + " object.method(arguments, _ + " arguments, _ + " arguments) + " + " and require extra logic to determine the correct indentation. + " + " Case 1: Line "lnum" is the first line of a multiline statement. + " Line "lnum" will have a trailing underscore character + " but the preceding non-blank line does not. + " Line "this_lnum" will be indented relative to "lnum". + " + " Case 2: Line "lnum" is the last line of a multiline statement. + " Line "lnum" will not have a trailing underscore character + " but the preceding non-blank line will. + " Line "this_lnum" will have the same indentation as the starting + " line of the multiline statement. + " + " Case 3: Line "lnum" is neither the first nor last line. + " Lines "lnum" and "lnum-1" will have a trailing underscore + " character. + " Line "this_lnum" will have the same indentation as the preceding + " line. + " + " No matter which case it is, the starting line of the statement must be + " found. It will be assumed that multiline statements cannot have + " intermingled comments, statement labels, preprocessor directives or + " blank lines. + " + let lnum_is_continued = (previous_line =~ '_$') + if lnum > 1 + let before_lnum = prevnonblank(lnum-1) + let before_previous_line = getline(before_lnum) + else + let before_lnum = 0 + let before_previous_line = "" + endif + + if before_previous_line !~ '_$' + " Variable "previous_line" contains the start of a statement. + " + let ind = indent(lnum) + if lnum_is_continued + let ind += bShiftwidth + endif + elseif ! lnum_is_continued + " Line "lnum" contains the last line of a multiline statement. + " Need to find where this multiline statement begins + " + while before_lnum > 0 + let before_lnum -= 1 + if getline(before_lnum) !~ '_$' + let before_lnum += 1 + break + endif + endwhile + if before_lnum == 0 + let before_lnum = 1 + endif + let previous_line = getline(before_lnum) + let ind = indent(before_lnum) + else + " Line "lnum" is not the first or last line of a multiline statement. + " + let ind = indent(lnum) + endif " Add - if previous_line =~? '^\s*\<\(begin\|\%(\%(private\|public\|friend\)\s\+\)\=\%(function\|sub\|property\)\|select\|case\|default\|if\|else\|elseif\|do\|for\|while\|enum\|with\)\>' - let ind = ind + shiftwidth() + if previous_line =~? '^\s*\<\(begin\|\%(\%(private\|public\|friend\)\s\+\)\=\%(function\|sub\|property\|enum\|type\)\|select\|case\|default\|if\|else\|elseif\|do\|for\|while\|with\)\>' + let ind = ind + bShiftwidth endif " Subtract if this_line =~? '^\s*\<end\>\s\+\<select\>' if previous_line !~? '^\s*\<select\>' - let ind = ind - 2 * shiftwidth() + let ind = ind - 2 * bShiftwidth else " this case is for an empty 'select' -- 'end select' " (w/o any case statements) like: " " select case readwrite " end select - let ind = ind - shiftwidth() + let ind = ind - bShiftwidth endif elseif this_line =~? '^\s*\<\(end\|else\|elseif\|until\|loop\|next\|wend\)\>' - let ind = ind - shiftwidth() + let ind = ind - bShiftwidth elseif this_line =~? '^\s*\<\(case\|default\)\>' if previous_line !~? '^\s*\<select\>' - let ind = ind - shiftwidth() + let ind = ind - bShiftwidth endif endif return ind -endfun +endfunction " vim:sw=4 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..f6fe350a8f --- /dev/null +++ b/runtime/indent/vue.vim @@ -0,0 +1,14 @@ +" Vim indent file placeholder +" Language: Vue +" Maintainer: None, please volunteer if you have a real Vue indent script +" Last Change: 2022 Dec 24 + +" Only load this indent file when no other was loaded. +if exists("b:did_indent") + finish +endif +" don't set b:did_indent, otherwise html indenting won't be activated +" 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/indent/zig.vim b/runtime/indent/zig.vim new file mode 100644 index 0000000000..e3ce8aa410 --- /dev/null +++ b/runtime/indent/zig.vim @@ -0,0 +1,80 @@ +" Vim filetype indent file +" Language: Zig +" Upstream: https://github.com/ziglang/zig.vim + +" Only load this indent file when no other was loaded. +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +if (!has("cindent") || !has("eval")) + finish +endif + +setlocal cindent + +" L0 -> 0 indent for jump labels (i.e. case statement in c). +" j1 -> indenting for "javascript object declarations" +" J1 -> see j1 +" w1 -> starting a new line with `(` at the same indent as `(` +" m1 -> if `)` starts a line, match its indent with the first char of its +" matching `(` line +" (s -> use one indent, when starting a new line after a trailing `(` +setlocal cinoptions=L0,m1,(s,j1,J1,l1 + +" cinkeys: controls what keys trigger indent formatting +" 0{ -> { +" 0} -> } +" 0) -> ) +" 0] -> ] +" !^F -> make CTRL-F (^F) reindent the current line when typed +" o -> when <CR> or `o` is used +" O -> when the `O` command is used +setlocal cinkeys=0{,0},0),0],!^F,o,O + +setlocal indentexpr=GetZigIndent(v:lnum) + +let b:undo_indent = "setlocal cindent< cinkeys< cinoptions< indentexpr<" + +function! GetZigIndent(lnum) + let curretLineNum = a:lnum + let currentLine = getline(a:lnum) + + " cindent doesn't handle multi-line strings properly, so force no indent + if currentLine =~ '^\s*\\\\.*' + return -1 + endif + + let prevLineNum = prevnonblank(a:lnum-1) + let prevLine = getline(prevLineNum) + + " for lines that look like + " }, + " }; + " try treating them the same as a } + if prevLine =~ '\v^\s*},$' + if currentLine =~ '\v^\s*};$' || currentLine =~ '\v^\s*}$' + return indent(prevLineNum) - 4 + endif + return indent(prevLineNum-1) - 4 + endif + if currentLine =~ '\v^\s*},$' + return indent(prevLineNum) - 4 + endif + if currentLine =~ '\v^\s*};$' + return indent(prevLineNum) - 4 + endif + + + " cindent doesn't handle this case correctly: + " switch (1): { + " 1 => true, + " ~ + " ^---- indents to here + if prevLine =~ '.*=>.*,$' && currentLine !~ '.*}$' + return indent(prevLineNum) + endif + + return cindent(a:lnum) +endfunction diff --git a/runtime/lua/_vim9script.lua b/runtime/lua/_vim9script.lua new file mode 100644 index 0000000000..363d061451 --- /dev/null +++ b/runtime/lua/_vim9script.lua @@ -0,0 +1,650 @@ +------------------------------------------------------------------------------- +-- This file is auto generated by vim9jit. Do not edit by hand. +-- All content is in the source repository. +-- Bugs should be reported to: github.com/tjdevries/vim9jit +-- +-- In addition, this file is considered "private" by neovim. You should +-- not expect any of the APIs, functions, etc to be stable. They are subject +-- to change at any time. +------------------------------------------------------------------------------- + +local vim9 = (function() + local M = {} + + M.ternary = function(cond, if_true, if_false) + if cond then + if type(if_true) == 'function' then + return if_true() + else + return if_true + end + else + if type(if_false) == 'function' then + return if_false() + else + return if_false + end + end + end + + M.fn_ref = function(module, name, copied, ...) + for _, val in ipairs({ ... }) do + table.insert(copied, val) + end + + local funcref = name + if type(funcref) == 'function' then + return funcref(unpack(copied)) + elseif type(funcref) == 'string' then + if vim.fn.exists('*' .. funcref) == 1 then + return vim.fn[funcref](unpack(copied)) + end + + if module[funcref] then + module[funcref](unpack(copied)) + end + + error('unknown function: ' .. funcref) + else + error(string.format('unable to call funcref: %s', funcref)) + end + end + + M.fn_mut = function(name, args, info) + local result = vim.fn._Vim9ScriptFn(name, args) + for idx, val in pairs(result[2]) do + M.replace(args[idx], val) + end + + -- Substitute returning the reference to the + -- returned value + if info.replace then + return args[info.replace + 1] + end + + return result[1] + end + + M.replace = function(orig, new) + if type(orig) == 'table' and type(new) == 'table' then + for k in pairs(orig) do + orig[k] = nil + end + + for k, v in pairs(new) do + orig[k] = v + end + + return orig + end + + return new + end + + M.index = function(obj, idx) + if vim.tbl_islist(obj) then + if idx < 0 then + return obj[#obj + idx + 1] + else + return obj[idx + 1] + end + elseif type(obj) == 'table' then + return obj[idx] + elseif type(obj) == 'string' then + return string.sub(obj, idx + 1, idx + 1) + end + + error('invalid type for indexing: ' .. vim.inspect(obj)) + end + + M.index_expr = function(idx) + if type(idx) == 'string' then + return idx + elseif type(idx) == 'number' then + return idx + 1 + else + error(string.format('not yet handled: %s', vim.inspect(idx))) + end + end + + M.slice = function(obj, start, finish) + if start == nil then + start = 0 + end + + if start < 0 then + start = #obj + start + end + assert(type(start) == 'number') + + if finish == nil then + finish = #obj + end + + if finish < 0 then + finish = #obj + finish + end + assert(type(finish) == 'number') + + local slicer + if vim.tbl_islist(obj) then + slicer = vim.list_slice + elseif type(obj) == 'string' then + slicer = string.sub + else + error('invalid type for slicing: ' .. vim.inspect(obj)) + end + + return slicer(obj, start + 1, finish + 1) + end + + -- Currently unused, but this could be used to embed vim9jit within a + -- running nvim application and transpile "on the fly" as files are + -- sourced. There would still need to be some work done to make that + -- work correctly with imports and what not, but overall it could + -- work well for calling ":source X" from within a vimscript/vim9script + -- function + M.make_source_cmd = function() + local group = vim.api.nvim_create_augroup('vim9script-source', {}) + vim.api.nvim_create_autocmd('SourceCmd', { + pattern = '*.vim', + group = group, + callback = function(a) + local file = vim.fn.readfile(a.file) + for _, line in ipairs(file) do + -- TODO: Or starts with def <something> + -- You can use def in legacy vim files + if vim.startswith(line, 'vim9script') then + -- TODO: Use the rust lib to actually + -- generate the corresponding lua code and then + -- execute that (instead of sourcing it directly) + return + end + end + + vim.api.nvim_exec(table.concat(file, '\n'), false) + end, + }) + end + + M.iter = function(expr) + if vim.tbl_islist(expr) then + return ipairs(expr) + else + return pairs(expr) + end + end + + M.ITER_DEFAULT = 0 + M.ITER_CONTINUE = 1 + M.ITER_BREAK = 2 + M.ITER_RETURN = 3 + + return M +end)() + +vim.cmd([[ +function! _Vim9ScriptFn(name, args) abort + try + let ret = function(a:name, a:args)() + catch + echo "Failed..." + echo a:name + echo a:args + + throw v:errmsg + endtry + + return [ret, a:args] +endfunction +]]) + +vim9['autoload'] = (function() + return function(path) + return loadfile(path)() + end +end)() +vim9['bool'] = (function() + return function(...) + return vim9.convert.to_vim_bool(...) + end +end)() +vim9['convert'] = (function() + local M = {} + + M.decl_bool = function(val) + if type(val) == 'boolean' then + return val + elseif type(val) == 'number' then + if val == 0 then + return false + elseif val == 1 then + return true + else + error(string.format('bad number passed to bool declaration: %s', val)) + end + end + + error(string.format('invalid bool declaration: %s', vim.inspect(val))) + end + + M.decl_dict = function(val) + if type(val) == 'nil' then + return vim.empty_dict() + elseif type(val) == 'table' then + if vim.tbl_isempty(val) then + return vim.empty_dict() + elseif vim.tbl_islist(val) then + error(string.format('Cannot pass list to dictionary? %s', vim.inspect(val))) + else + return val + end + end + + error(string.format('invalid dict declaration: %s', vim.inspect(val))) + end + + M.to_vim_bool = function(val) + if type(val) == 'boolean' then + return val + elseif type(val) == 'number' then + return val ~= 0 + elseif type(val) == 'string' then + return string.len(val) ~= 0 + elseif type(val) == 'table' then + return not vim.tbl_isempty(val) + elseif val == nil then + return false + end + + error('unhandled type: ' .. vim.inspect(val)) + end + + return M +end)() +vim9['fn'] = (function() + local M = {} + + M.insert = function(list, item, idx) + if idx == nil then + idx = 1 + end + + table.insert(list, idx + 1, item) + + return list + end + + M.extend = function(left, right, expr3) + if expr3 ~= nil then + error("haven't written this code yet") + end + + if vim.tbl_islist(right) then + vim.list_extend(left, right) + return left + else + -- local result = vim.tbl_extend(left, right) + for k, v in pairs(right) do + left[k] = v + end + + return left + end + end + + M.add = function(list, item) + table.insert(list, item) + return list + end + + M.has_key = function(obj, key) + return not not obj[key] + end + + M.prop_type_add = function(...) + local args = { ... } + print('[prop_type_add]', vim.inspect(args)) + end + + do + local has_overrides = { + -- We do have vim9script ;) that's this plugin + ['vim9script'] = true, + + -- Include some vim patches that are sometimes required by variuos vim9script plugins + -- that we implement via vim9jit + [ [[patch-8.2.2261]] ] = true, + [ [[patch-8.2.4257]] ] = true, + } + + M.has = function(patch) + if has_overrides[patch] then + return true + end + + return vim.fn.has(patch) + end + end + + --[=[ +Currently missing patch, can be removed in the future. + +readdirex({directory} [, {expr} [, {dict}]]) *readdirex()* + Extended version of |readdir()|. + Return a list of Dictionaries with file and directory + information in {directory}. + This is useful if you want to get the attributes of file and + directory at the same time as getting a list of a directory. + This is much faster than calling |readdir()| then calling + |getfperm()|, |getfsize()|, |getftime()| and |getftype()| for + each file and directory especially on MS-Windows. + The list will by default be sorted by name (case sensitive), + the sorting can be changed by using the optional {dict} + argument, see |readdir()|. + + The Dictionary for file and directory information has the + following items: + group Group name of the entry. (Only on Unix) + name Name of the entry. + perm Permissions of the entry. See |getfperm()|. + size Size of the entry. See |getfsize()|. + time Timestamp of the entry. See |getftime()|. + type Type of the entry. + On Unix, almost same as |getftype()| except: + Symlink to a dir "linkd" + Other symlink "link" + On MS-Windows: + Normal file "file" + Directory "dir" + Junction "junction" + Symlink to a dir "linkd" + Other symlink "link" + Other reparse point "reparse" + user User name of the entry's owner. (Only on Unix) + On Unix, if the entry is a symlink, the Dictionary includes + the information of the target (except the "type" item). + On MS-Windows, it includes the information of the symlink + itself because of performance reasons. +--]=] + M.readdirex = function(dir) + local files = vim.fn.readdir(dir) + local direx = {} + for _, f in ipairs(files) do + table.insert(direx, { + name = f, + type = vim.fn.getftype(f), + }) + end + + return direx + end + + M.mapnew = function(tbl, expr) + return vim.fn.map(tbl, expr) + end + + M.typename = function(val) + local ty = type(val) + if ty == 'string' then + return 'string' + elseif ty == 'boolean' then + return 'bool' + elseif ty == 'number' then + return 'number' + else + error(string.format('typename: %s', val)) + end + end + + -- Popup menu stuff: Could be rolled into other plugin later + -- but currently is here for testing purposes (and implements + -- some very simple compat layers at the moment) + do + local pos_map = { + topleft = 'NW', + topright = 'NE', + botleft = 'SW', + botright = 'SE', + } + + M.popup_menu = function(_, options) + -- print "OPTIONS:" + + local buf = vim.api.nvim_create_buf(false, true) + local win = vim.api.nvim_open_win(buf, true, { + relative = 'editor', + style = 'minimal', + anchor = pos_map[options.pos], + height = options.maxheight or options.minheight, + width = options.maxwidth or options.minwidth, + row = options.line, + col = options.col, + }) + + if options.filter then + local loop + loop = function() + vim.cmd([[redraw!]]) + local ok, ch = pcall(vim.fn.getcharstr) + if not ok then + return + end -- interrupted + + if ch == '<C-C>' then + return + end + + if not require('vim9script').bool(options.filter(nil, ch)) then + vim.cmd.normal(ch) + end + + vim.schedule(loop) + end + + vim.schedule(loop) + end + + return win + end + + M.popup_settext = function(id, text) + if type(text) == 'string' then + -- text = vim.split(text, "\n") + error("Haven't handled string yet") + end + + local lines = {} + for _, obj in ipairs(text) do + table.insert(lines, obj.text) + end + + vim.api.nvim_buf_set_lines(vim.api.nvim_win_get_buf(id), 0, -1, false, lines) + end + + M.popup_filter_menu = function() + print('ok, just pretend we filtered the menu') + end + + M.popup_setoptions = function(id, _) + print('setting options...', id) + end + end + + M = setmetatable(M, { + __index = vim.fn, + }) + + return M +end)() +vim9['heredoc'] = (function() + local M = {} + + M.trim = function(lines) + local min_whitespace = 9999 + for _, line in ipairs(lines) do + local _, finish = string.find(line, '^%s*') + min_whitespace = math.min(min_whitespace, finish) + end + + local trimmed_lines = {} + for _, line in ipairs(lines) do + table.insert(trimmed_lines, string.sub(line, min_whitespace + 1)) + end + + return trimmed_lines + end + + return M +end)() +vim9['import'] = (function() + local imported = {} + imported.autoload = setmetatable({}, { + __index = function(_, name) + local luaname = 'autoload/' .. string.gsub(name, '%.vim$', '.lua') + local runtime_file = vim.api.nvim_get_runtime_file(luaname, false)[1] + if not runtime_file then + error('unable to find autoload file:' .. name) + end + + return imported.absolute[vim.fn.fnamemodify(runtime_file, ':p')] + end, + }) + + imported.absolute = setmetatable({}, { + __index = function(self, name) + if vim.loop.fs_stat(name) then + local result = loadfile(name)() + rawset(self, name, result) + + return result + end + + error(string.format('unabled to find absolute file: %s', name)) + end, + }) + + return function(info) + local name = info.name + + if info.autoload then + return imported.autoload[info.name] + end + + local debug_info = debug.getinfo(2, 'S') + local sourcing_path = vim.fn.fnamemodify(string.sub(debug_info.source, 2), ':p') + + -- Relative paths + if vim.startswith(name, '../') or vim.startswith(name, './') then + local luaname = string.gsub(name, '%.vim$', '.lua') + local directory = vim.fn.fnamemodify(sourcing_path, ':h') + local search = directory .. '/' .. luaname + return imported.absolute[search] + end + + if vim.startswith(name, '/') then + error('absolute path') + -- local luaname = string.gsub(name, "%.vim", ".lua") + -- local runtime_file = vim.api.nvim_get_runtime_file(luaname, false)[1] + -- if runtime_file then + -- runtime_file = vim.fn.fnamemodify(runtime_file, ":p") + -- return loadfile(runtime_file)() + -- end + end + + error('Unhandled case' .. vim.inspect(info) .. vim.inspect(debug_info)) + end +end)() +vim9['ops'] = (function() + local lib = vim9 + + local M = {} + + M['And'] = function(left, right) + return lib.bool(left) and lib.bool(right) + end + + M['Or'] = function(left, right) + return lib.bool(left) or lib.bool(right) + end + + M['Plus'] = function(left, right) + return left + right + end + + M['Multiply'] = function(left, right) + return left * right + end + + M['Divide'] = function(left, right) + return left / right + end + + M['StringConcat'] = function(left, right) + return left .. right + end + + M['EqualTo'] = function(left, right) + return left == right + end + + M['NotEqualTo'] = function(left, right) + return not M['EqualTo'](left, right) + end + + M['LessThan'] = function(left, right) + return left < right + end + + M['LessThanOrEqual'] = function(left, right) + return left <= right + end + + M['GreaterThan'] = function(left, right) + return left > right + end + + M['GreaterThanOrEqual'] = function(left, right) + return left >= right + end + + M['RegexpMatches'] = function(left, right) + return not not vim.regex(right):match_str(left) + end + + M['RegexpMatchesIns'] = function(left, right) + return not not vim.regex('\\c' .. right):match_str(left) + end + + M['NotRegexpMatches'] = function(left, right) + return not M['RegexpMatches'](left, right) + end + + M['Modulo'] = function(left, right) + return left % right + end + + M['Minus'] = function(left, right) + -- TODO: This is not right :) + return left - right + end + + return M +end)() +vim9['prefix'] = (function() + local lib = vim9 + + local M = {} + + M['Minus'] = function(right) + return -right + end + + M['Bang'] = function(right) + return not lib.bool(right) + end + + return M +end)() + +return vim9 diff --git a/runtime/lua/editorconfig.lua b/runtime/lua/editorconfig.lua new file mode 100644 index 0000000000..2079006234 --- /dev/null +++ b/runtime/lua/editorconfig.lua @@ -0,0 +1,246 @@ +local M = {} + +M.properties = {} + +--- Modified version of the builtin assert that does not include error position information +--- +---@param v any Condition +---@param message string Error message to display if condition is false or nil +---@return any v if not false or nil, otherwise an error is displayed +--- +---@private +local function assert(v, message) + return v or error(message, 0) +end + +--- Show a warning message +--- +---@param msg string Message to show +--- +---@private +local function warn(msg, ...) + vim.notify(string.format(msg, ...), vim.log.levels.WARN, { + title = 'editorconfig', + }) +end + +function M.properties.charset(bufnr, val) + assert( + vim.tbl_contains({ 'utf-8', 'utf-8-bom', 'latin1', 'utf-16be', 'utf-16le' }, val), + 'charset must be one of "utf-8", "utf-8-bom", "latin1", "utf-16be", or "utf-16le"' + ) + if val == 'utf-8' or val == 'utf-8-bom' then + vim.bo[bufnr].fileencoding = 'utf-8' + vim.bo[bufnr].bomb = val == 'utf-8-bom' + elseif val == 'utf-16be' then + vim.bo[bufnr].fileencoding = 'utf-16' + else + vim.bo[bufnr].fileencoding = val + end +end + +function M.properties.end_of_line(bufnr, val) + vim.bo[bufnr].fileformat = assert( + ({ lf = 'unix', crlf = 'dos', cr = 'mac' })[val], + 'end_of_line must be one of "lf", "crlf", or "cr"' + ) +end + +function M.properties.indent_style(bufnr, val, opts) + assert(val == 'tab' or val == 'space', 'indent_style must be either "tab" or "space"') + vim.bo[bufnr].expandtab = val == 'space' + if val == 'tab' and not opts.indent_size then + vim.bo[bufnr].shiftwidth = 0 + vim.bo[bufnr].softtabstop = 0 + end +end + +function M.properties.indent_size(bufnr, val, opts) + if val == 'tab' then + vim.bo[bufnr].shiftwidth = 0 + vim.bo[bufnr].softtabstop = 0 + else + local n = assert(tonumber(val), 'indent_size must be a number') + vim.bo[bufnr].shiftwidth = n + vim.bo[bufnr].softtabstop = -1 + if not opts.tab_width then + vim.bo[bufnr].tabstop = n + end + end +end + +function M.properties.tab_width(bufnr, val) + vim.bo[bufnr].tabstop = assert(tonumber(val), 'tab_width must be a number') +end + +function M.properties.max_line_length(bufnr, val) + local n = tonumber(val) + if n then + vim.bo[bufnr].textwidth = n + else + assert(val == 'off', 'max_line_length must be a number or "off"') + vim.bo[bufnr].textwidth = 0 + end +end + +function M.properties.trim_trailing_whitespace(bufnr, val) + assert( + val == 'true' or val == 'false', + 'trim_trailing_whitespace must be either "true" or "false"' + ) + if val == 'true' then + vim.api.nvim_create_autocmd('BufWritePre', { + group = 'editorconfig', + buffer = bufnr, + callback = function() + local view = vim.fn.winsaveview() + vim.api.nvim_command('silent! undojoin') + vim.api.nvim_command('silent keepjumps keeppatterns %s/\\s\\+$//e') + vim.fn.winrestview(view) + end, + }) + else + vim.api.nvim_clear_autocmds({ + event = 'BufWritePre', + group = 'editorconfig', + buffer = bufnr, + }) + end +end + +function M.properties.insert_final_newline(bufnr, val) + assert(val == 'true' or val == 'false', 'insert_final_newline must be either "true" or "false"') + vim.bo[bufnr].fixendofline = val == 'true' + vim.bo[bufnr].endofline = val == 'true' +end + +--- Modified version of |glob2regpat()| that does not match path separators on *. +--- +--- This function replaces single instances of * with the regex pattern [^/]*. However, the star in +--- the replacement pattern also gets interpreted by glob2regpat, so we insert a placeholder, pass +--- it through glob2regpat, then replace the placeholder with the actual regex pattern. +--- +---@param glob string Glob to convert into a regular expression +---@return string Regular expression +--- +---@private +local function glob2regpat(glob) + local placeholder = '@@PLACEHOLDER@@' + return ( + string.gsub( + vim.fn.glob2regpat( + vim.fn.substitute( + string.gsub(glob, '{(%d+)%.%.(%d+)}', '[%1-%2]'), + '\\*\\@<!\\*\\*\\@!', + placeholder, + 'g' + ) + ), + placeholder, + '[^/]*' + ) + ) +end + +--- Parse a single line in an EditorConfig file +--- +---@param line string Line +---@return string|nil If the line contains a pattern, the glob pattern +---@return string|nil If the line contains a key-value pair, the key +---@return string|nil If the line contains a key-value pair, the value +--- +---@private +local function parse_line(line) + if line:find('^%s*[^ #;]') then + local glob = (line:match('%b[]') or ''):match('^%s*%[(.*)%]%s*$') + if glob then + return glob, nil, nil + end + + local key, val = line:match('^%s*([^:= ][^:=]-)%s*[:=]%s*(.-)%s*$') + if key ~= nil and val ~= nil then + return nil, key:lower(), val:lower() + end + end +end + +--- Parse options from an .editorconfig file +--- +---@param filepath string File path of the file to apply EditorConfig settings to +---@param dir string Current directory +---@return table Table of options to apply to the given file +--- +---@private +local function parse(filepath, dir) + local pat = nil + local opts = {} + local f = io.open(dir .. '/.editorconfig') + if f then + for line in f:lines() do + local glob, key, val = parse_line(line) + if glob then + glob = glob:find('/') and (dir .. '/' .. glob:gsub('^/', '')) or ('**/' .. glob) + local ok, regpat = pcall(glob2regpat, glob) + if ok then + pat = vim.regex(regpat) + else + pat = nil + warn('editorconfig: Error occurred while parsing glob pattern "%s": %s', glob, regpat) + end + elseif key ~= nil and val ~= nil then + if key == 'root' then + opts.root = val == 'true' + elseif pat and pat:match_str(filepath) then + opts[key] = val + end + end + end + f:close() + end + return opts +end + +--- Configure the given buffer with options from an .editorconfig file +--- +---@param bufnr number Buffer number to configure +--- +---@private +function M.config(bufnr) + bufnr = bufnr or vim.api.nvim_get_current_buf() + local path = vim.fs.normalize(vim.api.nvim_buf_get_name(bufnr)) + if vim.bo[bufnr].buftype ~= '' or not vim.bo[bufnr].modifiable or path == '' then + return + end + + local opts = {} + for parent in vim.fs.parents(path) do + for k, v in pairs(parse(path, parent)) do + if opts[k] == nil then + opts[k] = v + end + end + + if opts.root then + break + end + end + + local applied = {} + for opt, val in pairs(opts) do + if val ~= 'unset' then + local func = M.properties[opt] + if func then + local ok, err = pcall(func, bufnr, val, opts) + if ok then + applied[opt] = val + else + warn('editorconfig: invalid value for option %s: %s. %s', opt, val, err) + end + end + end + end + + vim.b[bufnr].editorconfig = applied +end + +return M diff --git a/runtime/lua/man.lua b/runtime/lua/man.lua index 5da3d2a92f..732a4ab92e 100644 --- a/runtime/lua/man.lua +++ b/runtime/lua/man.lua @@ -1,7 +1,89 @@ -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 + + -- We use the `env` command here rather than the env option to vim.loop.spawn since spawn will + -- completely overwrite the environment when we just want to modify the existing one. + -- + -- Overwriting mainly causes problems NixOS which relies heavily on a non-standard environment. + local cmd + if env then + cmd = { 'env' } + vim.list_extend(cmd, env) + vim.list_extend(cmd, cmd_) + else + cmd = cmd_ + end + + local handle + handle = vim.loop.spawn(cmd[1], { + args = vim.list_slice(cmd, 2), + stdio = { nil, stdout, stderr }, + }, 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 +234,549 @@ 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 -return { highlight_man_page = highlight_man_page } +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 + + -- `man -w /some/path` will return `/some/path` for any existent file, which + -- stops us from actually determining if a path has a corresponding man file. + -- Since `:Man /some/path/to/man/file` isn't supported anyway, we should just + -- error out here if we detect this is the case. + if sect == '' and #results == 1 and results[1] == name 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() + if vim.bo.filetype == 'man' then + return true + end + + 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.modifiable = 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 + +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 + + 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/nvim/health.lua b/runtime/lua/nvim/health.lua new file mode 100644 index 0000000000..b76106f241 --- /dev/null +++ b/runtime/lua/nvim/health.lua @@ -0,0 +1,406 @@ +local M = {} +local health = require('vim.health') + +local fn_bool = function(key) + return function(...) + return vim.fn[key](...) == 1 + end +end + +local has = fn_bool('has') +local executable = fn_bool('executable') +local empty = fn_bool('empty') +local filereadable = fn_bool('filereadable') +local filewritable = fn_bool('filewritable') + +local shell_error = function() + return vim.v.shell_error ~= 0 +end + +local suggest_faq = 'https://github.com/neovim/neovim/wiki/Building-Neovim#optimized-builds' + +local function check_runtime() + health.report_start('Runtime') + -- Files from an old installation. + local bad_files = { + ['plugin/man.vim'] = false, + ['scripts.vim'] = false, + ['autoload/man.vim'] = false, + } + local bad_files_msg = '' + for k, _ in pairs(bad_files) do + local path = ('%s/%s'):format(vim.env.VIMRUNTIME, k) + if vim.loop.fs_stat(path) then + bad_files[k] = true + bad_files_msg = ('%s%s\n'):format(bad_files_msg, path) + end + end + + local ok = (bad_files_msg == '') + local info = ok and health.report_ok or health.report_info + info(string.format('$VIMRUNTIME: %s', vim.env.VIMRUNTIME)) + if not ok then + health.report_error( + string.format( + '$VIMRUNTIME has files from an old installation (this can cause weird behavior):\n%s', + bad_files_msg + ), + { 'Delete $VIMRUNTIME (or uninstall Nvim), then reinstall Nvim.' } + ) + end +end + +local function check_config() + health.report_start('Configuration') + local ok = true + + local vimrc = ( + empty(vim.env.MYVIMRC) and vim.fn.stdpath('config') .. '/init.vim' or vim.env.MYVIMRC + ) + if not filereadable(vimrc) then + ok = false + local has_vim = filereadable(vim.fn.expand('~/.vimrc')) + health.report_warn( + (-1 == vim.fn.getfsize(vimrc) and 'Missing' or 'Unreadable') .. ' user config file: ' .. vimrc, + { has_vim and ':help nvim-from-vim' or ':help init.vim' } + ) + end + + -- If $VIM is empty we don't care. Else make sure it is valid. + if not empty(vim.env.VIM) and not filereadable(vim.env.VIM .. '/runtime/doc/nvim.txt') then + ok = false + health.report_error('$VIM is invalid: ' .. vim.env.VIM) + end + + if vim.env.NVIM_TUI_ENABLE_CURSOR_SHAPE then + ok = false + health.report_warn('$NVIM_TUI_ENABLE_CURSOR_SHAPE is ignored in Nvim 0.2+', { + "Use the 'guicursor' option to configure cursor shape. :help 'guicursor'", + 'https://github.com/neovim/neovim/wiki/Following-HEAD#20170402', + }) + end + + if vim.v.ctype == 'C' then + ok = false + health.report_error( + 'Locale does not support UTF-8. Unicode characters may not display correctly.' + .. ('\n$LANG=%s $LC_ALL=%s $LC_CTYPE=%s'):format( + vim.env.LANG, + vim.env.LC_ALL, + vim.env.LC_CTYPE + ), + { + 'If using tmux, try the -u option.', + 'Ensure that your terminal/shell/tmux/etc inherits the environment, or set $LANG explicitly.', + 'Configure your system locale.', + } + ) + end + + if vim.o.paste == 1 then + ok = false + health.report_error( + "'paste' is enabled. This option is only for pasting text.\nIt should not be set in your config.", + { + 'Remove `set paste` from your init.vim, if applicable.', + 'Check `:verbose set paste?` to see if a plugin or script set the option.', + } + ) + end + + local writeable = true + local shadaopt = vim.fn.split(vim.o.shada, ',') + local shadafile = ( + empty(vim.o.shada) and vim.o.shada + or vim.fn.substitute(vim.fn.matchstr(shadaopt[#shadaopt], '^n.\\+'), '^n', '', '') + ) + shadafile = ( + empty(vim.o.shadafile) + and (empty(shadafile) and vim.fn.stdpath('state') .. '/shada/main.shada' or vim.fn.expand( + shadafile + )) + or (vim.o.shadafile == 'NONE' and '' or vim.o.shadafile) + ) + if not empty(shadafile) and empty(vim.fn.glob(shadafile)) then + -- Since this may be the first time Nvim has been run, try to create a shada file. + if not pcall(vim.cmd.wshada) then + writeable = false + end + end + if + not writeable + or (not empty(shadafile) and (not filereadable(shadafile) or not filewritable(shadafile))) + then + ok = false + health.report_error( + 'shada file is not ' + .. ((not writeable or filereadable(shadafile)) and 'writeable' or 'readable') + .. ':\n' + .. shadafile + ) + end + + if ok then + health.report_ok('no issues found') + end +end + +local function check_performance() + health.report_start('Performance') + + -- Check buildtype + local buildtype = vim.fn.matchstr(vim.fn.execute('version'), [[\v\cbuild type:?\s*[^\n\r\t ]+]]) + if empty(buildtype) then + health.report_error('failed to get build type from :version') + elseif vim.regex([[\v(MinSizeRel|Release|RelWithDebInfo)]]):match_str(buildtype) then + health.report_ok(buildtype) + else + health.report_info(buildtype) + health.report_warn( + 'Non-optimized ' .. (has('debug') and '(DEBUG) ' or '') .. 'build. Nvim will be slower.', + { + 'Install a different Nvim package, or rebuild with `CMAKE_BUILD_TYPE=RelWithDebInfo`.', + suggest_faq, + } + ) + end + + -- check for slow shell invocation + local slow_cmd_time = 1.5 + local start_time = vim.fn.reltime() + vim.fn.system('echo') + local elapsed_time = vim.fn.reltimefloat(vim.fn.reltime(start_time)) + if elapsed_time > slow_cmd_time then + health.report_warn( + 'Slow shell invocation (took ' .. vim.fn.printf('%.2f', elapsed_time) .. ' seconds).' + ) + end +end + +-- Load the remote plugin manifest file and check for unregistered plugins +local function check_rplugin_manifest() + health.report_start('Remote Plugins') + + local existing_rplugins = {} + for _, item in ipairs(vim.fn['remote#host#PluginsForHost']('python')) do + existing_rplugins[item.path] = 'python' + end + + for item in ipairs(vim.fn['remote#host#PluginsForHost']('python3')) do + existing_rplugins[item.path] = 'python3' + end + + local require_update = false + local handle_path = function(path) + local python_glob = vim.fn.glob(path .. '/rplugin/python*', true, true) + if empty(python_glob) then + return + end + + local python_dir = python_glob[1] + local python_version = vim.fn.fnamemodify(python_dir, ':t') + + local scripts = vim.fn.glob(python_dir .. '/*.py', true, true) + vim.list_extend(scripts, vim.fn.glob(python_dir .. '/*/__init__.py', true, true)) + + for script in ipairs(scripts) do + local contents = vim.fn.join(vim.fn.readfile(script)) + if vim.regex([[\<\%(from\|import\)\s\+neovim\>]]):match_str(contents) then + if vim.regex([[[\/]__init__\.py$]]):match_str(script) then + script = vim.fn.tr(vim.fn.fnamemodify(script, ':h'), '\\', '/') + end + if not existing_rplugins[script] then + local msg = vim.fn.printf('"%s" is not registered.', vim.fn.fnamemodify(path, ':t')) + if python_version == 'pythonx' then + if not has('python3') then + msg = msg .. ' (python3 not available)' + end + elseif not has(python_version) then + msg = msg .. vim.fn.printf(' (%s not available)', python_version) + else + require_update = true + end + + health.report_warn(msg) + end + + break + end + end + end + + for _, path in ipairs(vim.fn.map(vim.fn.split(vim.o.runtimepath, ','), 'resolve(v:val)')) do + handle_path(path) + end + + if require_update then + health.report_warn('Out of date', { 'Run `:UpdateRemotePlugins`' }) + else + health.report_ok('Up to date') + end +end + +local function check_tmux() + if empty(vim.env.TMUX) or not executable('tmux') then + return + end + + local get_tmux_option = function(option) + local cmd = 'tmux show-option -qvg ' .. option -- try global scope + local out = vim.fn.system(vim.fn.split(cmd)) + local val = vim.fn.substitute(out, [[\v(\s|\r|\n)]], '', 'g') + if shell_error() then + health.report_error('command failed: ' .. cmd .. '\n' .. out) + return 'error' + elseif empty(val) then + cmd = 'tmux show-option -qvgs ' .. option -- try session scope + out = vim.fn.system(vim.fn.split(cmd)) + val = vim.fn.substitute(out, [[\v(\s|\r|\n)]], '', 'g') + if shell_error() then + health.report_error('command failed: ' .. cmd .. '\n' .. out) + return 'error' + end + end + return val + end + + health.report_start('tmux') + + -- check escape-time + local suggestions = + { 'set escape-time in ~/.tmux.conf:\nset-option -sg escape-time 10', suggest_faq } + local tmux_esc_time = get_tmux_option('escape-time') + if tmux_esc_time ~= 'error' then + if empty(tmux_esc_time) then + health.report_error('`escape-time` is not set', suggestions) + elseif tonumber(tmux_esc_time) > 300 then + health.report_error( + '`escape-time` (' .. tmux_esc_time .. ') is higher than 300ms', + suggestions + ) + else + health.report_ok('escape-time: ' .. tmux_esc_time) + end + end + + -- check focus-events + local tmux_focus_events = get_tmux_option('focus-events') + if tmux_focus_events ~= 'error' then + if empty(tmux_focus_events) or tmux_focus_events ~= 'on' then + health.report_warn( + "`focus-events` is not enabled. |'autoread'| may not work.", + { '(tmux 1.9+ only) Set `focus-events` in ~/.tmux.conf:\nset-option -g focus-events on' } + ) + else + health.report_ok('focus-events: ' .. tmux_focus_events) + end + end + + -- check default-terminal and $TERM + health.report_info('$TERM: ' .. vim.env.TERM) + local cmd = 'tmux show-option -qvg default-terminal' + local out = vim.fn.system(vim.fn.split(cmd)) + local tmux_default_term = vim.fn.substitute(out, [[\v(\s|\r|\n)]], '', 'g') + if empty(tmux_default_term) then + cmd = 'tmux show-option -qvgs default-terminal' + out = vim.fn.system(vim.fn.split(cmd)) + tmux_default_term = vim.fn.substitute(out, [[\v(\s|\r|\n)]], '', 'g') + end + + if shell_error() then + health.report_error('command failed: ' .. cmd .. '\n' .. out) + elseif tmux_default_term ~= vim.env.TERM then + health.report_info('default-terminal: ' .. tmux_default_term) + health.report_error( + '$TERM differs from the tmux `default-terminal` setting. Colors might look wrong.', + { '$TERM may have been set by some rc (.bashrc, .zshrc, ...).' } + ) + elseif not vim.regex([[\v(tmux-256color|screen-256color)]]):match_str(vim.env.TERM) then + health.report_error( + '$TERM should be "screen-256color" or "tmux-256color" in tmux. Colors might look wrong.', + { + 'Set default-terminal in ~/.tmux.conf:\nset-option -g default-terminal "screen-256color"', + suggest_faq, + } + ) + end + + -- check for RGB capabilities + local info = vim.fn.system({ 'tmux', 'display-message', '-p', '#{client_termfeatures}' }) + info = vim.split(vim.trim(info), ',', { trimempty = true }) + if not vim.tbl_contains(info, 'RGB') then + local has_rgb = false + if #info == 0 then + -- client_termfeatures may not be supported; fallback to checking show-messages + info = vim.fn.system({ 'tmux', 'show-messages', '-JT' }) + has_rgb = info:find(' Tc: (flag) true', 1, true) or info:find(' RGB: (flag) true', 1, true) + end + if not has_rgb then + health.report_warn( + "Neither Tc nor RGB capability set. True colors are disabled. |'termguicolors'| won't work properly.", + { + "Put this in your ~/.tmux.conf and replace XXX by your $TERM outside of tmux:\nset-option -sa terminal-features ',XXX:RGB'", + "For older tmux versions use this instead:\nset-option -ga terminal-overrides ',XXX:Tc'", + } + ) + end + end +end + +local function check_terminal() + if not executable('infocmp') then + return + end + + health.report_start('terminal') + local cmd = 'infocmp -L' + local out = vim.fn.system(vim.fn.split(cmd)) + local kbs_entry = vim.fn.matchstr(out, 'key_backspace=[^,[:space:]]*') + local kdch1_entry = vim.fn.matchstr(out, 'key_dc=[^,[:space:]]*') + + if + shell_error() + and ( + not has('win32') + or empty( + vim.fn.matchstr( + out, + [[infocmp: couldn't open terminfo file .\+\%(conemu\|vtpcon\|win32con\)]] + ) + ) + ) + then + health.report_error('command failed: ' .. cmd .. '\n' .. out) + else + health.report_info( + vim.fn.printf( + 'key_backspace (kbs) terminfo entry: `%s`', + (empty(kbs_entry) and '? (not found)' or kbs_entry) + ) + ) + + health.report_info( + vim.fn.printf( + 'key_dc (kdch1) terminfo entry: `%s`', + (empty(kbs_entry) and '? (not found)' or kdch1_entry) + ) + ) + end + + for env_var in ipairs({ 'XTERM_VERSION', 'VTE_VERSION', 'TERM_PROGRAM', 'COLORTERM', 'SSH_TTY' }) do + if vim.env[env_var] then + health.report_info(vim.fn.printf('$%s="%s"', env_var, vim.env[env_var])) + end + end +end + +function M.check() + check_config() + check_runtime() + check_performance() + check_rplugin_manifest() + check_terminal() + check_tmux() +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..da8764fbd4 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({ @@ -51,6 +36,7 @@ for k, v in pairs({ ui = true, health = true, fs = true, + secure = true, }) do vim._submodules[k] = v end @@ -122,9 +108,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 @@ -139,7 +123,7 @@ do --- (such as the |TUI|) pastes text into the editor. --- --- Example: To remove ANSI color codes when pasting: - --- <pre> + --- <pre>lua --- vim.paste = (function(overridden) --- return function(lines, phase) --- for i,line in ipairs(lines) do @@ -152,14 +136,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 @@ -183,7 +168,8 @@ do local line1 = lines[1]:gsub('(%c)', '\022%1') -- nvim_input() is affected by mappings, -- so use nvim_feedkeys() with "n" flag to ignore mappings. - vim.api.nvim_feedkeys(line1, 'n', true) + -- "t" flag is also needed so the pasted text is saved in cmdline history. + vim.api.nvim_feedkeys(line1, 'nt', true) end return true end @@ -255,6 +241,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(...) @@ -292,7 +280,7 @@ end --- command. --- --- Example: ---- <pre> +--- <pre>lua --- vim.cmd('echo 42') --- vim.cmd([[ --- augroup My_group @@ -399,11 +387,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 region 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) @@ -430,11 +418,16 @@ function vim.region(bufnr, pos1, pos2, regtype, inclusive) c2 = c1 + regtype:sub(2) -- and adjust for non-ASCII characters bufline = vim.api.nvim_buf_get_lines(bufnr, l, l + 1, true)[1] - if c1 < #bufline then + local utflen = vim.str_utfindex(bufline, #bufline) + if c1 <= utflen then c1 = vim.str_byteindex(bufline, c1) + else + c1 = #bufline + 1 end - if c2 < #bufline then + if c2 <= utflen then c2 = vim.str_byteindex(bufline, c2) + else + c2 = #bufline + 1 end else c1 = (l == pos1[1]) and pos1[2] or 0 @@ -448,11 +441,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() @@ -753,12 +746,12 @@ end ---Prints given arguments in human-readable format. ---Example: ----<pre> +---<pre>lua --- -- Print highlight group Normal and store it's contents in a variable. --- 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..0c4ee8636d 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 @@ -59,6 +56,9 @@ setmetatable(vim, { if vim._submodules[key] then t[key] = require('vim.' .. key) return t[key] + elseif key == 'inspect_pos' or key == 'show_pos' then + require('vim._inspector') + return t[key] elseif vim.startswith(key, 'uri_') then local val = require('vim.uri')[key] if val ~= nil then diff --git a/runtime/lua/vim/_inspector.lua b/runtime/lua/vim/_inspector.lua new file mode 100644 index 0000000000..f46a525910 --- /dev/null +++ b/runtime/lua/vim/_inspector.lua @@ -0,0 +1,238 @@ +---@class InspectorFilter +---@field syntax boolean include syntax based highlight groups (defaults to true) +---@field treesitter boolean include treesitter based highlight groups (defaults to true) +---@field extmarks boolean|"all" include extmarks. When `all`, then extmarks without a `hl_group` will also be included (defaults to true) +---@field semantic_tokens boolean include semantic tokens (defaults to true) +local defaults = { + syntax = true, + treesitter = true, + extmarks = true, + semantic_tokens = true, +} + +---Get all the items at a given buffer position. +--- +---Can also be pretty-printed with `:Inspect!`. *:Inspect!* +--- +---@param bufnr? number defaults to the current buffer +---@param row? number row to inspect, 0-based. Defaults to the row of the current cursor +---@param col? number col to inspect, 0-based. Defaults to the col of the current cursor +---@param filter? InspectorFilter (table|nil) a table with key-value pairs to filter the items +--- - syntax (boolean): include syntax based highlight groups (defaults to true) +--- - treesitter (boolean): include treesitter based highlight groups (defaults to true) +--- - extmarks (boolean|"all"): include extmarks. When `all`, then extmarks without a `hl_group` will also be included (defaults to true) +--- - semantic_tokens (boolean): include semantic tokens (defaults to true) +---@return {treesitter:table,syntax:table,extmarks:table,semantic_tokens:table,buffer:number,col:number,row:number} (table) a table with the following key-value pairs. Items are in "traversal order": +--- - treesitter: a list of treesitter captures +--- - syntax: a list of syntax groups +--- - semantic_tokens: a list of semantic tokens +--- - extmarks: a list of extmarks +--- - buffer: the buffer used to get the items +--- - row: the row used to get the items +--- - col: the col used to get the items +function vim.inspect_pos(bufnr, row, col, filter) + filter = vim.tbl_deep_extend('force', defaults, filter or {}) + + bufnr = bufnr or 0 + if row == nil or col == nil then + -- get the row/col from the first window displaying the buffer + local win = bufnr == 0 and vim.api.nvim_get_current_win() or vim.fn.bufwinid(bufnr) + if win == -1 then + error('row/col is required for buffers not visible in a window') + end + local cursor = vim.api.nvim_win_get_cursor(win) + row, col = cursor[1] - 1, cursor[2] + end + bufnr = bufnr == 0 and vim.api.nvim_get_current_buf() or bufnr + + local results = { + treesitter = {}, + syntax = {}, + extmarks = {}, + semantic_tokens = {}, + buffer = bufnr, + row = row, + col = col, + } + + -- resolve hl links + ---@private + local function resolve_hl(data) + if data.hl_group then + local hlid = vim.api.nvim_get_hl_id_by_name(data.hl_group) + local name = vim.fn.synIDattr(vim.fn.synIDtrans(hlid), 'name') + data.hl_group_link = name + end + return data + end + + -- treesitter + if filter.treesitter then + for _, capture in pairs(vim.treesitter.get_captures_at_pos(bufnr, row, col)) do + capture.hl_group = '@' .. capture.capture + table.insert(results.treesitter, resolve_hl(capture)) + end + end + + -- syntax + if filter.syntax then + for _, i1 in ipairs(vim.fn.synstack(row + 1, col + 1)) do + table.insert(results.syntax, resolve_hl({ hl_group = vim.fn.synIDattr(i1, 'name') })) + end + end + + -- semantic tokens + if filter.semantic_tokens then + for _, token in ipairs(vim.lsp.semantic_tokens.get_at_pos(bufnr, row, col) or {}) do + token.hl_groups = { + type = resolve_hl({ hl_group = '@' .. token.type }), + modifiers = vim.tbl_map(function(modifier) + return resolve_hl({ hl_group = '@' .. modifier }) + end, token.modifiers or {}), + } + table.insert(results.semantic_tokens, token) + end + end + + -- extmarks + if filter.extmarks then + for ns, nsid in pairs(vim.api.nvim_get_namespaces()) do + if ns:find('vim_lsp_semantic_tokens') ~= 1 then + local extmarks = vim.api.nvim_buf_get_extmarks(bufnr, nsid, 0, -1, { details = true }) + for _, extmark in ipairs(extmarks) do + extmark = { + ns_id = nsid, + ns = ns, + id = extmark[1], + row = extmark[2], + col = extmark[3], + opts = resolve_hl(extmark[4]), + } + local end_row = extmark.opts.end_row or extmark.row -- inclusive + local end_col = extmark.opts.end_col or (extmark.col + 1) -- exclusive + if + (filter.extmarks == 'all' or extmark.opts.hl_group) -- filter hl_group + and (row >= extmark.row and row <= end_row) -- within the rows of the extmark + and (row > extmark.row or col >= extmark.col) -- either not the first row, or in range of the col + and (row < end_row or col < end_col) -- either not in the last row or in range of the col + then + table.insert(results.extmarks, extmark) + end + end + end + end + end + return results +end + +---Show all the items at a given buffer position. +--- +---Can also be shown with `:Inspect`. *:Inspect* +--- +---@param bufnr? number defaults to the current buffer +---@param row? number row to inspect, 0-based. Defaults to the row of the current cursor +---@param col? number col to inspect, 0-based. Defaults to the col of the current cursor +---@param filter? InspectorFilter (table|nil) see |vim.inspect_pos()| +function vim.show_pos(bufnr, row, col, filter) + local items = vim.inspect_pos(bufnr, row, col, filter) + + local lines = { {} } + + ---@private + local function append(str, hl) + table.insert(lines[#lines], { str, hl }) + end + + ---@private + local function nl() + table.insert(lines, {}) + end + + ---@private + local function item(data, comment) + append(' - ') + append(data.hl_group, data.hl_group) + append(' ') + if data.hl_group ~= data.hl_group_link then + append('links to ', 'MoreMsg') + append(data.hl_group_link, data.hl_group_link) + append(' ') + end + if comment then + append(comment, 'Comment') + end + nl() + end + + -- treesitter + if #items.treesitter > 0 then + append('Treesitter', 'Title') + nl() + for _, capture in ipairs(items.treesitter) do + item(capture, capture.lang) + end + nl() + end + + if #items.semantic_tokens > 0 then + append('Semantic Tokens', 'Title') + nl() + for _, token in ipairs(items.semantic_tokens) do + local client = vim.lsp.get_client_by_id(token.client_id) + client = client and (' (' .. client.name .. ')') or '' + item(token.hl_groups.type, 'type' .. client) + for _, modifier in ipairs(token.hl_groups.modifiers) do + item(modifier, 'modifier' .. client) + end + end + nl() + end + + -- syntax + if #items.syntax > 0 then + append('Syntax', 'Title') + nl() + for _, syn in ipairs(items.syntax) do + item(syn) + end + nl() + end + -- extmarks + if #items.extmarks > 0 then + append('Extmarks', 'Title') + nl() + for _, extmark in ipairs(items.extmarks) do + if extmark.opts.hl_group then + item(extmark.opts, extmark.ns) + else + append(' - ') + append(extmark.ns, 'Comment') + nl() + end + end + nl() + end + + if #lines[#lines] == 0 then + table.remove(lines) + end + + local chunks = {} + for _, line in ipairs(lines) do + vim.list_extend(chunks, line) + table.insert(chunks, { '\n' }) + end + if #chunks == 0 then + chunks = { + { + 'No items found at position ' + .. items.row + .. ',' + .. items.col + .. ' in buffer ' + .. items.buffer, + }, + } + end + vim.api.nvim_echo(chunks, false, {}) +end diff --git a/runtime/lua/vim/_meta.lua b/runtime/lua/vim/_meta.lua index f1652718ee..104f29c4c0 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 })) + return make_option(k, a.nvim_get_option_value(k, {})) 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..6fd000a029 100644 --- a/runtime/lua/vim/diagnostic.lua +++ b/runtime/lua/vim/diagnostic.lua @@ -1,7 +1,8 @@ -local if_nil = vim.F.if_nil +local api, if_nil = vim.api, vim.F.if_nil local M = {} +---@enum DiagnosticSeverity M.severity = { ERROR = 1, WARN = 2, @@ -45,18 +46,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 = api.nvim_create_augroup('DiagnosticBufWipeout', {}) + diagnostic_cache = setmetatable({}, { + __index = function(t, bufnr) + assert(bufnr > 0, 'Invalid buffer number') + 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 = {} @@ -239,25 +246,12 @@ end)() ---@private local function get_bufnr(bufnr) if not bufnr or bufnr == 0 then - return vim.api.nvim_get_current_buf() + return api.nvim_get_current_buf() end return bufnr end ---@private -local function is_disabled(namespace, bufnr) - local ns = M.get_namespace(namespace) - if ns.disabled then - return true - end - - if type(diagnostic_disabled[bufnr]) == 'table' then - return diagnostic_disabled[bufnr][namespace] - end - return diagnostic_disabled[bufnr] -end - ----@private local function diagnostic_lines(diagnostics) if not diagnostics then return {} @@ -293,7 +287,7 @@ end ---@private local function restore_extmarks(bufnr, last) for ns, extmarks in pairs(diagnostic_cache_extmarks[bufnr]) do - local extmarks_current = vim.api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, { details = true }) + local extmarks_current = api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, { details = true }) local found = {} for _, extmark in ipairs(extmarks_current) do -- nvim_buf_set_lines will move any extmark to the line after the last @@ -306,7 +300,7 @@ local function restore_extmarks(bufnr, last) if not found[extmark[1]] then local opts = extmark[4] opts.id = extmark[1] - pcall(vim.api.nvim_buf_set_extmark, bufnr, ns, extmark[2], extmark[3], opts) + pcall(api.nvim_buf_set_extmark, bufnr, ns, extmark[2], extmark[3], opts) end end end @@ -316,7 +310,7 @@ end local function save_extmarks(namespace, bufnr) bufnr = get_bufnr(bufnr) if not diagnostic_attached_buffers[bufnr] then - vim.api.nvim_buf_attach(bufnr, false, { + api.nvim_buf_attach(bufnr, false, { on_lines = function(_, _, _, _, _, last) restore_extmarks(bufnr, last - 1) end, @@ -327,7 +321,7 @@ local function save_extmarks(namespace, bufnr) diagnostic_attached_buffers[bufnr] = true end diagnostic_cache_extmarks[bufnr][namespace] = - vim.api.nvim_buf_get_extmarks(bufnr, namespace, 0, -1, { details = true }) + api.nvim_buf_get_extmarks(bufnr, namespace, 0, -1, { details = true }) end local registered_autocmds = {} @@ -351,19 +345,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' } @@ -373,8 +354,8 @@ local function schedule_display(namespace, bufnr, args) local key = make_augroup_key(namespace, bufnr) if not registered_autocmds[key] then - local group = vim.api.nvim_create_augroup(key, { clear = true }) - vim.api.nvim_create_autocmd(insert_leave_auto_cmds, { + local group = api.nvim_create_augroup(key, { clear = true }) + api.nvim_create_autocmd(insert_leave_auto_cmds, { group = group, buffer = bufnr, callback = function() @@ -391,7 +372,7 @@ local function clear_scheduled_display(namespace, bufnr) local key = make_augroup_key(namespace, bufnr) if registered_autocmds[key] then - vim.api.nvim_del_augroup_by_name(key) + api.nvim_del_augroup_by_name(key) registered_autocmds[key] = nil end end @@ -406,7 +387,7 @@ local function get_diagnostics(bufnr, opts, clamp) -- Memoized results of buf_line_count per bufnr local buf_line_count = setmetatable({}, { __index = function(t, k) - t[k] = vim.api.nvim_buf_line_count(k) + t[k] = api.nvim_buf_line_count(k) return rawget(t, k) end, }) @@ -414,7 +395,7 @@ local function get_diagnostics(bufnr, opts, clamp) ---@private local function add(b, d) if not opts.lnum or d.lnum == opts.lnum then - if clamp and vim.api.nvim_buf_is_loaded(b) then + if clamp and api.nvim_buf_is_loaded(b) then local line_count = buf_line_count[b] - 1 if d.lnum > line_count @@ -435,32 +416,31 @@ local function get_diagnostics(bufnr, opts, clamp) end end + ---@private + local function add_all_diags(buf, diags) + for _, diagnostic in pairs(diags) do + add(buf, diagnostic) + end + end + if namespace == nil and bufnr == nil then for b, t in pairs(diagnostic_cache) do for _, v in pairs(t) do - for _, diagnostic in pairs(v) do - add(b, diagnostic) - end + add_all_diags(b, v) end end elseif namespace == nil then bufnr = get_bufnr(bufnr) for iter_namespace in pairs(diagnostic_cache[bufnr]) do - for _, diagnostic in pairs(diagnostic_cache[bufnr][iter_namespace]) do - add(bufnr, diagnostic) - end + add_all_diags(bufnr, diagnostic_cache[bufnr][iter_namespace]) end elseif bufnr == nil then for b, t in pairs(diagnostic_cache) do - for _, diagnostic in pairs(t[namespace] or {}) do - add(b, diagnostic) - end + add_all_diags(b, t[namespace] or {}) end else bufnr = get_bufnr(bufnr) - for _, diagnostic in pairs(diagnostic_cache[bufnr][namespace] or {}) do - add(bufnr, diagnostic) - end + add_all_diags(bufnr, diagnostic_cache[bufnr][namespace] or {}) end if opts.severity then @@ -478,7 +458,7 @@ local function set_list(loclist, opts) local winnr = opts.winnr or 0 local bufnr if loclist then - bufnr = vim.api.nvim_win_get_buf(winnr) + bufnr = api.nvim_win_get_buf(winnr) end -- Don't clamp line numbers since the quickfix list can already handle line -- numbers beyond the end of the buffer @@ -490,7 +470,7 @@ local function set_list(loclist, opts) vim.fn.setqflist({}, ' ', { title = title, items = items }) end if open then - vim.api.nvim_command(loclist and 'lopen' or 'botright copen') + api.nvim_command(loclist and 'lwindow' or 'botright cwindow') end end @@ -499,7 +479,7 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace) position[1] = position[1] - 1 bufnr = get_bufnr(bufnr) local wrap = vim.F.if_nil(opts.wrap, true) - local line_count = vim.api.nvim_buf_line_count(bufnr) + local line_count = api.nvim_buf_line_count(bufnr) local diagnostics = get_diagnostics(bufnr, vim.tbl_extend('keep', opts, { namespace = namespace }), true) local line_diagnostics = diagnostic_lines(diagnostics) @@ -513,7 +493,7 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace) lnum = (lnum + line_count) % line_count end if line_diagnostics[lnum] and not vim.tbl_isempty(line_diagnostics[lnum]) then - local line_length = #vim.api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1] + local line_length = #api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1] local sort_diagnostics, is_next if search_forward then sort_diagnostics = function(a, b) @@ -549,17 +529,17 @@ local function diagnostic_move_pos(opts, pos) opts = opts or {} local float = vim.F.if_nil(opts.float, true) - local win_id = opts.win_id or vim.api.nvim_get_current_win() + local win_id = opts.win_id or api.nvim_get_current_win() if not pos then - vim.api.nvim_echo({ { 'No more valid diagnostics to move to', 'WarningMsg' } }, true, {}) + api.nvim_echo({ { 'No more valid diagnostics to move to', 'WarningMsg' } }, true, {}) return end - vim.api.nvim_win_call(win_id, function() + api.nvim_win_call(win_id, function() -- Save position in the window's jumplist vim.cmd("normal! m'") - vim.api.nvim_win_set_cursor(win_id, { pos[1] + 1, pos[2] }) + api.nvim_win_set_cursor(win_id, { pos[1] + 1, pos[2] }) -- Open folds under the cursor vim.cmd('normal! zv') end) @@ -568,7 +548,7 @@ local function diagnostic_move_pos(opts, pos) local float_opts = type(float) == 'table' and float or {} vim.schedule(function() M.open_float(vim.tbl_extend('keep', float_opts, { - bufnr = vim.api.nvim_win_get_buf(win_id), + bufnr = api.nvim_win_get_buf(win_id), scope = 'cursor', focus = false, })) @@ -585,12 +565,12 @@ end --- followed by namespace configuration, and finally global configuration. --- --- For example, if a user enables virtual text globally with ---- <pre> +--- <pre>lua --- vim.diagnostic.config({ virtual_text = true }) --- </pre> --- --- and a diagnostic producer sets diagnostics with ---- <pre> +--- <pre>lua --- vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) --- </pre> --- @@ -620,16 +600,20 @@ end --- * spacing: (number) Amount of empty spaces inserted at the beginning --- of the virtual text. --- * prefix: (string) Prepend diagnostic message with prefix. +--- * suffix: (string or function) Append diagnostic message with suffix. +--- If a function, it must have the signature (diagnostic) -> +--- string, where {diagnostic} is of type |diagnostic-structure|. +--- This can be used to render an LSP diagnostic error code. --- * format: (function) A function that takes a diagnostic as input and --- returns a string. The return value is the text used to display --- the diagnostic. Example: ---- <pre> ---- function(diagnostic) ---- if diagnostic.severity == vim.diagnostic.severity.ERROR then ---- return string.format("E: %s", diagnostic.message) +--- <pre>lua +--- function(diagnostic) +--- if diagnostic.severity == vim.diagnostic.severity.ERROR then +--- return string.format("E: %s", diagnostic.message) +--- end +--- return diagnostic.message --- end ---- return diagnostic.message ---- end --- </pre> --- - signs: (default true) Use signs for diagnostics. Options: --- * severity: Only show signs for diagnostics matching the given severity @@ -673,13 +657,13 @@ function M.config(opts, namespace) if namespace then for bufnr, v in pairs(diagnostic_cache) do - if vim.api.nvim_buf_is_loaded(bufnr) and v[namespace] then + if api.nvim_buf_is_loaded(bufnr) and v[namespace] then M.show(namespace, bufnr) end end else for bufnr, v in pairs(diagnostic_cache) do - if vim.api.nvim_buf_is_loaded(bufnr) then + if api.nvim_buf_is_loaded(bufnr) then for ns in pairs(v) do M.show(ns, bufnr) end @@ -714,13 +698,14 @@ function M.set(namespace, bufnr, diagnostics, opts) set_diagnostic_cache(namespace, bufnr, diagnostics) end - if vim.api.nvim_buf_is_loaded(bufnr) then + if api.nvim_buf_is_loaded(bufnr) then M.show(namespace, bufnr, nil, opts) end - vim.api.nvim_exec_autocmds('DiagnosticChanged', { + api.nvim_exec_autocmds('DiagnosticChanged', { modeline = false, buffer = bufnr, + data = { diagnostics = diagnostics }, }) end @@ -732,7 +717,7 @@ function M.get_namespace(namespace) vim.validate({ namespace = { namespace, 'n' } }) if not all_namespaces[namespace] then local name - for k, v in pairs(vim.api.nvim_get_namespaces()) do + for k, v in pairs(api.nvim_get_namespaces()) do if namespace == v then name = k break @@ -757,6 +742,18 @@ function M.get_namespaces() return vim.deepcopy(all_namespaces) end +---@class Diagnostic +---@field buffer number +---@field lnum number 0-indexed +---@field end_lnum nil|number 0-indexed +---@field col number 0-indexed +---@field end_col nil|number 0-indexed +---@field severity DiagnosticSeverity +---@field message string +---@field source nil|string +---@field code nil|string +---@field user_data nil|any arbitrary data plugins can add + --- Get current diagnostics. --- ---@param bufnr number|nil Buffer number to get diagnostics from. Use 0 for @@ -765,7 +762,7 @@ end --- - namespace: (number) Limit diagnostics to the given namespace. --- - lnum: (number) Limit diagnostics to the given line number. --- - severity: See |diagnostic-severity|. ----@return table A list of diagnostic items |diagnostic-structure|. +---@return Diagnostic[] table A list of diagnostic items |diagnostic-structure|. function M.get(bufnr, opts) vim.validate({ bufnr = { bufnr, 'n', true }, @@ -777,22 +774,23 @@ end --- Get the previous diagnostic closest to the cursor position. --- ----@param opts table See |vim.diagnostic.goto_next()| ----@return table Previous diagnostic +---@param opts nil|table See |vim.diagnostic.goto_next()| +---@return Diagnostic|nil Previous diagnostic function M.get_prev(opts) opts = opts or {} - local win_id = opts.win_id or vim.api.nvim_get_current_win() - local bufnr = vim.api.nvim_win_get_buf(win_id) - local cursor_position = opts.cursor_position or vim.api.nvim_win_get_cursor(win_id) + local win_id = opts.win_id or api.nvim_get_current_win() + local bufnr = api.nvim_win_get_buf(win_id) + local cursor_position = opts.cursor_position or api.nvim_win_get_cursor(win_id) return next_diagnostic(cursor_position, false, bufnr, opts, opts.namespace) end --- Return the position of the previous diagnostic in the current buffer. --- ----@param opts table See |vim.diagnostic.goto_next()| ----@return table Previous diagnostic position as a (row, col) tuple. +---@param opts table|nil See |vim.diagnostic.goto_next()| +---@return table|false Previous diagnostic position as a (row, col) tuple or false if there is no +--- prior diagnostic function M.get_prev_pos(opts) local prev = M.get_prev(opts) if not prev then @@ -803,29 +801,30 @@ function M.get_prev_pos(opts) end --- Move to the previous diagnostic in the current buffer. ----@param opts table See |vim.diagnostic.goto_next()| +---@param opts table|nil See |vim.diagnostic.goto_next()| function M.goto_prev(opts) return diagnostic_move_pos(opts, M.get_prev_pos(opts)) end --- Get the next diagnostic closest to the cursor position. --- ----@param opts table See |vim.diagnostic.goto_next()| ----@return table Next diagnostic +---@param opts table|nil See |vim.diagnostic.goto_next()| +---@return Diagnostic|nil Next diagnostic function M.get_next(opts) opts = opts or {} - local win_id = opts.win_id or vim.api.nvim_get_current_win() - local bufnr = vim.api.nvim_win_get_buf(win_id) - local cursor_position = opts.cursor_position or vim.api.nvim_win_get_cursor(win_id) + local win_id = opts.win_id or api.nvim_get_current_win() + local bufnr = api.nvim_win_get_buf(win_id) + local cursor_position = opts.cursor_position or api.nvim_win_get_cursor(win_id) return next_diagnostic(cursor_position, true, bufnr, opts, opts.namespace) end --- Return the position of the next diagnostic in the current buffer. --- ----@param opts table See |vim.diagnostic.goto_next()| ----@return table Next diagnostic position as a (row, col) tuple. +---@param opts table|nil See |vim.diagnostic.goto_next()| +---@return table|false Next diagnostic position as a (row, col) tuple or false if no next +--- diagnostic. function M.get_next_pos(opts) local next = M.get_next(opts) if not next then @@ -909,7 +908,7 @@ M.handlers.signs = { end, hide = function(namespace, bufnr) local ns = M.get_namespace(namespace) - if ns.user_data.sign_group then + if ns.user_data.sign_group and api.nvim_buf_is_valid(bufnr) then vim.fn.sign_unplace(ns.user_data.sign_group, { buffer = bufnr }) end end, @@ -937,7 +936,7 @@ M.handlers.underline = { local ns = M.get_namespace(namespace) if not ns.user_data.underline_ns then - ns.user_data.underline_ns = vim.api.nvim_create_namespace('') + ns.user_data.underline_ns = api.nvim_create_namespace('') end local underline_ns = ns.user_data.underline_ns @@ -964,7 +963,9 @@ M.handlers.underline = { local ns = M.get_namespace(namespace) if ns.user_data.underline_ns then diagnostic_cache_extmarks[bufnr][ns.user_data.underline_ns] = {} - vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.underline_ns, 0, -1) + if api.nvim_buf_is_valid(bufnr) then + api.nvim_buf_clear_namespace(bufnr, ns.user_data.underline_ns, 0, -1) + end end end, } @@ -1003,7 +1004,7 @@ M.handlers.virtual_text = { local ns = M.get_namespace(namespace) if not ns.user_data.virt_text_ns then - ns.user_data.virt_text_ns = vim.api.nvim_create_namespace('') + ns.user_data.virt_text_ns = api.nvim_create_namespace('') end local virt_text_ns = ns.user_data.virt_text_ns @@ -1015,7 +1016,7 @@ M.handlers.virtual_text = { local virt_texts = M._get_virt_text_chunks(line_diagnostics, opts.virtual_text) if virt_texts then - vim.api.nvim_buf_set_extmark(bufnr, virt_text_ns, line, 0, { + api.nvim_buf_set_extmark(bufnr, virt_text_ns, line, 0, { hl_mode = 'combine', virt_text = virt_texts, }) @@ -1027,7 +1028,9 @@ M.handlers.virtual_text = { local ns = M.get_namespace(namespace) if ns.user_data.virt_text_ns then diagnostic_cache_extmarks[bufnr][ns.user_data.virt_text_ns] = {} - vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.virt_text_ns, 0, -1) + if api.nvim_buf_is_valid(bufnr) then + api.nvim_buf_clear_namespace(bufnr, ns.user_data.virt_text_ns, 0, -1) + end end end, } @@ -1045,6 +1048,7 @@ function M._get_virt_text_chunks(line_diags, opts) opts = opts or {} local prefix = opts.prefix or 'â– ' + local suffix = opts.suffix or '' local spacing = opts.spacing or 4 -- Create a little more space between virtual text and contents @@ -1058,8 +1062,11 @@ function M._get_virt_text_chunks(line_diags, opts) -- TODO(tjdevries): Allow different servers to be shown first somehow? -- TODO(tjdevries): Display server name associated with these? if last.message then + if type(suffix) == 'function' then + suffix = suffix(last) or '' + end table.insert(virt_texts, { - string.format('%s %s', prefix, last.message:gsub('\r', ''):gsub('\n', ' ')), + string.format('%s %s%s', prefix, last.message:gsub('\r', ''):gsub('\n', ' '), suffix), virtual_text_highlight_map[last.severity], }) @@ -1099,6 +1106,27 @@ function M.hide(namespace, bufnr) end end +--- Check whether diagnostics are disabled in a given buffer. +--- +---@param bufnr number|nil Buffer number, or 0 for current buffer. +---@param namespace number|nil Diagnostic namespace. When omitted, checks if +--- all diagnostics are disabled in {bufnr}. +--- Otherwise, only checks if diagnostics from +--- {namespace} are disabled. +---@return boolean +function M.is_disabled(bufnr, namespace) + bufnr = get_bufnr(bufnr) + if namespace and M.get_namespace(namespace).disabled then + return true + end + + if type(diagnostic_disabled[bufnr]) == 'table' then + return diagnostic_disabled[bufnr][namespace] + end + + return diagnostic_disabled[bufnr] ~= nil +end + --- Display diagnostics for the given namespace and buffer. --- ---@param namespace number|nil Diagnostic namespace. When omitted, show @@ -1142,7 +1170,7 @@ function M.show(namespace, bufnr, diagnostics, opts) return end - if is_disabled(namespace, bufnr) then + if M.is_disabled(bufnr, namespace) then return end @@ -1159,7 +1187,7 @@ function M.show(namespace, bufnr, diagnostics, opts) if opts.update_in_insert then clear_scheduled_display(namespace, bufnr) else - local mode = vim.api.nvim_get_mode() + local mode = api.nvim_get_mode() if string.sub(mode.mode, 1, 1) == 'i' then schedule_display(namespace, bufnr, opts) return @@ -1226,7 +1254,9 @@ end --- string, it is prepended to each diagnostic in the window with no --- highlight. --- Overrides the setting from |vim.diagnostic.config()|. ----@return tuple ({float_bufnr}, {win_id}) +--- - suffix: Same as {prefix}, but appends the text to the diagnostic instead of +--- prepending it. Overrides the setting from |vim.diagnostic.config()|. +---@return number|nil, number|nil: ({float_bufnr}, {win_id}) function M.open_float(opts, ...) -- Support old (bufnr, opts) signature local bufnr @@ -1257,7 +1287,7 @@ function M.open_float(opts, ...) local lnum, col if scope == 'line' or scope == 'cursor' then if not opts.pos then - local pos = vim.api.nvim_win_get_cursor(0) + local pos = api.nvim_win_get_cursor(0) lnum = pos[1] - 1 col = pos[2] elseif type(opts.pos) == 'number' then @@ -1279,7 +1309,7 @@ function M.open_float(opts, ...) end, diagnostics) elseif scope == 'cursor' then -- LSP servers can send diagnostics with `end_col` past the length of the line - local line_length = #vim.api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1] + local line_length = #api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1] diagnostics = vim.tbl_filter(function(d) return d.lnum == lnum and math.min(d.col, line_length - 1) <= col @@ -1311,9 +1341,7 @@ function M.open_float(opts, ...) vim.validate({ header = { header, - function(v) - return type(v) == 'string' or type(v) == 'table' - end, + { 'string', 'table' }, "'string' or 'table'", }, }) @@ -1321,11 +1349,11 @@ function M.open_float(opts, ...) -- Don't insert any lines for an empty string if string.len(if_nil(header[1], '')) > 0 then table.insert(lines, header[1]) - table.insert(highlights, { 0, header[2] or 'Bold' }) + table.insert(highlights, { hlname = header[2] or 'Bold' }) end elseif #header > 0 then table.insert(lines, header) - table.insert(highlights, { 0, 'Bold' }) + table.insert(highlights, { hlname = 'Bold' }) end end @@ -1347,9 +1375,7 @@ function M.open_float(opts, ...) vim.validate({ prefix = { prefix_opt, - function(v) - return type(v) == 'string' or type(v) == 'table' or type(v) == 'function' - end, + { 'string', 'table', 'function' }, "'string' or 'table' or 'function'", }, }) @@ -1360,18 +1386,52 @@ function M.open_float(opts, ...) end end + local suffix_opt = if_nil(opts.suffix, function(diagnostic) + return diagnostic.code and string.format(' [%s]', diagnostic.code) or '' + end) + + local suffix, suffix_hl_group + if suffix_opt then + vim.validate({ + suffix = { + suffix_opt, + { 'string', 'table', 'function' }, + "'string' or 'table' or 'function'", + }, + }) + if type(suffix_opt) == 'string' then + suffix, suffix_hl_group = suffix_opt, 'NormalFloat' + elseif type(suffix_opt) == 'table' then + suffix, suffix_hl_group = suffix_opt[1] or '', suffix_opt[2] or 'NormalFloat' + end + end + for i, diagnostic in ipairs(diagnostics) do if prefix_opt and type(prefix_opt) == 'function' then prefix, prefix_hl_group = prefix_opt(diagnostic, i, #diagnostics) prefix, prefix_hl_group = prefix or '', prefix_hl_group or 'NormalFloat' end + if suffix_opt and type(suffix_opt) == 'function' then + suffix, suffix_hl_group = suffix_opt(diagnostic, i, #diagnostics) + suffix, suffix_hl_group = suffix or '', suffix_hl_group or 'NormalFloat' + end local hiname = floating_highlight_map[diagnostic.severity] local message_lines = vim.split(diagnostic.message, '\n') - table.insert(lines, prefix .. message_lines[1]) - table.insert(highlights, { #prefix, hiname, prefix_hl_group }) - for j = 2, #message_lines do - table.insert(lines, string.rep(' ', #prefix) .. message_lines[j]) - table.insert(highlights, { 0, hiname }) + for j = 1, #message_lines do + local pre = j == 1 and prefix or string.rep(' ', #prefix) + local suf = j == #message_lines and suffix or '' + table.insert(lines, pre .. message_lines[j] .. suf) + table.insert(highlights, { + hlname = hiname, + prefix = { + length = j == 1 and #prefix or 0, + hlname = prefix_hl_group, + }, + suffix = { + length = j == #message_lines and #suffix or 0, + hlname = suffix_hl_group, + }, + }) end end @@ -1380,12 +1440,17 @@ function M.open_float(opts, ...) opts.focus_id = scope end local float_bufnr, winnr = require('vim.lsp.util').open_floating_preview(lines, 'plaintext', opts) - for i, hi in ipairs(highlights) do - local prefixlen, hiname, prefix_hiname = unpack(hi) - if prefix_hiname then - vim.api.nvim_buf_add_highlight(float_bufnr, -1, prefix_hiname, i - 1, 0, prefixlen) + for i, hl in ipairs(highlights) do + local line = lines[i] + local prefix_len = hl.prefix and hl.prefix.length or 0 + local suffix_len = hl.suffix and hl.suffix.length or 0 + if prefix_len > 0 then + api.nvim_buf_add_highlight(float_bufnr, -1, hl.prefix.hlname, i - 1, 0, prefix_len) + end + api.nvim_buf_add_highlight(float_bufnr, -1, hl.hlname, i - 1, prefix_len, #line - suffix_len) + if suffix_len > 0 then + api.nvim_buf_add_highlight(float_bufnr, -1, hl.suffix.hlname, i - 1, #line - suffix_len, -1) end - vim.api.nvim_buf_add_highlight(float_bufnr, -1, hiname, i - 1, prefixlen, -1) end return float_bufnr, winnr @@ -1416,10 +1481,15 @@ function M.reset(namespace, bufnr) M.hide(iter_namespace, iter_bufnr) end - vim.api.nvim_exec_autocmds('DiagnosticChanged', { - modeline = false, - buffer = iter_bufnr, - }) + if api.nvim_buf_is_valid(iter_bufnr) then + api.nvim_exec_autocmds('DiagnosticChanged', { + modeline = false, + buffer = iter_bufnr, + data = { diagnostics = {} }, + }) + else + diagnostic_cache[iter_bufnr] = nil + end end end @@ -1522,11 +1592,11 @@ end --- --- This can be parsed into a diagnostic |diagnostic-structure| --- with: ---- <pre> ---- local s = "WARNING filename:27:3: Variable 'foo' does not exist" ---- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" ---- local groups = { "severity", "lnum", "col", "message" } ---- vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) +--- <pre>lua +--- local s = "WARNING filename:27:3: Variable 'foo' does not exist" +--- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" +--- local groups = { "severity", "lnum", "col", "message" } +--- vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) --- </pre> --- ---@param str string String to parse diagnostics from. @@ -1538,7 +1608,7 @@ end ---@param 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. ----@return diagnostic |diagnostic-structure| or `nil` if {pat} fails to match {str}. +---@return Diagnostic|nil: |diagnostic-structure| or `nil` if {pat} fails to match {str}. function M.match(str, pat, groups, severity_map, defaults) vim.validate({ str = { str, 's' }, @@ -1585,7 +1655,7 @@ local errlist_type_map = { --- passed to |setqflist()| or |setloclist()|. --- ---@param diagnostics table List of diagnostics |diagnostic-structure|. ----@return array of quickfix list items |setqflist-what| +---@return table[] of quickfix list items |setqflist-what| function M.toqflist(diagnostics) vim.validate({ diagnostics = { @@ -1610,7 +1680,11 @@ function M.toqflist(diagnostics) end table.sort(list, function(a, b) if a.bufnr == b.bufnr then - return a.lnum < b.lnum + if a.lnum == b.lnum then + return a.col < b.col + else + return a.lnum < b.lnum + end else return a.bufnr < b.bufnr end @@ -1622,7 +1696,7 @@ end --- ---@param list table A list of quickfix items from |getqflist()| or --- |getloclist()|. ----@return array of diagnostics |diagnostic-structure| +---@return Diagnostic[] array of |diagnostic-structure| function M.fromqflist(list) vim.validate({ list = { diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 99c98764dd..9293c828b8 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -170,13 +170,14 @@ local extension = { return require('vim.filetype.detect').bindzone(bufnr, 'dcl') end, db = function(path, bufnr) - return require('vim.filetype.detect').bindzone(bufnr, '') + return require('vim.filetype.detect').bindzone(bufnr) end, bicep = 'bicep', bb = 'bitbake', bbappend = 'bitbake', bbclass = 'bitbake', bl = 'blank', + blp = 'blueprint', bsd = 'bsdl', bsdl = 'bsdl', bst = 'bst', @@ -189,6 +190,7 @@ local extension = { BUILD = 'bzl', qc = 'c', cabal = 'cabal', + capnp = 'capnp', cdl = 'cdl', toc = 'cdrtoc', cfc = 'cf', @@ -201,6 +203,7 @@ local extension = { return require('vim.filetype.detect').change(bufnr) end, chs = 'chaskell', + chatito = 'chatito', chopro = 'chordpro', crd = 'chordpro', crdpro = 'chordpro', @@ -255,6 +258,7 @@ local extension = { cc = function(path, bufnr) return vim.g.cynlib_syntax_for_cc and 'cynlib' or 'cpp' end, + cql = 'cqlang', crm = 'crm', csx = 'cs', cs = 'cs', @@ -324,11 +328,7 @@ local extension = { end, eex = 'eelixir', leex = 'eelixir', - am = function(path, bufnr) - if not path:lower():find('makefile%.am$') then - return 'elf' - end - end, + am = 'elf', exs = 'elixir', elm = 'elm', elv = 'elvish', @@ -416,15 +416,18 @@ local extension = { fs = function(path, bufnr) return require('vim.filetype.detect').fs(bufnr) end, + fsh = 'fsh', fsi = 'fsharp', fsx = 'fsharp', fusion = 'fusion', 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 +447,8 @@ local extension = { gsp = 'gsp', gjs = 'javascript.glimmer', gts = 'typescript.glimmer', + gyp = 'gyp', + gypi = 'gyp', hack = 'hack', hackpartial = 'hack', haml = 'haml', @@ -469,6 +474,8 @@ local extension = { hex = 'hex', ['h32'] = 'hex', hjson = 'hjson', + m3u = 'hlsplaylist', + m3u8 = 'hlsplaylist', hog = 'hog', hws = 'hollywood', hoon = 'hoon', @@ -538,6 +545,7 @@ local extension = { mjs = 'javascript', javascript = 'javascript', js = 'javascript', + jsm = 'javascript', cjs = 'javascript', jsx = 'javascriptreact', clp = 'jess', @@ -546,6 +554,7 @@ local extension = { jov = 'jovial', jovial = 'jovial', properties = 'jproperties', + jq = 'jq', slnf = 'json', json = 'json', jsonp = 'json', @@ -554,6 +563,8 @@ local extension = { ['json-patch'] = 'json', json5 = 'json5', jsonc = 'jsonc', + jsonnet = 'jsonnet', + libsonnet = 'jsonnet', jsp = 'jsp', jl = 'julia', kv = 'kivy', @@ -600,11 +611,14 @@ local extension = { c = function(path, bufnr) return require('vim.filetype.detect').lpc(bufnr) end, - lsl = 'lsl', + lsl = function(path, bufnr) + return require('vim.filetype.detect').lsl(bufnr) + end, lss = 'lss', nse = 'lua', rockspec = 'lua', lua = 'lua', + lrc = 'lyrics', m = function(path, bufnr) return require('vim.filetype.detect').m(bufnr) end, @@ -644,6 +658,9 @@ local extension = { dmt = 'maxima', wxm = 'maxima', mel = 'mel', + mmd = 'mermaid', + mmdc = 'mermaid', + mermaid = 'mermaid', mf = 'mf', mgl = 'mgl', mgp = 'mgp', @@ -662,6 +679,7 @@ local extension = { DEF = 'modula2', ['m2'] = 'modula2', mi = 'modula2', + lm3 = 'modula3', ssc = 'monk', monk = 'monk', tsc = 'monk', @@ -695,6 +713,9 @@ local extension = { nanorc = 'nanorc', ncf = 'ncf', nginx = 'nginx', + nim = 'nim', + nims = 'nim', + nimble = 'nim', ninja = 'ninja', nix = 'nix', nqc = 'nqc', @@ -707,6 +728,10 @@ local extension = { nsi = 'nsis', nsh = 'nsis', obj = 'obj', + obl = 'obse', + obse = 'obse', + oblivion = 'obse', + obscript = 'obse', mlt = 'ocaml', mly = 'ocaml', mll = 'ocaml', @@ -720,6 +745,7 @@ local extension = { opam = 'opam', ['or'] = 'openroad', scad = 'openscad', + ovpn = 'openvpn', ora = 'ora', org = 'org', org_archive = 'org', @@ -741,6 +767,7 @@ local extension = { php = 'php', phpt = 'php', phtml = 'php', + theme = 'php', pike = 'pike', pmod = 'pike', rcp = 'pilrc', @@ -758,6 +785,7 @@ local extension = { po = 'po', pot = 'po', pod = 'pod', + filter = 'poefilter', pk = 'poke', ps = 'postscr', epsi = 'postscr', @@ -900,7 +928,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', @@ -916,12 +946,14 @@ local extension = { ice = 'slice', score = 'slrnsc', sol = 'solidity', + smali = 'smali', tpl = 'smarty', ihlp = 'smcl', smcl = 'smcl', hlp = 'smcl', smith = 'smith', smt = 'smith', + smithy = 'smithy', sml = 'sml', spt = 'snobol4', sno = 'snobol4', @@ -950,6 +982,9 @@ local extension = { srec = 'srec', mot = 'srec', ['s19'] = 'srec', + srt = 'srt', + ssa = 'ssa', + ass = 'ssa', st = 'st', imata = 'stata', ['do'] = 'stata', @@ -987,6 +1022,7 @@ local extension = { texinfo = 'texinfo', text = 'text', tfvars = 'terraform-vars', + thrift = 'thrift', tla = 'tla', tli = 'tli', toml = 'toml', @@ -1002,6 +1038,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 +1049,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', @@ -1023,6 +1067,7 @@ local extension = { hdl = 'vhdl', vho = 'vhdl', vbe = 'vhdl', + tape = 'vhs', vim = 'vim', vba = 'vim', mar = 'vmasm', @@ -1032,6 +1077,7 @@ local extension = { vue = 'vue', wat = 'wast', wast = 'wast', + wdl = 'wdl', wm = 'webmacro', wbt = 'winbatch', wml = 'wml', @@ -1078,6 +1124,7 @@ local extension = { yang = 'yang', ['z8a'] = 'z8a', zig = 'zig', + zir = 'zir', zu = 'zimbu', zut = 'zimbutempl', zsh = 'zsh', @@ -1276,9 +1323,9 @@ local filename = { ['GNUmakefile.am'] = 'automake', ['named.root'] = 'bindzone', WORKSPACE = 'bzl', + ['WORKSPACE.bzlmod'] = 'bzl', BUILD = 'bzl', ['cabal.project'] = 'cabalproject', - [vim.env.HOME .. '/cabal.config'] = 'cabalconfig', ['cabal.config'] = 'cabalconfig', calendar = 'calendar', catalog = 'catalog', @@ -1332,13 +1379,13 @@ local filename = { npmrc = 'dosini', ['/etc/yum.conf'] = 'dosini', ['.npmrc'] = 'dosini', - ['.editorconfig'] = 'dosini', ['/etc/pacman.conf'] = 'confini', ['mpv.conf'] = 'confini', dune = 'dune', jbuild = 'dune', ['dune-workspace'] = 'dune', ['dune-project'] = 'dune', + ['.editorconfig'] = 'editorconfig', ['elinks.conf'] = 'elinks', ['mix.lock'] = 'elixir', ['filter-rules'] = 'elmfilt', @@ -1371,6 +1418,8 @@ local filename = { ['EDIT_DESCRIPTION'] = 'gitcommit', ['.gitconfig'] = 'gitconfig', ['.gitmodules'] = 'gitconfig', + ['.gitattributes'] = 'gitattributes', + ['.gitignore'] = 'gitignore', ['gitolite.conf'] = 'gitolite', ['git-rebase-todo'] = 'gitrebase', gkrellmrc = 'gkrellmrc', @@ -1379,6 +1428,7 @@ local filename = { gnashpluginrc = 'gnash', gnashrc = 'gnash', ['.gnuplot'] = 'gnuplot', + ['go.sum'] = 'gosum', ['go.work'] = 'gowork', ['.gprc'] = 'gp', ['/.gnupg/gpg.conf'] = 'gpg', @@ -1408,11 +1458,15 @@ local filename = { ['ipf.conf'] = 'ipfilter', ['ipf6.conf'] = 'ipfilter', ['ipf.rules'] = 'ipfilter', - ['.eslintrc'] = 'json', - ['.babelrc'] = 'json', ['Pipfile.lock'] = 'json', ['.firebaserc'] = 'json', ['.prettierrc'] = 'json', + ['.babelrc'] = 'jsonc', + ['.eslintrc'] = 'jsonc', + ['.hintrc'] = 'jsonc', + ['.jsfmtrc'] = 'jsonc', + ['.jshintrc'] = 'jsonc', + ['.swrc'] = 'jsonc', Kconfig = 'kconfig', ['Kconfig.debug'] = 'kconfig', ['lftp.conf'] = 'lftp', @@ -1427,6 +1481,10 @@ local filename = { ['.sawfishrc'] = 'lisp', ['/etc/login.access'] = 'loginaccess', ['/etc/login.defs'] = 'logindefs', + ['.lsl'] = function(path, bufnr) + return require('vim.filetype.detect').lsl(bufnr) + end, + ['.luacheckrc'] = 'lua', ['lynx.cfg'] = 'lynx', ['m3overrides'] = 'm3build', ['m3makefile'] = 'm3build', @@ -1472,8 +1530,11 @@ local filename = { ['/etc/shadow-'] = 'passwd', ['/etc/shadow'] = 'passwd', ['/etc/passwd.edit'] = 'passwd', + ['latexmkrc'] = 'perl', + ['.latexmkrc'] = 'perl', ['pf.conf'] = 'pf', ['main.cf'] = 'pfmain', + ['main.cf.proto'] = 'pfmain', pinerc = 'pine', ['.pinercex'] = 'pine', ['.pinerc'] = 'pine', @@ -1506,6 +1567,9 @@ local filename = { ['.pythonstartup'] = 'python', ['.pythonrc'] = 'python', SConstruct = 'python', + ['.Rprofile'] = 'r', + ['Rprofile'] = 'r', + ['Rprofile.site'] = 'r', ratpoisonrc = 'ratpoison', ['.ratpoisonrc'] = 'ratpoison', inputrc = 'readline', @@ -1632,6 +1696,8 @@ local filename = { fglrxrc = 'xml', ['/etc/blkid.tab'] = 'xml', ['/etc/blkid.tab.old'] = 'xml', + ['.clang-format'] = 'yaml', + ['.clang-tidy'] = 'yaml', ['/etc/zprofile'] = 'zsh', ['.zlogin'] = 'zsh', ['.zlogout'] = 'zsh', @@ -1684,6 +1750,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 +1769,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', @@ -1744,6 +1811,8 @@ local pattern = { ['.*/etc/DIR_COLORS'] = 'dircolors', ['.*/etc/dnsmasq%.conf'] = 'dnsmasq', ['php%.ini%-.*'] = 'dosini', + ['.*/%.aws/config'] = 'confini', + ['.*/%.aws/credentials'] = 'confini', ['.*/etc/pacman%.conf'] = 'confini', ['.*/etc/yum%.conf'] = 'dosini', ['.*lvs'] = 'dracula', @@ -1808,26 +1877,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 +1905,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', @@ -1855,7 +1919,9 @@ local pattern = { ['Prl.*%..*'] = starsetf('jam'), ['.*%.properties_..'] = 'jproperties', ['.*%.properties_.._..'] = 'jproperties', + ['org%.eclipse%..*%.prefs'] = 'jproperties', ['.*%.properties_.._.._.*'] = starsetf('jproperties'), + ['[jt]sconfig.*%.json'] = 'jsonc', ['Kconfig%..*'] = starsetf('kconfig'), ['.*%.[Ss][Uu][Bb]'] = 'krl', ['lilo%.conf.*'] = starsetf('lilo'), @@ -2009,6 +2075,7 @@ local pattern = { ['.*%.ml%.cppo'] = 'ocaml', ['.*%.mli%.cppo'] = 'ocaml', ['.*%.opam%.template'] = 'opam', + ['.*/openvpn/.*/.*%.conf'] = 'openvpn', ['.*%.[Oo][Pp][Ll]'] = 'opl', ['.*/etc/pam%.conf'] = 'pamconf', ['.*/etc/pam%.d/.*'] = starsetf('pamconf'), @@ -2245,13 +2312,14 @@ 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. --- ---- Note that Lua filetype detection is disabled when |g:do_legacy_filetype| is set. ---- --- Example: ---- <pre> +--- <pre>lua --- vim.filetype.add({ --- extension = { --- foo = 'fooscript', @@ -2273,6 +2341,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' @@ -2284,8 +2354,8 @@ end --- }) --- </pre> --- ---- To add a fallback match on contents (see |new-filetype-scripts|), use ---- <pre> +--- To add a fallback match on contents, use +--- <pre>lua --- vim.filetype.add { --- pattern = { --- ['.*'] = { @@ -2346,8 +2416,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 @@ -2377,7 +2467,7 @@ end --- Each of the three options is specified using a key to the single argument of this function. --- Example: --- ---- <pre> +--- <pre>lua --- -- Using a buffer number --- vim.filetype.match({ buf = 42 }) --- diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index 2be9dcff88..edffdde9c7 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -181,7 +181,7 @@ function M.cls(bufnr) return vim.g.filetype_cls end local line = getlines(bufnr, 1) - if line:find('^%%') then + if line:find('^[%%\\]') then return 'tex' elseif line:find('^#') and line:lower():find('rexx') then return 'rexx' @@ -634,6 +634,19 @@ function M.lpc(bufnr) return 'c' end +function M.lsl(bufnr) + if vim.g.filetype_lsl then + return vim.g.filetype_lsl + end + + local line = nextnonblank(bufnr, 1) + if findany(line, { '^%s*%%', ':%s*trait%s*$' }) then + return 'larch' + else + return 'lsl' + end +end + function M.m(bufnr) if vim.g.filetype_m then return vim.g.filetype_m @@ -1084,11 +1097,10 @@ function M.sc(bufnr) for _, line in ipairs(getlines(bufnr, 1, 25)) do if findany(line, { - '[A-Za-z0-9]*%s:%s[A-Za-z0-9]', 'var%s<', 'classvar%s<', '%^this.*', - '|%w*|', + '|%w+|', '%+%s%w*%s{', '%*ar%s', }) @@ -1153,13 +1165,14 @@ function M.sh(path, contents, name) vim.b[b].is_bash = nil vim.b[b].is_sh = nil end - elseif vim.g.bash_is_sh or matchregex(name, [[\<bash\>]]) or matchregex(name, [[\<bash2\>]]) then + elseif vim.g.bash_is_sh or matchregex(name, [[\<\(bash\|bash2\)\>]]) then on_detect = function(b) vim.b[b].is_bash = 1 vim.b[b].is_kornshell = nil vim.b[b].is_sh = nil end - elseif matchregex(name, [[\<sh\>]]) then + -- Ubuntu links sh to dash + elseif matchregex(name, [[\<\(sh\|dash\)\>]]) then on_detect = function(b) vim.b[b].is_sh = 1 vim.b[b].is_kornshell = nil @@ -1194,6 +1207,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) @@ -1230,17 +1256,15 @@ end -- 2. Check the first 1000 non-comment lines for LaTeX or ConTeXt keywords. -- 3. Default to "plain" or to g:tex_flavor, can be set in user's vimrc. function M.tex(path, bufnr) - local format = getlines(bufnr, 1):find('^%%&%s*(%a+)') - if format then + local matched, _, format = getlines(bufnr, 1):find('^%%&%s*(%a+)') + if matched then format = format:lower():gsub('pdf', '', 1) - if format == 'tex' then - return 'tex' - elseif format == 'plaintex' then - return 'plaintex' - end elseif path:lower():find('tex/context/.*/.*%.tex') then return 'context' else + -- Default value, may be changed later: + format = vim.g.tex_flavor or 'plaintex' + local lpat = [[documentclass\>\|usepackage\>\|begin{\|newcommand\>\|renewcommand\>]] local cpat = [[start\a\+\|setup\a\+\|usemodule\|enablemode\|enableregime\|setvariables\|useencoding\|usesymbols\|stelle\a\+\|verwende\a\+\|stel\a\+\|gebruik\a\+\|usa\a\+\|imposta\a\+\|regle\a\+\|utilisemodule\>]] @@ -1249,26 +1273,25 @@ function M.tex(path, bufnr) -- Find first non-comment line if not l:find('^%s*%%%S') then -- Check the next thousand lines for a LaTeX or ConTeXt keyword. - for _, line in ipairs(getlines(bufnr, i + 1, i + 1000)) do - local lpat_match, cpat_match = - matchregex(line, [[\c^\s*\\\%(]] .. lpat .. [[\)\|^\s*\\\(]] .. cpat .. [[\)]]) - if lpat_match then + for _, line in ipairs(getlines(bufnr, i, i + 1000)) do + if matchregex(line, [[\c^\s*\\\%(]] .. lpat .. [[\)]]) then return 'tex' - elseif cpat_match then + elseif matchregex(line, [[\c^\s*\\\%(]] .. cpat .. [[\)]]) then return 'context' end end end end - -- TODO: add AMSTeX, RevTex, others? - if not vim.g.tex_flavor or vim.g.tex_flavor == 'plain' then - return 'plaintex' - elseif vim.g.tex_flavor == 'context' then - return 'context' - else - -- Probably LaTeX - return 'tex' - end + end -- if matched + + -- Translation from formats to file types. TODO: add AMSTeX, RevTex, others? + if format == 'plain' then + return 'plaintex' + elseif format == 'plaintex' or format == 'context' then + return format + else + -- Probably LaTeX + return 'tex' end end @@ -1434,8 +1457,8 @@ local function match_from_hashbang(contents, path) name = 'wish' end - if matchregex(name, [[^\(bash\d*\|\|ksh\d*\|sh\)\>]]) then - -- Bourne-like shell scripts: bash bash2 ksh ksh93 sh + if matchregex(name, [[^\(bash\d*\|dash\|ksh\d*\|sh\)\>]]) then + -- Bourne-like shell scripts: bash bash2 dash ksh ksh93 sh return require('vim.filetype.detect').sh(path, contents, first_line) elseif matchregex(name, [[^csh\>]]) then return require('vim.filetype.detect').shell(path, contents, vim.g.filetype_csh or 'csh') diff --git a/runtime/lua/vim/fs.lua b/runtime/lua/vim/fs.lua index ce845eda15..a0d2c4c339 100644 --- a/runtime/lua/vim/fs.lua +++ b/runtime/lua/vim/fs.lua @@ -1,9 +1,11 @@ local M = {} +local iswin = vim.loop.os_uname().sysname == 'Windows_NT' + --- Iterate over all the parents of the given file or directory. --- --- Example: ---- <pre> +--- <pre>lua --- local root_dir --- for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do --- if vim.fn.isdirectory(dir .. "/.git") == 1 then @@ -40,7 +42,19 @@ function M.dirname(file) if file == nil then return nil end - return vim.fn.fnamemodify(file, ':h') + vim.validate({ file = { file, 's' } }) + if iswin and file:match('^%w:[\\/]?$') then + return (file:gsub('\\', '/')) + elseif not file:match('[\\/]') then + return '.' + elseif file == '/' or file:match('^/[^/]+$') then + return '/' + end + local dir = file:match('[/\\]$') and file:sub(1, #file - 1) or file:match('^([/\\]?.+)[/\\]') + if iswin and dir:match('^%w:$') then + return dir .. '/' + end + return (dir:gsub('\\', '/')) end --- Return the basename of the given file or directory @@ -48,21 +62,75 @@ end ---@param file (string) File or directory ---@return (string) Basename of {file} function M.basename(file) - return vim.fn.fnamemodify(file, ':t') + if file == nil then + return nil + end + vim.validate({ file = { file, 's' } }) + if iswin and file:match('^%w:[\\/]?$') then + return '' + end + return file:match('[/\\]$') and '' or (file:match('[^\\/]*$'):gsub('\\', '/')) +end + +---@private +local function join_paths(...) + return (table.concat({ ... }, '/'):gsub('//+', '/')) end --- Return an iterator over the files and directories located in {path} --- ---@param path (string) An absolute or relative path to the directory to iterate --- over. The path is first normalized |vim.fs.normalize()|. +--- @param opts table|nil Optional keyword arguments: +--- - depth: integer|nil How deep the traverse (default 1) +--- - skip: (fun(dir_name: string): boolean)|nil Predicate +--- to control traversal. Return false to stop searching the current directory. +--- Only useful when depth > 1 +--- ---@return Iterator over files and directories in {path}. Each iteration yields --- two values: name and type. Each "name" is the basename of the file or --- directory relative to {path}. Type is one of "file" or "directory". -function M.dir(path) - return function(fs) - return vim.loop.fs_scandir_next(fs) - end, - vim.loop.fs_scandir(M.normalize(path)) +function M.dir(path, opts) + opts = opts or {} + + vim.validate({ + path = { path, { 'string' } }, + depth = { opts.depth, { 'number' }, true }, + skip = { opts.skip, { 'function' }, true }, + }) + + if not opts.depth or opts.depth == 1 then + return function(fs) + return vim.loop.fs_scandir_next(fs) + end, + vim.loop.fs_scandir(M.normalize(path)) + end + + --- @async + return coroutine.wrap(function() + local dirs = { { path, 1 } } + while #dirs > 0 do + local dir0, level = unpack(table.remove(dirs, 1)) + local dir = level == 1 and dir0 or join_paths(path, dir0) + local fs = vim.loop.fs_scandir(M.normalize(dir)) + while fs do + local name, t = vim.loop.fs_scandir_next(fs) + if not name then + break + end + local f = level == 1 and name or join_paths(dir0, name) + coroutine.yield(f, t) + if + opts.depth + and level < opts.depth + and t == 'directory' + and (not opts.skip or opts.skip(f) ~= false) + then + dirs[#dirs + 1] = { f, level + 1 } + end + end + end + end) end --- Find files or directories in the given path. @@ -73,14 +141,18 @@ end --- searches are recursive and may search through many directories! If {stop} --- is non-nil, then the search stops when the directory given in {stop} is --- reached. The search terminates when {limit} (default 1) matches are found. ---- The search can be narrowed to find only files or or only directories by +--- The search can be narrowed to find only files 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. +--- The function is called per file and directory within the +--- traversed directories to test if they match {names}. +--- ---@param opts (table) Optional keyword arguments: --- - path (string): Path to begin searching from. If ---- omitted, the current working directory is used. +--- omitted, the |current-directory| is used. --- - upward (boolean, default false): If true, search --- upward through parent directories. Otherwise, --- search through child directories @@ -89,16 +161,16 @@ end --- reached. The directory itself is not searched. --- - type (string): Find only files ("file") or --- directories ("directory"). If omitted, both ---- files and directories that match {name} are +--- files and directories that match {names} are --- included. --- - limit (number, default 1): Stop the search after --- finding this many matches. Use `math.huge` to --- place no limit on the number of matches. ----@return (table) The paths of all matching files or directories +---@return (table) Normalized paths |vim.fs.normalize()| of all matching files or directories 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 +195,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, join_paths(p, name)) + end end + return t end + else + test = function(p) + local t = {} + for _, name in ipairs(names) do + local f = join_paths(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 +247,25 @@ function M.find(names, opts) break end - 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 + for other, type_ in M.dir(dir) do + local f = join_paths(dir, other) + 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 @@ -187,23 +280,29 @@ end --- backslash (\\) characters are converted to forward slashes (/). Environment --- variables are also expanded. --- ---- Example: ---- <pre> ---- vim.fs.normalize('C:\\Users\\jdoe') ---- => 'C:/Users/jdoe' +--- Examples: +--- <pre>lua +--- vim.fs.normalize('C:\\\\Users\\\\jdoe') +--- --> 'C:/Users/jdoe' --- ---- vim.fs.normalize('~/src/neovim') ---- => '/home/jdoe/src/neovim' +--- vim.fs.normalize('~/src/neovim') +--- --> '/home/jdoe/src/neovim' --- ---- vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') ---- => '/Users/jdoe/.config/nvim/init.vim' +--- vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') +--- --> '/Users/jdoe/.config/nvim/init.vim' --- </pre> --- ---@param path (string) Path to normalize ---@return (string) Normalized path function M.normalize(path) vim.validate({ path = { path, 's' } }) - return (path:gsub('^~/', vim.env.HOME .. '/'):gsub('%$([%w_]+)', vim.env):gsub('\\', '/')) + return ( + path + :gsub('^~$', vim.loop.os_homedir()) + :gsub('^~/', vim.loop.os_homedir() .. '/') + :gsub('%$([%w_]+)', vim.loop.os_getenv) + :gsub('\\', '/') + ) end return M diff --git a/runtime/lua/vim/health.lua b/runtime/lua/vim/health.lua index b875da0abc..044880e076 100644 --- a/runtime/lua/vim/health.lua +++ b/runtime/lua/vim/health.lua @@ -23,7 +23,20 @@ end local path2name = function(path) if path:match('%.lua$') then -- Lua: transform "../lua/vim/lsp/health.lua" into "vim.lsp" - return path:gsub('.-lua[%\\%/]', '', 1):gsub('[%\\%/]', '.'):gsub('%.health.-$', '') + + -- Get full path, make sure all slashes are '/' + path = vim.fs.normalize(path) + + -- Remove everything up to the last /lua/ folder + path = path:gsub('^.*/lua/', '') + + -- Remove the filename (health.lua) + path = vim.fn.fnamemodify(path, ':h') + + -- Change slashes to dots + path = path:gsub('/', '.') + + return path else -- Vim: transform "../autoload/health/provider.vim" into "provider" return vim.fn.fnamemodify(path, ':t:r') diff --git a/runtime/lua/vim/highlight.lua b/runtime/lua/vim/highlight.lua index ddd504a0e0..20ad48dd27 100644 --- a/runtime/lua/vim/highlight.lua +++ b/runtime/lua/vim/highlight.lua @@ -5,6 +5,7 @@ local M = {} M.priorities = { syntax = 50, treesitter = 100, + semantic_tokens = 125, diagnostics = 150, user = 200, } @@ -41,7 +42,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..ef1c66ea20 100644 --- a/runtime/lua/vim/keymap.lua +++ b/runtime/lua/vim/keymap.lua @@ -2,7 +2,7 @@ local keymap = {} --- Add a new |mapping|. --- Examples: ---- <pre> +--- <pre>lua --- -- Can add mapping to Lua functions --- vim.keymap.set('n', 'lhs', function() print("real lua function") end) --- @@ -21,13 +21,13 @@ local keymap = {} --- </pre> --- --- Note that in a mapping like: ---- <pre> +--- <pre>lua --- vim.keymap.set('n', 'asdf', require('jkl').my_fun) --- </pre> --- --- the ``require('jkl')`` gets evaluated during this call in order to access the function. --- If you want to avoid this cost at startup you can wrap it in a function, for example: ---- <pre> +--- <pre>lua --- vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end) --- </pre> --- @@ -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 @@ -94,14 +93,14 @@ end --- Remove an existing mapping. --- Examples: ---- <pre> +--- <pre>lua --- vim.keymap.del('n', 'lhs') --- --- 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..c5392ac154 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -4,8 +4,8 @@ local lsp_rpc = require('vim.lsp.rpc') local protocol = require('vim.lsp.protocol') local util = require('vim.lsp.util') local sync = require('vim.lsp.sync') +local semantic_tokens = require('vim.lsp.semantic_tokens') -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, @@ -26,6 +26,7 @@ local lsp = { buf = require('vim.lsp.buf'), diagnostic = require('vim.lsp.diagnostic'), codelens = require('vim.lsp.codelens'), + semantic_tokens = semantic_tokens, util = util, -- Allow raw RPC access. @@ -57,6 +58,8 @@ lsp._request_name_to_capability = { ['textDocument/formatting'] = { 'documentFormattingProvider' }, ['textDocument/completion'] = { 'completionProvider' }, ['textDocument/documentHighlight'] = { 'documentHighlightProvider' }, + ['textDocument/semanticTokens/full'] = { 'semanticTokensProvider' }, + ['textDocument/semanticTokens/full/delta'] = { 'semanticTokensProvider' }, } -- TODO improve handling of scratch buffers with LSP attached. @@ -64,7 +67,7 @@ lsp._request_name_to_capability = { ---@private --- Concatenates and writes a list of strings to the Vim error buffer. --- ----@param {...} (List of strings) List to write to the buffer +---@param {...} table[] List to write to the buffer local function err_message(...) nvim_err_writeln(table.concat(vim.tbl_flatten({ ... }))) nvim_command('redraw') @@ -73,7 +76,7 @@ end ---@private --- Returns the buffer number for the given {bufnr}. --- ----@param bufnr (number) Buffer number to resolve. Defaults to the current +---@param bufnr (number|nil) Buffer number to resolve. Defaults to the current ---buffer if not given. ---@returns bufnr (number) Number of requested buffer local function resolve_bufnr(bufnr) @@ -241,9 +244,9 @@ end ---@private --- Augments a validator function with support for optional (nil) values. --- ----@param fn (function(v)) The original validator function; should return a +---@param fn (fun(v)) The original validator function; should return a ---bool. ----@returns (function(v)) The augmented function. Also returns true if {v} is +---@returns (fun(v)) The augmented function. Also returns true if {v} is ---`nil`. local function optional_validator(fn) return function(v) @@ -289,7 +292,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) @@ -809,8 +817,7 @@ end --- Attaches the current buffer to the client. --- --- Example: ---- ---- <pre> +--- <pre>lua --- vim.lsp.start({ --- name = 'my-server-name', --- cmd = {'name-of-language-server-executable'}, @@ -818,25 +825,18 @@ end --- }) --- </pre> --- ---- See |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. +--- See |vim.lsp.start_client()| for all available options. The most important are: --- ---- `cmd` the command as list - used to start the language server. ---- The command must be present in the `$PATH` environment variable or an ---- absolute path to the executable. Shell 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 `pyproject.toml` or `setup.py` ---- file is found. ---- ---- `workspace_folders` a list of { uri:string, name: string } tables. ---- The project root folders used by the language server. ---- If `nil` the property is derived from the `root_dir` for convenience. +--- - `name` arbitrary name for the LSP client. Should be unique per language server. +--- - `cmd` command (in list form) used to start the language server. Must be absolute, or found on +--- `$PATH`. Shell 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 `pyproject.toml` or `setup.py` file is found. +--- - `workspace_folders` list of `{ uri:string, name: string }` tables specifying the project root +--- folders used by the language server. If `nil` the property is derived from `root_dir` for +--- convenience. --- --- Language servers use this information to discover metadata like the --- dependencies of your project and they tend to index the contents within the @@ -844,26 +844,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 @@ -888,110 +897,114 @@ end -- --- Starts and initializes a client with the given configuration. --- ---- Parameter `cmd` is required. ---- ---- 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_cwd: (string, default=|getcwd()|) Directory to launch ---- the `cmd` process. Not related to `root_dir`. ---- ----@param 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: ---- <pre> ---- { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; } ---- </pre> ---- ----@param 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. ---- ----@param 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. ---- ----@param 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 ---- its result. ---- - Note: To send an empty dictionary use ---- `{[vim.type_idx]=vim.types.dictionary}`, else it will be encoded as an ---- array. +--- Field `cmd` in {config} is required. +--- +---@param config (table) Configuration for the server: +--- - 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 +--- 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: +--- <pre> +--- { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; } +--- </pre> +--- +--- - 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 +--- 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 by +--- |vim.lsp.protocol.make_client_capabilities()|, passed to the language +--- server on initialization. Hint: use make_client_capabilities() and modify +--- its result. +--- - 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 |lsp-handler| +--- +--- - 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 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 `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 string. +--- Defaults to the filetype. +--- +--- - 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 +--- 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. +--- Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name. +--- +--- - 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 after LSP +--- "initialize", where `result` is a table of `capabilities` and anything else +--- the server may send. For example, clangd sends +--- `initialize_result.offsetEncoding` if `capabilities.offsetEncoding` was +--- sent to it. You can only modify the `client.offset_encoding` here before +--- any notifications are sent. Most language servers expect to be sent client specified settings after +--- initialization. Neovim does not 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 client +--- exit. +--- - code: exit code of the process +--- - signal: number describing the signal used to terminate (if any) +--- - client_id: client handle --- ----@param handlers Map of language server method names to |lsp-handler| +--- - on_attach: Callback (client, bufnr) invoked when client +--- attaches to a buffer. --- ----@param settings Map with language server specific settings. These are ---- returned to the language server if requested via `workspace/configuration`. ---- Keys are case-sensitive. +--- - trace: ("off" | "messages" | "verbose" | nil) passed directly to the language +--- server in the initialize request. Invalid/empty values will default to "off" --- ----@param 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. +--- - 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 +--- - debounce_text_changes (number, default 150): Debounce didChange +--- 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. --- ----@param init_options Values to pass in the initialization request ---- as `initializationOptions`. See `initialize` in the LSP spec. ---- ----@param name (string, default=client-id) Name in log messages. ---- ----@param get_language_id function(bufnr, filetype) -> language ID as string. ---- Defaults to the filetype. ---- ----@param 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. ---- ----@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. ---- Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name. ---- ----@param 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. ---- ----@param 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 ---- `initialize_result.offsetEncoding` if `capabilities.offsetEncoding` was ---- sent to it. You can only modify the `client.offset_encoding` here before ---- any notifications are sent. Most language servers expect to be sent client specified settings after ---- initialization. Neovim does not make this assumption. A ---- `workspace/didChangeConfiguration` notification should be sent ---- to the server during on_init. ---- ----@param 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 ---- ----@param on_attach Callback (client, bufnr) invoked when client ---- attaches to a buffer. ---- ----@param trace: "off" | "messages" | "verbose" | nil passed directly to the language ---- server in the initialize request. Invalid/empty values will default to "off" ----@param 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 ---- - debounce_text_changes (number, default 150): Debounce didChange ---- 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. ---- ----@param root_dir string Directory where the LSP ---- server will base its workspaceFolders, rootUri, and rootPath ---- on initialization. +--- - root_dir: (string) Directory where the LSP +--- server will base its workspaceFolders, rootUri, and rootPath +--- on initialization. --- ---@returns Client id. |vim.lsp.get_client_by_id()| Note: client may not be --- fully initialized. Use `on_init` to do any actions once @@ -1065,7 +1078,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 +1147,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 @@ -1269,8 +1288,6 @@ function lsp.start_client(config) client.initialized = true uninitialized_clients[client_id] = nil client.workspace_folders = workspace_folders - -- TODO(mjlbach): Backwards compatibility, to be removed in 0.7 - client.workspaceFolders = client.workspace_folders -- These are the cleaned up capabilities we use for dynamically deciding -- when to send certain events to clients. @@ -1348,7 +1365,7 @@ function lsp.start_client(config) --- ---@param method (string) LSP method name. ---@param params (table) LSP request params. - ---@param handler (function, optional) Response |lsp-handler| for this method. + ---@param handler (function|nil) Response |lsp-handler| for this method. ---@param bufnr (number) Buffer handle (0 for current). ---@returns ({status}, [request_id]): {status} is a bool indicating ---whether the request was successful. If it is `false`, then it will @@ -1359,8 +1376,10 @@ function lsp.start_client(config) ---@see |vim.lsp.buf_request()| function client.request(method, params, handler, bufnr) if not handler then - handler = resolve_handler(method) - or error(string.format('not found: %q request handler for client %q.', method, client.name)) + handler = assert( + resolve_handler(method), + string.format('not found: %q request handler for client %q.', method, client.name) + ) end -- Ensure pending didChange notifications are sent so that the server doesn't operate on a stale state changetracking.flush(client, bufnr) @@ -1378,7 +1397,7 @@ function lsp.start_client(config) nvim_exec_autocmds('User', { pattern = 'LspRequest', modeline = false }) end) - if success then + if success and request_id then client.requests[request_id] = { type = 'pending', bufnr = bufnr, method = method } nvim_exec_autocmds('User', { pattern = 'LspRequest', modeline = false }) end @@ -1393,8 +1412,8 @@ function lsp.start_client(config) --- ---@param method (string) LSP method name. ---@param params (table) LSP request params. - ---@param timeout_ms (number, optional, default=1000) Maximum time in - ---milliseconds to wait for a result. + ---@param timeout_ms (number|nil) Maximum time in milliseconds to wait for + --- a result. Defaults to 1000 ---@param bufnr (number) Buffer handle (0 for current). ---@returns { err=err, result=result }, a dictionary, where `err` and `result` come from the |lsp-handler|. ---On timeout, cancel or error, returns `(nil, err)` where `err` is a @@ -1417,7 +1436,9 @@ function lsp.start_client(config) end, 10) if not wait_result then - client.cancel_request(request_id) + if request_id then + client.cancel_request(request_id) + end return nil, wait_result_reason[reason] end return request_result @@ -1464,14 +1485,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 +1500,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 +1512,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 @@ -1513,6 +1533,16 @@ function lsp.start_client(config) -- TODO(ashkan) handle errors. pcall(config.on_attach, client, bufnr) end + + -- schedule the initialization of semantic tokens to give the above + -- on_attach and LspAttach callbacks the ability to schedule wrap the + -- opt-out (deleting the semanticTokensProvider from capabilities) + vim.schedule(function() + if vim.tbl_get(client.server_capabilities, 'semanticTokensProvider', 'full') then + semantic_tokens.start(bufnr, client.id) + end + end) + client.attached_buffers[bufnr] = true end @@ -1526,15 +1556,21 @@ end --- Notify all attached clients that a buffer has changed. local text_document_did_change_handler do - text_document_did_change_handler = - function(_, bufnr, changedtick, firstline, lastline, new_lastline) - -- Detach (nvim_buf_attach) via returning True to on_lines if no clients are attached - if tbl_isempty(all_buffer_active_clients[bufnr] or {}) then - return true - end - util.buf_versions[bufnr] = changedtick - changetracking.send_changes(bufnr, firstline, lastline, new_lastline) + text_document_did_change_handler = function( + _, + bufnr, + changedtick, + firstline, + lastline, + new_lastline + ) + -- Detach (nvim_buf_attach) via returning True to on_lines if no clients are attached + if tbl_isempty(all_buffer_active_clients[bufnr] or {}) then + return true end + util.buf_versions[bufnr] = changedtick + changetracking.send_changes(bufnr, firstline, lastline, new_lastline) + end end ---@private @@ -1598,9 +1634,37 @@ function lsp.buf_attach_client(bufnr, client_id) all_buffer_active_clients[bufnr] = buffer_client_ids local uri = vim.uri_from_bufnr(bufnr) - local augroup = ('lsp_c_%d_b_%d_did_save'):format(client_id, bufnr) + local augroup = ('lsp_c_%d_b_%d_save'):format(client_id, bufnr) + local group = api.nvim_create_augroup(augroup, { clear = true }) + api.nvim_create_autocmd('BufWritePre', { + group = group, + buffer = bufnr, + desc = 'vim.lsp: textDocument/willSave', + callback = function(ctx) + for_each_buffer_client(ctx.buf, function(client) + local params = { + textDocument = { + uri = uri, + }, + reason = protocol.TextDocumentSaveReason.Manual, + } + if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'willSave') then + client.notify('textDocument/willSave', params) + end + if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'willSaveWaitUntil') then + local result, err = + client.request_sync('textDocument/willSaveWaitUntil', params, 1000, ctx.buf) + if result and result.result then + util.apply_text_edits(result.result, ctx.buf, client.offset_encoding) + elseif err then + log.error(vim.inspect(err)) + end + end + end) + end, + }) api.nvim_create_autocmd('BufWritePost', { - group = api.nvim_create_augroup(augroup, { clear = true }), + group = group, buffer = bufnr, desc = 'vim.lsp: textDocument/didSave handler', callback = function(ctx) @@ -1627,6 +1691,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 @@ -1737,16 +1802,15 @@ end --- --- You can also use the `stop()` function on a |vim.lsp.client| object. --- To stop all clients: ---- ---- <pre> +--- <pre>lua --- vim.lsp.stop_client(vim.lsp.get_active_clients()) --- </pre> --- --- By default asks the server to shutdown, unless stop was requested --- already for this client, then force-shutdown is attempted. --- ----@param client_id client id or |vim.lsp.client| object, or list thereof ----@param force boolean (optional) shutdown forcefully +---@param client_id number|table id or |vim.lsp.client| object, or list thereof +---@param force boolean|nil shutdown forcefully function lsp.stop_client(client_id, force) local ids = type(client_id) == 'table' and client_id or { client_id } for _, id in ipairs(ids) do @@ -1760,10 +1824,16 @@ function lsp.stop_client(client_id, force) end end +---@class vim.lsp.get_active_clients.filter +---@field id number|nil Match clients by id +---@field bufnr number|nil match clients attached to the given buffer +---@field name string|nil match clients by name + --- Get active clients. --- ----@param filter (table|nil) A table with key-value pairs used to filter the ---- returned clients. The available keys are: +---@param filter vim.lsp.get_active_clients.filter|nil (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 buffer --- - name (string): Only return clients with the given name @@ -1780,7 +1850,8 @@ function lsp.get_active_clients(filter) for client_id in pairs(t) do local client = active_clients[client_id] if - (filter.id == nil or client.id == filter.id) + client + and (filter.id == nil or client.id == filter.id) and (filter.name == nil or client.name == filter.name) then clients[#clients + 1] = client @@ -1911,7 +1982,7 @@ end --- ---@param bufnr (number) Buffer handle, or 0 for current. ---@param method (string) LSP method name ----@param params (optional, table) Parameters to send to the server +---@param params (table|nil) Parameters to send to the server ---@param callback (function) The callback to call when all requests are finished. -- Unlike `buf_request`, this will collect all the responses from each server instead of handling them. -- A map of client_id:request_result will be provided to the callback @@ -1953,9 +2024,9 @@ end --- ---@param bufnr (number) Buffer handle, or 0 for current. ---@param method (string) LSP method name ----@param params (optional, table) Parameters to send to the server ----@param timeout_ms (optional, number, default=1000) Maximum time in ---- milliseconds to wait for a result. +---@param params (table|nil) Parameters to send to the server +---@param timeout_ms (number|nil) Maximum time in milliseconds to wait for a +--- result. Defaults to 1000 --- ---@returns Map of client_id:request_result. On timeout, cancel or error, --- returns `(nil, err)` where `err` is a string describing the failure @@ -1980,9 +2051,9 @@ function lsp.buf_request_sync(bufnr, method, params, timeout_ms) end --- Send a notification to a server ----@param bufnr [number] (optional): The number of the buffer ----@param method [string]: Name of the request method ----@param params [string]: Arguments to send to the server +---@param bufnr (number|nil) The number of the buffer +---@param method (string) Name of the request method +---@param params (any) Arguments to send to the server --- ---@returns true if any client returns true; false otherwise function lsp.buf_notify(bufnr, method, params) @@ -2023,8 +2094,8 @@ end ---@see |complete-items| ---@see |CompleteDone| --- ----@param findstart 0 or 1, decides behavior ----@param base If findstart=0, text to match against +---@param findstart number 0 or 1, decides behavior +---@param base number findstart=0, text to match against --- ---@returns (number) Decided by {findstart}: --- - findstart=0: column where the completion starts, or -2 or -3 @@ -2153,8 +2224,8 @@ end --- Otherwise, uses "workspace/symbol". If no results are returned from --- any LSP servers, falls back to using built-in tags. --- ----@param pattern Pattern used to find a workspace symbol ----@param flags See |tag-function| +---@param pattern string Pattern used to find a workspace symbol +---@param flags string See |tag-function| --- ---@returns A list of matching tags function lsp.tagfunc(...) @@ -2163,7 +2234,7 @@ end ---Checks whether a client is stopped. --- ----@param client_id (Number) +---@param client_id (number) ---@returns true if client is stopped, false otherwise. function lsp.client_is_stopped(client_id) return active_clients[client_id] == nil @@ -2172,7 +2243,7 @@ end --- Gets a map of client_id:client pairs for the given buffer, where each value --- is a |vim.lsp.client| object. --- ----@param bufnr (optional, number): Buffer handle, or 0 for current +---@param bufnr (number|nil): Buffer handle, or 0 for current ---@returns (table) Table of (client_id, client) pairs ---@deprecated Use |vim.lsp.get_active_clients()| instead. function lsp.buf_get_clients(bufnr) @@ -2201,7 +2272,7 @@ lsp.log_levels = log.levels --- ---@see |vim.lsp.log_levels| --- ----@param level [number|string] the case insensitive level name or number +---@param level (number|string) the case insensitive level name or number function lsp.set_log_level(level) if type(level) == 'string' or type(level) == 'number' then log.set_level(level) @@ -2222,7 +2293,7 @@ end ---@param 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: ---- <pre> +--- <pre>lua --- vim.lsp.for_each_buffer_client(0, function(client, client_id, bufnr) --- print(vim.inspect(client)) --- end) diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 6a070928d9..6ac885c78f 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 @@ -168,11 +162,11 @@ end --- Predicate used to filter clients. Receives a client as argument and must return a --- boolean. Clients matching the predicate are included. Example: --- ---- <pre> ---- -- Never request typescript-language-server for formatting ---- vim.lsp.buf.format { ---- filter = function(client) return client.name ~= "tsserver" end ---- } +--- <pre>lua +--- -- Never request typescript-language-server for formatting +--- vim.lsp.buf.format { +--- filter = function(client) return client.name ~= "tsserver" end +--- } --- </pre> --- --- - async boolean|nil @@ -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() @@ -198,24 +197,40 @@ function M.format(options) clients = vim.tbl_filter(options.filter, clients) 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 + local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting' + clients = vim.tbl_filter(function(client) - return client.supports_method('textDocument/formatting') + return client.supports_method(method) end, clients) if #clients == 0 then vim.notify('[LSP] Format request failed, no matching language servers.') 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 + 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 @@ -500,7 +383,7 @@ end --- Lists all the references to the symbol under the cursor in the quickfix window. --- ----@param context (table) Context for the request +---@param context (table|nil) Context for the request ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references ---@param options table|nil additional options --- - on_list: (function) handler for list results. See |lsp-on-list-handler| @@ -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 @@ -581,7 +464,7 @@ end --- function M.list_workspace_folders() local workspace_folders = {} - for _, client in pairs(vim.lsp.buf_get_clients()) do + for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do for _, folder in pairs(client.workspace_folders or {}) do table.insert(workspace_folders, folder.name) end @@ -604,9 +487,9 @@ function M.add_workspace_folder(workspace_folder) end local params = util.make_workspace_params( { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } }, - { {} } + {} ) - for _, client in pairs(vim.lsp.buf_get_clients()) do + for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do local found = false for _, folder in pairs(client.workspace_folders or {}) do if folder.name == workspace_folder then @@ -639,7 +522,7 @@ function M.remove_workspace_folder(workspace_folder) { {} }, { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } } ) - for _, client in pairs(vim.lsp.buf_get_clients()) do + for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do for idx, folder in pairs(client.workspace_folders) do if folder.name == workspace_folder then vim.lsp.buf_notify(0, 'workspace/didChangeWorkspaceFolders', params) @@ -672,18 +555,17 @@ end --- Send request to the server to resolve document highlights for the current --- text document position. This request can be triggered by a key mapping or --- by events such as `CursorHold`, e.g.: ---- ---- <pre> ---- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() ---- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() ---- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() +--- <pre>vim +--- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() +--- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() +--- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() --- </pre> --- --- 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) @@ -851,6 +733,7 @@ end --- List of LSP `CodeActionKind`s used to filter the code actions. --- Most language servers support values like `refactor` --- or `quickfix`. +--- - triggerKind (number|nil): The reason why code actions were requested. --- - filter: (function|nil) --- Predicate taking an `CodeAction` and returning a boolean. --- - apply: (boolean|nil) @@ -864,6 +747,7 @@ end --- using mark-like indexing. See |api-indexing| --- ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction +---@see vim.lsp.protocol.constants.CodeActionTriggerKind function M.code_action(options) validate({ options = { options, 't', true } }) options = options or {} @@ -873,6 +757,9 @@ function M.code_action(options) options = { options = options } end local context = options.context or {} + if not context.triggerKind then + context.triggerKind = vim.lsp.protocol.CodeActionTriggerKind.Invoked + end if not context.diagnostics then local bufnr = api.nvim_get_current_buf() context.diagnostics = vim.lsp.diagnostic.get_line_diagnostics(bufnr) @@ -885,23 +772,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 +781,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/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 4fa02c8db2..17489ed84d 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -108,13 +108,36 @@ function M.run() end end +---@private +local function resolve_bufnr(bufnr) + return bufnr == 0 and api.nvim_get_current_buf() or bufnr +end + +--- Clear the lenses +--- +---@param client_id number|nil filter by client_id. All clients if nil +---@param bufnr number|nil filter by buffer. All buffers if nil +function M.clear(client_id, bufnr) + local buffers = bufnr and { resolve_bufnr(bufnr) } or vim.tbl_keys(lens_cache_by_buf) + for _, iter_bufnr in pairs(buffers) do + local client_ids = client_id and { client_id } or vim.tbl_keys(namespaces) + for _, iter_client_id in pairs(client_ids) do + local ns = namespaces[iter_client_id] + lens_cache_by_buf[iter_bufnr][iter_client_id] = {} + api.nvim_buf_clear_namespace(iter_bufnr, ns, 0, -1) + end + end +end + --- Display the lenses using virtual text --- ---@param lenses table of lenses to display (`CodeLens[] | null`) ---@param bufnr number ---@param client_id number function M.display(lenses, bufnr, client_id) + local ns = namespaces[client_id] if not lenses or not next(lenses) then + api.nvim_buf_clear_namespace(bufnr, ns, 0, -1) return end local lenses_by_lnum = {} @@ -126,7 +149,6 @@ function M.display(lenses, bufnr, client_id) end table.insert(line_lenses, lens) end - local ns = namespaces[client_id] local num_lines = api.nvim_buf_line_count(bufnr) for i = 0, num_lines do local line_lenses = lenses_by_lnum[i] or {} @@ -241,7 +263,8 @@ end --- --- It is recommended to trigger this using an autocmd or via keymap. --- ---- <pre> +--- Example: +--- <pre>vim --- autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() --- </pre> --- diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 1f9d084e2b..5e2bf75f1b 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -150,7 +150,7 @@ end --- --- See |vim.diagnostic.config()| for configuration options. Handler-specific --- configuration can be set using |vim.lsp.with()|: ---- <pre> +--- <pre>lua --- vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( --- vim.lsp.diagnostic.on_publish_diagnostics, { --- -- Enable underline, use default values diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 624436bc9b..5096100a60 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 = {} @@ -82,22 +81,38 @@ M['window/workDoneProgress/create'] = function(_, result, ctx) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessageRequest +---@param result lsp.ShowMessageRequestParams M['window/showMessageRequest'] = function(_, result) - local actions = result.actions - print(result.message) - local option_strings = { result.message, '\nRequest Actions:' } - for i, action in ipairs(actions) do - local title = action.title:gsub('\r\n', '\\r\\n') - title = title:gsub('\n', '\\n') - table.insert(option_strings, string.format('%d. %s', i, title)) - end - - -- window/showMessageRequest can return either MessageActionItem[] or null. - local choice = vim.fn.inputlist(option_strings) - if choice < 1 or choice > #actions then - return vim.NIL + local actions = result.actions or {} + local co, is_main = coroutine.running() + if co and not is_main then + local opts = { + prompt = result.message .. ': ', + format_item = function(action) + return (action.title:gsub('\r\n', '\\r\\n')):gsub('\n', '\\n') + end, + } + vim.ui.select(actions, opts, function(choice) + -- schedule to ensure resume doesn't happen _before_ yield with + -- default synchronous vim.ui.select + vim.schedule(function() + coroutine.resume(co, choice or vim.NIL) + end) + end) + return coroutine.yield() else - return actions[choice] + local option_strings = { result.message, '\nRequest Actions:' } + for i, action in ipairs(actions) do + local title = action.title:gsub('\r\n', '\\r\\n') + title = title:gsub('\n', '\\n') + table.insert(option_strings, string.format('%d. %s', i, title)) + end + local choice = vim.fn.inputlist(option_strings) + if choice < 1 or choice > #actions then + return vim.NIL + else + return actions[choice] + end end end @@ -116,9 +131,10 @@ end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit M['workspace/applyEdit'] = function(_, workspace_edit, ctx) - if not workspace_edit then - return - end + assert( + workspace_edit, + 'workspace/applyEdit must be called with `ApplyWorkspaceEditParams`. Server is violating the specification' + ) -- TODO(ashkan) Do something more with label? local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) @@ -298,13 +314,15 @@ M['textDocument/completion'] = function(_, result, _, _) end --- |lsp-handler| for the method "textDocument/hover" ---- <pre> ---- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( ---- vim.lsp.handlers.hover, { ---- -- Use a sharp border with `FloatBorder` highlights ---- border = "single" ---- } ---- ) +--- <pre>lua +--- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( +--- vim.lsp.handlers.hover, { +--- -- Use a sharp border with `FloatBorder` highlights +--- border = "single", +--- -- add the title in hover float window +--- title = "hover" +--- } +--- ) --- </pre> ---@param config table Configuration table. --- - border: (default=nil) @@ -313,8 +331,14 @@ end function M.hover(_, result, ctx, config) config = config or {} config.focus_id = ctx.method + if api.nvim_get_current_buf() ~= ctx.bufnr then + -- Ignore result since buffer changed. This happens for slow language servers. + return + end if not (result and result.contents) then - vim.notify('No information available') + if config.silent ~= true then + vim.notify('No information available') + end return end local markdown_lines = util.convert_input_to_markdown_lines(result.contents) @@ -378,21 +402,25 @@ M['textDocument/implementation'] = location_handler --- |lsp-handler| for the method "textDocument/signatureHelp". --- The active parameter is highlighted with |hl-LspSignatureActiveParameter|. ---- <pre> ---- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( ---- vim.lsp.handlers.signature_help, { ---- -- Use a sharp border with `FloatBorder` highlights ---- border = "single" ---- } ---- ) +--- <pre>lua +--- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( +--- vim.lsp.handlers.signature_help, { +--- -- Use a sharp border with `FloatBorder` highlights +--- border = "single" +--- } +--- ) --- </pre> ---@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 + if api.nvim_get_current_buf() ~= ctx.bufnr then + -- Ignore result since buffer changed. This happens for slow language servers. + return + end -- When use `autocmd CompleteDone <silent><buffer> lua vim.lsp.buf.signature_help()` to call signatureHelp handler -- If the completion item doesn't have signatures It will make noise. Change to use `print` that can use `<silent>` to ignore if not (result and result.signatures and result.signatures[1]) then @@ -512,6 +540,55 @@ 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', '""', uri } + elseif vim.fn.has('macunix') == 1 then + cmd = { 'open', uri } + else + cmd = { 'xdg-open', uri } + end + + local ret = vim.fn.system(cmd) + if vim.v.shell_error ~= 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, { + reuse_win = true, + focus = 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/health.lua b/runtime/lua/vim/lsp/health.lua index ba730e3d6d..987707e661 100644 --- a/runtime/lua/vim/lsp/health.lua +++ b/runtime/lua/vim/lsp/health.lua @@ -2,8 +2,8 @@ local M = {} --- Performs a healthcheck for LSP function M.check() - local report_info = vim.fn['health#report_info'] - local report_warn = vim.fn['health#report_warn'] + local report_info = vim.health.report_info + local report_warn = vim.health.report_warn local log = require('vim.lsp.log') local current_log_level = log.get_level() @@ -27,6 +27,18 @@ function M.check() local report_fn = (log_size / 1000000 > 100 and report_warn or report_info) report_fn(string.format('Log size: %d KB', log_size / 1000)) + + local clients = vim.lsp.get_active_clients() + vim.health.report_start('vim.lsp: Active Clients') + if next(clients) then + for _, client in pairs(clients) do + report_info( + string.format('%s (id=%s, root_dir=%s)', client.name, client.id, client.config.root_dir) + ) + end + else + report_info('No active clients') + end end return M diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua index 6c6ba0f206..d1a78572aa 100644 --- a/runtime/lua/vim/lsp/log.lua +++ b/runtime/lua/vim/lsp/log.lua @@ -20,6 +20,17 @@ local format_func = function(arg) end do + ---@private + local function notify(msg, level) + if vim.in_fast_event() then + vim.schedule(function() + vim.notify(msg, level) + end) + else + vim.notify(msg, level) + end + end + local path_sep = vim.loop.os_uname().version:match('Windows') and '\\' or '/' ---@private local function path_join(...) @@ -53,7 +64,7 @@ do logfile, openerr = io.open(logfilename, 'a+') if not logfile then local err_msg = string.format('Failed to open LSP client log file: %s', openerr) - vim.notify(err_msg, vim.log.levels.ERROR) + notify(err_msg, vim.log.levels.ERROR) return false end @@ -64,7 +75,7 @@ do log_info.size / (1000 * 1000), logfilename ) - vim.notify(warn_msg) + notify(warn_msg) end -- Start message for logging @@ -130,7 +141,7 @@ end vim.tbl_add_reverse_lookup(log.levels) --- Sets the current log level. ----@param level (string or number) One of `vim.lsp.log.levels` +---@param level (string|number) One of `vim.lsp.log.levels` function log.set_level(level) if type(level) == 'string' then current_log_level = diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 27da60b4ae..12345b6c8c 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -20,6 +20,14 @@ function transform_schema_to_table() end --]=] +---@class lsp.ShowMessageRequestParams +---@field type lsp.MessageType +---@field message string +---@field actions nil|lsp.MessageActionItem[] + +---@class lsp.MessageActionItem +---@field title string + local constants = { DiagnosticSeverity = { -- Reports an error. @@ -39,6 +47,7 @@ local constants = { Deprecated = 2, }, + ---@enum lsp.MessageType MessageType = { -- An error message. Error = 1, @@ -142,6 +151,7 @@ local constants = { }, -- Represents reasons why a text document is saved. + ---@enum lsp.TextDocumentSaveReason TextDocumentSaveReason = { -- Manually triggered, e.g. by the user pressing save, by starting debugging, -- or by an API call. @@ -294,6 +304,17 @@ local constants = { -- Base kind for an organize imports source action SourceOrganizeImports = 'source.organizeImports', }, + -- The reason why code actions were requested. + ---@enum lsp.CodeActionTriggerKind + CodeActionTriggerKind = { + -- Code actions were explicitly requested by the user or by an extension. + Invoked = 1, + -- Code actions were requested automatically. + -- + -- This typically happens when current selection in a file changes, but can + -- also be triggered when file content changes. + Automatic = 2, + }, } for k, v in pairs(constants) do @@ -619,14 +640,63 @@ export interface WorkspaceClientCapabilities { function protocol.make_client_capabilities() return { textDocument = { - synchronization = { + semanticTokens = { dynamicRegistration = false, + tokenTypes = { + 'namespace', + 'type', + 'class', + 'enum', + 'interface', + 'struct', + 'typeParameter', + 'parameter', + 'variable', + 'property', + 'enumMember', + 'event', + 'function', + 'method', + 'macro', + 'keyword', + 'modifier', + 'comment', + 'string', + 'number', + 'regexp', + 'operator', + 'decorator', + }, + tokenModifiers = { + 'declaration', + 'definition', + 'readonly', + 'static', + 'deprecated', + 'abstract', + 'async', + 'modification', + 'documentation', + 'defaultLibrary', + }, + formats = { 'relative' }, + requests = { + -- TODO(jdrouhard): Add support for this + range = false, + full = { delta = true }, + }, - -- TODO(ashkan) Send textDocument/willSave before saving (BufWritePre) - willSave = false, + overlappingTokenSupport = true, + -- TODO(jdrouhard): Add support for this + multilineTokenSupport = false, + serverCancelSupport = false, + augmentsSyntaxTokens = true, + }, + synchronization = { + dynamicRegistration = false, - -- TODO(ashkan) Implement textDocument/willSaveWaitUntil - willSaveWaitUntil = false, + willSave = true, + willSaveWaitUntil = true, -- Send textDocument/didSave after saving (BufWritePost) didSave = true, @@ -637,7 +707,7 @@ function protocol.make_client_capabilities() codeActionLiteralSupport = { codeActionKind = { valueSet = (function() - local res = vim.tbl_values(protocol.CodeActionKind) + local res = vim.tbl_values(constants.CodeActionKind) table.sort(res) return res end)(), @@ -742,6 +812,9 @@ function protocol.make_client_capabilities() end)(), }, }, + callHierarchy = { + dynamicRegistration = false, + }, }, workspace = { symbol = { @@ -765,9 +838,9 @@ function protocol.make_client_capabilities() workspaceEdit = { resourceOperations = { 'rename', 'create', 'delete' }, }, - }, - callHierarchy = { - dynamicRegistration = false, + semanticTokens = { + refreshSupport = true, + }, }, experimental = nil, window = { @@ -778,7 +851,7 @@ function protocol.make_client_capabilities() }, }, showDocument = { - support = false, + support = true, }, }, } @@ -861,8 +934,8 @@ function protocol._resolve_capabilities_compat(server_capabilities) text_document_sync_properties = { text_document_open_close = if_nil(textDocumentSync.openClose, false), text_document_did_change = if_nil(textDocumentSync.change, TextDocumentSyncKind.None), - text_document_will_save = if_nil(textDocumentSync.willSave, false), - text_document_will_save_wait_until = if_nil(textDocumentSync.willSaveWaitUntil, false), + text_document_will_save = if_nil(textDocumentSync.willSave, true), + text_document_will_save_wait_until = if_nil(textDocumentSync.willSaveWaitUntil, true), text_document_save = if_nil(textDocumentSync.save, false), text_document_save_include_text = if_nil( type(textDocumentSync.save) == 'table' and textDocumentSync.save.includeText, diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 0926912066..f1492601ff 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,247 +240,162 @@ function default_dispatchers.on_error(code, err) local _ = log.error() and log.error('client_error:', client_errors[code], err) 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. ---- ----@param cmd (string) Command to start the LSP server. ----@param cmd_args (table) List of additional string arguments to pass to {cmd}. ----@param dispatchers table|nil Dispatchers for LSP message types. Valid ----dispatcher names are: ---- - `"notification"` ---- - `"server_request"` ---- - `"on_error"` ---- - `"on_exit"` ----@param extra_spawn_params table|nil Additional context for the LSP ---- server process. May contain: ---- - {cwd} (string) Working directory for the LSP server process ---- - {env} (table) Additional environment variables for LSP server process ----@returns Client RPC object. ---- ----@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|. -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 }) - validate({ - cmd = { cmd, 's' }, - cmd_args = { cmd_args, 't' }, - dispatchers = { dispatchers, 't', true }, - }) - - 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 +---@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 - else - dispatchers = default_dispatchers - end - - 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 + if not chunk then + if on_no_chunk then + on_no_chunk() end + return 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.' + + while true do + local headers, body = parse_chunk(chunk) + if headers then + handle_body(body) + chunk = '' else - msg = msg .. string.format(' with error message: %s', pid) + break 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 +---@class RpcClient +---@field message_index number +---@field message_callbacks table +---@field notify_reply_callbacks table +---@field transport table +---@field dispatchers table - -- 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, - }) - end +---@class RpcClient +local Client = {} - ---@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, - }) +---@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 - -- 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 +---@private +--- Sends a notification to the LSP server. +---@param method (string) The invoked LSP method +---@param params (any): 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 - stderr:read_start(function(_, chunk) - if chunk then - local _ = log.error() and log.error('rpc', cmd, 'stderr', chunk) - 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 - 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, ... - end - ---@private - local function try_call(errkind, fn, ...) - return pcall_handler(errkind, pcall(fn, ...)) +---@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 - -- 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:try_call(errkind, fn, ...) + return self:pcall_handler(errkind, pcall(fn, ...)) +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) +-- 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. - 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() +---@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() + coroutine.wrap(function() local status, result - status, result, err = try_call( + status, result, err = self:try_call( client_errors.SERVER_REQUEST_HANDLER_ERROR, - dispatchers.server_request, + self.dispatchers.server_request, decoded.method, decoded.params ) @@ -491,8 +405,7 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) { 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 + 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', @@ -516,120 +429,328 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) 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 + self:send_response(decoded.id, err, result) + end)() + 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 - -- 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 + local message_callbacks = self.message_callbacks - 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 + -- 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' }, + 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, }) - 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 + self:try_call( + client_errors.SERVER_RESULT_CALLBACK_ERROR, + callback, + decoded.error, + decoded.result ) else - -- Invalid server message - on_error(client_errors.INVALID_SERVER_MESSAGE, decoded) + 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 - 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 = '' +---@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 - break + dispatchers[dispatch_name] = default_dispatch end 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 { - pid = pid, - handle = handle, - request = request, - notify = notify, + 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 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}. +---@param dispatchers table|nil Dispatchers for LSP message types. Valid +---dispatcher names are: +--- - `"notification"` +--- - `"server_request"` +--- - `"on_error"` +--- - `"on_exit"` +---@param extra_spawn_params table|nil Additional context for the LSP +--- server process. May contain: +--- - {cwd} (string) Working directory for the LSP server process +--- - {env} (table) Additional environment variables for LSP server process +---@returns Client RPC object. +--- +---@returns Methods: +--- - `notify()` |vim.lsp.rpc.notify()| +--- - `request()` |vim.lsp.rpc.request()| +--- - `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 }) + validate({ + cmd = { cmd, 's' }, + cmd_args = { cmd_args, 't' }, + dispatchers = { dispatchers, 't', true }, + }) + + if extra_spawn_params and extra_spawn_params.cwd then + assert(is_dir(extra_spawn_params.cwd), 'cwd must be a directory') + end + + dispatchers = merge_dispatchers(dispatchers) + local stdin = uv.new_pipe(false) + local stdout = uv.new_pipe(false) + local stderr = uv.new_pipe(false) + local handle, 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 + end, + }) + + ---@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() + 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) + end + vim.notify(msg, vim.log.levels.WARN) + return + end + + stderr:read_start(function(_, chunk) + if chunk then + local _ = log.error() and log.error('rpc', cmd, 'stderr', chunk) + end + end) + + local handle_body = function(body) + client:handle_body(body) + end + stdout:read_start(create_read_loop(handle_body, nil, function(err) + client:on_error(client_errors.READ_ERROR, err) + end)) + + 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/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua new file mode 100644 index 0000000000..b1bc48dac6 --- /dev/null +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -0,0 +1,702 @@ +local api = vim.api +local handlers = require('vim.lsp.handlers') +local util = require('vim.lsp.util') + +--- @class STTokenRange +--- @field line number line number 0-based +--- @field start_col number start column 0-based +--- @field end_col number end column 0-based +--- @field type string token type as string +--- @field modifiers string[] token modifiers as strings +--- @field extmark_added boolean whether this extmark has been added to the buffer yet +--- +--- @class STCurrentResult +--- @field version number document version associated with this result +--- @field result_id string resultId from the server; used with delta requests +--- @field highlights STTokenRange[] cache of highlight ranges for this document version +--- @field tokens number[] raw token array as received by the server. used for calculating delta responses +--- @field namespace_cleared boolean whether the namespace was cleared for this result yet +--- +--- @class STActiveRequest +--- @field request_id number the LSP request ID of the most recent request sent to the server +--- @field version number the document version associated with the most recent request +--- +--- @class STClientState +--- @field namespace number +--- @field active_request STActiveRequest +--- @field current_result STCurrentResult + +---@class STHighlighter +---@field active table<number, STHighlighter> +---@field bufnr number +---@field augroup number augroup for buffer events +---@field debounce number milliseconds to debounce requests for new tokens +---@field timer table uv_timer for debouncing requests for new tokens +---@field client_state table<number, STClientState> +local STHighlighter = { active = {} } + +---@private +local function binary_search(tokens, line) + local lo = 1 + local hi = #tokens + while lo < hi do + local mid = math.floor((lo + hi) / 2) + if tokens[mid].line < line then + lo = mid + 1 + else + hi = mid + end + end + return lo +end + +--- Extracts modifier strings from the encoded number in the token array +--- +---@private +---@return string[] +local function modifiers_from_number(x, modifiers_table) + local modifiers = {} + local idx = 1 + while x > 0 do + if _G.bit then + if _G.bit.band(x, 1) == 1 then + modifiers[#modifiers + 1] = modifiers_table[idx] + end + x = _G.bit.rshift(x, 1) + else + --TODO(jdrouhard): remove this branch once `bit` module is available for non-LuaJIT (#21222) + if x % 2 == 1 then + modifiers[#modifiers + 1] = modifiers_table[idx] + end + x = math.floor(x / 2) + end + idx = idx + 1 + end + + return modifiers +end + +--- Converts a raw token list to a list of highlight ranges used by the on_win callback +--- +---@private +---@return STTokenRange[] +local function tokens_to_ranges(data, bufnr, client) + local legend = client.server_capabilities.semanticTokensProvider.legend + local token_types = legend.tokenTypes + local token_modifiers = legend.tokenModifiers + local ranges = {} + + local line + local start_char = 0 + for i = 1, #data, 5 do + local delta_line = data[i] + line = line and line + delta_line or delta_line + local delta_start = data[i + 1] + start_char = delta_line == 0 and start_char + delta_start or delta_start + + -- data[i+3] +1 because Lua tables are 1-indexed + local token_type = token_types[data[i + 3] + 1] + local modifiers = modifiers_from_number(data[i + 4], token_modifiers) + + ---@private + local function _get_byte_pos(char_pos) + return util._get_line_byte_from_position(bufnr, { + line = line, + character = char_pos, + }, client.offset_encoding) + end + + local start_col = _get_byte_pos(start_char) + local end_col = _get_byte_pos(start_char + data[i + 2]) + + if token_type then + ranges[#ranges + 1] = { + line = line, + start_col = start_col, + end_col = end_col, + type = token_type, + modifiers = modifiers, + extmark_added = false, + } + end + end + + return ranges +end + +--- Construct a new STHighlighter for the buffer +--- +---@private +---@param bufnr number +function STHighlighter.new(bufnr) + local self = setmetatable({}, { __index = STHighlighter }) + + self.bufnr = bufnr + self.augroup = api.nvim_create_augroup('vim_lsp_semantic_tokens:' .. bufnr, { clear = true }) + self.client_state = {} + + STHighlighter.active[bufnr] = self + + api.nvim_buf_attach(bufnr, false, { + on_lines = function(_, buf) + local highlighter = STHighlighter.active[buf] + if not highlighter then + return true + end + highlighter:on_change() + end, + on_reload = function(_, buf) + local highlighter = STHighlighter.active[buf] + if highlighter then + highlighter:reset() + highlighter:send_request() + end + end, + on_detach = function(_, buf) + local highlighter = STHighlighter.active[buf] + if highlighter then + highlighter:destroy() + end + end, + }) + + api.nvim_create_autocmd({ 'BufWinEnter', 'InsertLeave' }, { + buffer = self.bufnr, + group = self.augroup, + callback = function() + self:send_request() + end, + }) + + api.nvim_create_autocmd('LspDetach', { + buffer = self.bufnr, + group = self.augroup, + callback = function(args) + self:detach(args.data.client_id) + if vim.tbl_isempty(self.client_state) then + self:destroy() + end + end, + }) + + return self +end + +---@private +function STHighlighter:destroy() + for client_id, _ in pairs(self.client_state) do + self:detach(client_id) + end + + api.nvim_del_augroup_by_id(self.augroup) + STHighlighter.active[self.bufnr] = nil +end + +---@private +function STHighlighter:attach(client_id) + local state = self.client_state[client_id] + if not state then + state = { + namespace = api.nvim_create_namespace('vim_lsp_semantic_tokens:' .. client_id), + active_request = {}, + current_result = {}, + } + self.client_state[client_id] = state + end +end + +---@private +function STHighlighter:detach(client_id) + local state = self.client_state[client_id] + if state then + --TODO: delete namespace if/when that becomes possible + api.nvim_buf_clear_namespace(self.bufnr, state.namespace, 0, -1) + self.client_state[client_id] = nil + end +end + +--- This is the entry point for getting all the tokens in a buffer. +--- +--- For the given clients (or all attached, if not provided), this sends a request +--- to ask for semantic tokens. If the server supports delta requests, that will +--- be prioritized if we have a previous requestId and token array. +--- +--- This function will skip servers where there is an already an active request in +--- flight for the same version. If there is a stale request in flight, that is +--- cancelled prior to sending a new one. +--- +--- Finally, if the request was successful, the requestId and document version +--- are saved to facilitate document synchronization in the response. +--- +---@private +function STHighlighter:send_request() + local version = util.buf_versions[self.bufnr] + + self:reset_timer() + + for client_id, state in pairs(self.client_state) do + local client = vim.lsp.get_client_by_id(client_id) + + local current_result = state.current_result + local active_request = state.active_request + + -- Only send a request for this client if the current result is out of date and + -- there isn't a current a request in flight for this version + if client and current_result.version ~= version and active_request.version ~= version then + -- cancel stale in-flight request + if active_request.request_id then + client.cancel_request(active_request.request_id) + active_request = {} + state.active_request = active_request + end + + local spec = client.server_capabilities.semanticTokensProvider.full + local hasEditProvider = type(spec) == 'table' and spec.delta + + local params = { textDocument = util.make_text_document_params(self.bufnr) } + local method = 'textDocument/semanticTokens/full' + + if hasEditProvider and current_result.result_id then + method = method .. '/delta' + params.previousResultId = current_result.result_id + end + local success, request_id = client.request(method, params, function(err, response, ctx) + -- look client up again using ctx.client_id instead of using a captured + -- client object + local c = vim.lsp.get_client_by_id(ctx.client_id) + local highlighter = STHighlighter.active[ctx.bufnr] + if not err and c and highlighter then + highlighter:process_response(response, c, version) + end + end, self.bufnr) + + if success then + active_request.request_id = request_id + active_request.version = version + end + end + end +end + +--- This function will parse the semantic token responses and set up the cache +--- (current_result). It also performs document synchronization by checking the +--- version of the document associated with the resulting request_id and only +--- performing work if the response is not out-of-date. +--- +--- Delta edits are applied if necessary, and new highlight ranges are calculated +--- and stored in the buffer state. +--- +--- Finally, a redraw command is issued to force nvim to redraw the screen to +--- pick up changed highlight tokens. +--- +---@private +function STHighlighter:process_response(response, client, version) + local state = self.client_state[client.id] + if not state then + return + end + + -- ignore stale responses + if state.active_request.version and version ~= state.active_request.version then + return + end + + -- reset active request + state.active_request = {} + + -- skip nil responses + if response == nil then + return + end + + -- if we have a response to a delta request, update the state of our tokens + -- appropriately. if it's a full response, just use that + local tokens + local token_edits = response.edits + if token_edits then + table.sort(token_edits, function(a, b) + return a.start < b.start + end) + + tokens = {} + local old_tokens = state.current_result.tokens + local idx = 1 + for _, token_edit in ipairs(token_edits) do + vim.list_extend(tokens, old_tokens, idx, token_edit.start) + if token_edit.data then + vim.list_extend(tokens, token_edit.data) + end + idx = token_edit.start + token_edit.deleteCount + 1 + end + vim.list_extend(tokens, old_tokens, idx) + else + tokens = response.data + end + + -- Update the state with the new results + local current_result = state.current_result + current_result.version = version + current_result.result_id = response.resultId + current_result.tokens = tokens + current_result.highlights = tokens_to_ranges(tokens, self.bufnr, client) + current_result.namespace_cleared = false + + api.nvim_command('redraw!') +end + +--- on_win handler for the decoration provider (see |nvim_set_decoration_provider|) +--- +--- If there is a current result for the buffer and the version matches the +--- current document version, then the tokens are valid and can be applied. As +--- the buffer is drawn, this function will add extmark highlights for every +--- token in the range of visible lines. Once a highlight has been added, it +--- sticks around until the document changes and there's a new set of matching +--- highlight tokens available. +--- +--- If this is the first time a buffer is being drawn with a new set of +--- highlights for the current document version, the namespace is cleared to +--- remove extmarks from the last version. It's done here instead of the response +--- handler to avoid the "blink" that occurs due to the timing between the +--- response handler and the actual redraw. +--- +---@private +function STHighlighter:on_win(topline, botline) + for _, state in pairs(self.client_state) do + local current_result = state.current_result + if current_result.version and current_result.version == util.buf_versions[self.bufnr] then + if not current_result.namespace_cleared then + api.nvim_buf_clear_namespace(self.bufnr, state.namespace, 0, -1) + current_result.namespace_cleared = true + end + + -- We can't use ephemeral extmarks because the buffer updates are not in + -- sync with the list of semantic tokens. There's a delay between the + -- buffer changing and when the LSP server can respond with updated + -- tokens, and we don't want to "blink" the token highlights while + -- updates are in flight, and we don't want to use stale tokens because + -- they likely won't line up right with the actual buffer. + -- + -- Instead, we have to use normal extmarks that can attach to locations + -- in the buffer and are persisted between redraws. + local highlights = current_result.highlights + local idx = binary_search(highlights, topline) + + for i = idx, #highlights do + local token = highlights[i] + + if token.line > botline then + break + end + + if not token.extmark_added then + -- `strict = false` is necessary here for the 1% of cases where the + -- current result doesn't actually match the buffer contents. Some + -- LSP servers can respond with stale tokens on requests if they are + -- still processing changes from a didChange notification. + -- + -- LSP servers that do this _should_ follow up known stale responses + -- with a refresh notification once they've finished processing the + -- didChange notification, which would re-synchronize the tokens from + -- our end. + -- + -- The server I know of that does this is clangd when the preamble of + -- a file changes and the token request is processed with a stale + -- preamble while the new one is still being built. Once the preamble + -- finishes, clangd sends a refresh request which lets the client + -- re-synchronize the tokens. + api.nvim_buf_set_extmark(self.bufnr, state.namespace, token.line, token.start_col, { + hl_group = '@' .. token.type, + end_col = token.end_col, + priority = vim.highlight.priorities.semantic_tokens, + strict = false, + }) + + -- TODO(bfredl) use single extmark when hl_group supports table + if #token.modifiers > 0 then + for _, modifier in pairs(token.modifiers) do + api.nvim_buf_set_extmark(self.bufnr, state.namespace, token.line, token.start_col, { + hl_group = '@' .. modifier, + end_col = token.end_col, + priority = vim.highlight.priorities.semantic_tokens + 1, + strict = false, + }) + end + end + + token.extmark_added = true + end + end + end + end +end + +--- Reset the buffer's highlighting state and clears the extmark highlights. +--- +---@private +function STHighlighter:reset() + for client_id, state in pairs(self.client_state) do + api.nvim_buf_clear_namespace(self.bufnr, state.namespace, 0, -1) + state.current_result = {} + if state.active_request.request_id then + local client = vim.lsp.get_client_by_id(client_id) + assert(client) + client.cancel_request(state.active_request.request_id) + state.active_request = {} + end + end +end + +--- Mark a client's results as dirty. This method will cancel any active +--- requests to the server and pause new highlights from being added +--- in the on_win callback. The rest of the current results are saved +--- in case the server supports delta requests. +--- +---@private +---@param client_id number +function STHighlighter:mark_dirty(client_id) + local state = self.client_state[client_id] + assert(state) + + -- if we clear the version from current_result, it'll cause the + -- next request to be sent and will also pause new highlights + -- from being added in on_win until a new result comes from + -- the server + if state.current_result then + state.current_result.version = nil + end + + if state.active_request.request_id then + local client = vim.lsp.get_client_by_id(client_id) + assert(client) + client.cancel_request(state.active_request.request_id) + state.active_request = {} + end +end + +---@private +function STHighlighter:on_change() + self:reset_timer() + if self.debounce > 0 then + self.timer = vim.defer_fn(function() + self:send_request() + end, self.debounce) + else + self:send_request() + end +end + +---@private +function STHighlighter:reset_timer() + local timer = self.timer + if timer then + self.timer = nil + if not timer:is_closing() then + timer:stop() + timer:close() + end + end +end + +local M = {} + +--- Start the semantic token highlighting engine for the given buffer with the +--- given client. The client must already be attached to the buffer. +--- +--- NOTE: This is currently called automatically by |vim.lsp.buf_attach_client()|. To +--- opt-out of semantic highlighting with a server that supports it, you can +--- delete the semanticTokensProvider table from the {server_capabilities} of +--- your client in your |LspAttach| callback or your configuration's +--- `on_attach` callback: +--- <pre>lua +--- client.server_capabilities.semanticTokensProvider = nil +--- </pre> +--- +---@param bufnr number +---@param client_id number +---@param opts (nil|table) Optional keyword arguments +--- - debounce (number, default: 200): Debounce token requests +--- to the server by the given number in milliseconds +function M.start(bufnr, client_id, opts) + vim.validate({ + bufnr = { bufnr, 'n', false }, + client_id = { client_id, 'n', false }, + }) + + opts = opts or {} + assert( + (not opts.debounce or type(opts.debounce) == 'number'), + 'opts.debounce must be a number with the debounce time in milliseconds' + ) + + local client = vim.lsp.get_client_by_id(client_id) + if not client then + vim.notify('[LSP] No client with id ' .. client_id, vim.log.levels.ERROR) + return + end + + if not vim.lsp.buf_is_attached(bufnr, client_id) then + vim.notify( + '[LSP] Client with id ' .. client_id .. ' not attached to buffer ' .. bufnr, + vim.log.levels.WARN + ) + return + end + + if not vim.tbl_get(client.server_capabilities, 'semanticTokensProvider', 'full') then + vim.notify('[LSP] Server does not support semantic tokens', vim.log.levels.WARN) + return + end + + local highlighter = STHighlighter.active[bufnr] + + if not highlighter then + highlighter = STHighlighter.new(bufnr) + highlighter.debounce = opts.debounce or 200 + else + highlighter.debounce = math.max(highlighter.debounce, opts.debounce or 200) + end + + highlighter:attach(client_id) + highlighter:send_request() +end + +--- Stop the semantic token highlighting engine for the given buffer with the +--- given client. +--- +--- NOTE: This is automatically called by a |LspDetach| autocmd that is set up as part +--- of `start()`, so you should only need this function to manually disengage the semantic +--- token engine without fully detaching the LSP client from the buffer. +--- +---@param bufnr number +---@param client_id number +function M.stop(bufnr, client_id) + vim.validate({ + bufnr = { bufnr, 'n', false }, + client_id = { client_id, 'n', false }, + }) + + local highlighter = STHighlighter.active[bufnr] + if not highlighter then + return + end + + highlighter:detach(client_id) + + if vim.tbl_isempty(highlighter.client_state) then + highlighter:destroy() + end +end + +--- Return the semantic token(s) at the given position. +--- If called without arguments, returns the token under the cursor. +--- +---@param bufnr number|nil Buffer number (0 for current buffer, default) +---@param row number|nil Position row (default cursor position) +---@param col number|nil Position column (default cursor position) +--- +---@return table|nil (table|nil) List of tokens at position +function M.get_at_pos(bufnr, row, col) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + local highlighter = STHighlighter.active[bufnr] + if not highlighter then + return + end + + if row == nil or col == nil then + local cursor = api.nvim_win_get_cursor(0) + row, col = cursor[1] - 1, cursor[2] + end + + local tokens = {} + for client_id, client in pairs(highlighter.client_state) do + local highlights = client.current_result.highlights + if highlights then + local idx = binary_search(highlights, row) + for i = idx, #highlights do + local token = highlights[i] + + if token.line > row then + break + end + + if token.start_col <= col and token.end_col > col then + token.client_id = client_id + tokens[#tokens + 1] = token + end + end + end + end + return tokens +end + +--- Force a refresh of all semantic tokens +--- +--- Only has an effect if the buffer is currently active for semantic token +--- highlighting (|vim.lsp.semantic_tokens.start()| has been called for it) +--- +---@param bufnr (nil|number) default: current buffer +function M.force_refresh(bufnr) + vim.validate({ + bufnr = { bufnr, 'n', true }, + }) + + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + local highlighter = STHighlighter.active[bufnr] + if not highlighter then + return + end + + highlighter:reset() + highlighter:send_request() +end + +--- |lsp-handler| for the method `workspace/semanticTokens/refresh` +--- +--- Refresh requests are sent by the server to indicate a project-wide change +--- that requires all tokens to be re-requested by the client. This handler will +--- invalidate the current results of all buffers and automatically kick off a +--- new request for buffers that are displayed in a window. For those that aren't, a +--- the BufWinEnter event should take care of it next time it's displayed. +--- +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#semanticTokens_refreshRequest +handlers['workspace/semanticTokens/refresh'] = function(err, _, ctx) + if err then + return vim.NIL + end + + for _, bufnr in ipairs(vim.lsp.get_buffers_by_client_id(ctx.client_id)) do + local highlighter = STHighlighter.active[bufnr] + if highlighter and highlighter.client_state[ctx.client_id] then + highlighter:mark_dirty(ctx.client_id) + + if not vim.tbl_isempty(vim.fn.win_findbuf(bufnr)) then + highlighter:send_request() + end + end + end + + return vim.NIL +end + +local namespace = api.nvim_create_namespace('vim_lsp_semantic_tokens') +api.nvim_set_decoration_provider(namespace, { + on_win = function(_, _, bufnr, topline, botline) + local highlighter = STHighlighter.active[bufnr] + if highlighter then + highlighter:on_win(topline, botline) + end + end, +}) + +--- for testing only! there is no guarantee of API stability with this! +--- +---@private +M.__STHighlighter = STHighlighter + +return M diff --git a/runtime/lua/vim/lsp/sync.lua b/runtime/lua/vim/lsp/sync.lua index 0d65e86b55..826352f036 100644 --- a/runtime/lua/vim/lsp/sync.lua +++ b/runtime/lua/vim/lsp/sync.lua @@ -392,7 +392,7 @@ end ---@param lastline number line to begin search in old_lines for last difference ---@param new_lastline number line to begin search in new_lines for last difference ---@param offset_encoding string encoding requested by language server ----@returns table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentContentChangeEvent +---@returns table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent function M.compute_diff( prev_lines, curr_lines, diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 283099bbcf..38051e6410 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 @@ -828,7 +856,7 @@ end --- `textDocument/signatureHelp`, and potentially others. --- ---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) ----@param contents (table, optional, default `{}`) List of strings to extend with converted lines +---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}. ---@returns {contents}, extended with lines of converted markdown. ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover function M.convert_input_to_markdown_lines(input, contents) @@ -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 @@ -987,6 +1015,7 @@ end --- - border (string or table) override `border` --- - focusable (string or table) override `focusable` --- - zindex (string or table) override `zindex`, defaults to 50 +--- - relative ("mouse"|"cursor") defaults to "cursor" ---@returns (table) Options function M.make_floating_popup_options(width, height, opts) validate({ @@ -1001,7 +1030,8 @@ function M.make_floating_popup_options(width, height, opts) local anchor = '' local row, col - local lines_above = vim.fn.winline() - 1 + local lines_above = opts.relative == 'mouse' and vim.fn.getmousepos().line - 1 + or vim.fn.winline() - 1 local lines_below = vim.fn.winheight(0) - lines_above if lines_above < lines_below then @@ -1014,7 +1044,9 @@ function M.make_floating_popup_options(width, height, opts) row = 0 end - if vim.fn.wincol() + width + (opts.offset_x or 0) <= api.nvim_get_option('columns') then + local wincol = opts.relative == 'mouse' and vim.fn.getmousepos().column or vim.fn.wincol() + + if wincol + width + (opts.offset_x or 0) <= api.nvim_get_option('columns') then anchor = anchor .. 'W' col = 0 else @@ -1022,64 +1054,103 @@ function M.make_floating_popup_options(width, height, opts) col = 1 end + local title = (opts.border and opts.title) and opts.title or nil + local title_pos + + if title then + title_pos = opts.title_pos or 'center' + end + return { anchor = anchor, col = col + (opts.offset_x or 0), height = height, focusable = opts.focusable, - relative = 'cursor', + relative = opts.relative == 'mouse' and 'mouse' or 'cursor', row = row + (opts.offset_y or 0), style = 'minimal', width = width, border = opts.border or default_border, zindex = opts.zindex or 50, + title = title, + title_pos = title_pos, } 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|nil 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|nil 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: @@ -1194,7 +1265,7 @@ function M.stylize_markdown(bufnr, contents, opts) -- when ft is nil, we get the ft from the regex match local matchers = { block = { nil, '```+([a-zA-Z0-9_]*)', '```+' }, - pre = { '', '<pre>', '</pre>' }, + pre = { nil, '<pre>([a-z0-9]*)', '</pre>' }, code = { '', '<code>', '</code>' }, text = { 'text', '<text>', '</text>' }, } @@ -1219,8 +1290,6 @@ function M.stylize_markdown(bufnr, contents, opts) -- Clean up contents = M._trim(contents, opts) - -- Insert blank line separator after code block? - local add_sep = opts.separator == nil and true or opts.separator local stripped = {} local highlights = {} -- keep track of lnums that contain markdown @@ -1248,7 +1317,7 @@ function M.stylize_markdown(bufnr, contents, opts) finish = #stripped, }) -- add a separator, but not on the last line - if add_sep and i < #contents then + if opts.separator and i < #contents then table.insert(stripped, '---') markdown_lines[#stripped] = true end @@ -1484,7 +1553,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 @@ -1612,7 +1681,7 @@ do --[[ References ]] ---@param bufnr number Buffer id ---@param references table List of `DocumentHighlight` objects to highlight ---@param offset_encoding string One of "utf-8", "utf-16", "utf-32". - ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#documentHighlight + ---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent function M.buf_highlight_references(bufnr, references, offset_encoding) validate({ bufnr = { bufnr, 'n', true }, @@ -1799,7 +1868,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 @@ -1843,7 +1912,7 @@ end --- Creates a `TextDocumentPositionParams` object for the current buffer and cursor position. --- ---@param window number|nil: window handle or 0 for current, defaults to current ----@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` +---@param offset_encoding string|nil utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` ---@returns `TextDocumentPositionParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams function M.make_position_params(window, offset_encoding) @@ -1866,7 +1935,7 @@ function M._get_offset_encoding(bufnr) local offset_encoding - for _, client in pairs(vim.lsp.buf_get_clients(bufnr)) do + for _, client in pairs(vim.lsp.get_active_clients({ bufnr = bufnr })) do if client.offset_encoding == nil then vim.notify_once( string.format( @@ -1972,7 +2041,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/secure.lua b/runtime/lua/vim/secure.lua new file mode 100644 index 0000000000..443b152273 --- /dev/null +++ b/runtime/lua/vim/secure.lua @@ -0,0 +1,188 @@ +local M = {} + +---@private +--- Reads trust database from $XDG_STATE_HOME/nvim/trust. +--- +---@return (table) Contents of trust database, if it exists. Empty table otherwise. +local function read_trust() + local trust = {} + local f = io.open(vim.fn.stdpath('state') .. '/trust', 'r') + if f then + local contents = f:read('*a') + if contents then + for line in vim.gsplit(contents, '\n') do + local hash, file = string.match(line, '^(%S+) (.+)$') + if hash and file then + trust[file] = hash + end + end + end + f:close() + end + return trust +end + +---@private +--- Writes provided {trust} table to trust database at +--- $XDG_STATE_HOME/nvim/trust. +--- +---@param trust (table) Trust table to write +local function write_trust(trust) + vim.validate({ trust = { trust, 't' } }) + local f = assert(io.open(vim.fn.stdpath('state') .. '/trust', 'w')) + + local t = {} + for p, h in pairs(trust) do + t[#t + 1] = string.format('%s %s\n', h, p) + end + f:write(table.concat(t)) + f:close() +end + +--- Attempt to read the file at {path} prompting the user if the file should be +--- trusted. The user's choice is persisted in a trust database at +--- $XDG_STATE_HOME/nvim/trust. +--- +---@see |:trust| +--- +---@param path (string) Path to a file to read. +--- +---@return (string|nil) The contents of the given file if it exists and is +--- trusted, or nil otherwise. +function M.read(path) + vim.validate({ path = { path, 's' } }) + local fullpath = vim.loop.fs_realpath(vim.fs.normalize(path)) + if not fullpath then + return nil + end + + local trust = read_trust() + + if trust[fullpath] == '!' then + -- File is denied + return nil + end + + local contents + do + local f = io.open(fullpath, 'r') + if not f then + return nil + end + contents = f:read('*a') + f:close() + end + + local hash = vim.fn.sha256(contents) + if trust[fullpath] == hash then + -- File already exists in trust database + return contents + end + + -- File either does not exist in trust database or the hash does not match + local ok, result = pcall( + vim.fn.confirm, + string.format('%s is not trusted.', fullpath), + '&ignore\n&view\n&deny\n&allow', + 1 + ) + + if not ok and result ~= 'Keyboard interrupt' then + error(result) + elseif not ok or result == 0 or result == 1 then + -- Cancelled or ignored + return nil + elseif result == 2 then + -- View + vim.cmd('sview ' .. fullpath) + return nil + elseif result == 3 then + -- Deny + trust[fullpath] = '!' + contents = nil + elseif result == 4 then + -- Allow + trust[fullpath] = hash + end + + write_trust(trust) + + return contents +end + +--- Manage the trust database. +--- +--- The trust database is located at |$XDG_STATE_HOME|/nvim/trust. +--- +---@param opts (table): +--- - action (string): "allow" to add a file to the trust database and trust it, +--- "deny" to add a file to the trust database and deny it, +--- "remove" to remove file from the trust database +--- - path (string|nil): Path to a file to update. Mutually exclusive with {bufnr}. +--- Cannot be used when {action} is "allow". +--- - bufnr (number|nil): Buffer number to update. Mutually exclusive with {path}. +---@return (boolean, string) success, msg: +--- - true and full path of target file if operation was successful +--- - false and error message on failure +function M.trust(opts) + vim.validate({ + path = { opts.path, 's', true }, + bufnr = { opts.bufnr, 'n', true }, + action = { + opts.action, + function(m) + return m == 'allow' or m == 'deny' or m == 'remove' + end, + [["allow" or "deny" or "remove"]], + }, + }) + + local path = opts.path + local bufnr = opts.bufnr + local action = opts.action + + assert(not path or not bufnr, '"path" and "bufnr" are mutually exclusive') + + if action == 'allow' then + assert(not path, '"path" is not valid when action is "allow"') + end + + local fullpath + if path then + fullpath = vim.loop.fs_realpath(vim.fs.normalize(path)) + elseif bufnr then + local bufname = vim.api.nvim_buf_get_name(bufnr) + if bufname == '' then + return false, 'buffer is not associated with a file' + end + fullpath = vim.loop.fs_realpath(vim.fs.normalize(bufname)) + else + error('one of "path" or "bufnr" is required') + end + + if not fullpath then + return false, string.format('invalid path: %s', path) + end + + local trust = read_trust() + + if action == 'allow' then + local newline = vim.bo[bufnr].fileformat == 'unix' and '\n' or '\r\n' + local contents = table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, false), newline) + if vim.bo[bufnr].endofline then + contents = contents .. newline + end + local hash = vim.fn.sha256(contents) + + trust[fullpath] = hash + elseif action == 'deny' then + trust[fullpath] = '!' + elseif action == 'remove' then + trust[fullpath] = nil + end + + write_trust(trust) + return true, fullpath +end + +return M diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index e1b4ed4ea9..cc48e3f193 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) @@ -48,6 +49,9 @@ vim.deepcopy = (function() if f then return f(orig, cache or {}) else + if type(orig) == 'userdata' and orig == vim.NIL then + return vim.NIL + end error('Cannot deepcopy object of type ' .. type(orig)) end end @@ -56,13 +60,14 @@ end)() --- Splits a string at each instance of a separator. --- ---@see |vim.split()| +---@see |luaref-patterns| ---@see https://www.lua.org/pil/20.2.html ---@see http://lua-users.org/wiki/StringLibraryTutorial --- ---@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 +---@param plain (boolean|nil) If `true` use `sep` literally (passed to string.find) +---@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 } }) @@ -98,10 +103,10 @@ end --- Splits a string at each instance of a separator. --- --- Examples: ---- <pre> ---- split(":aa::b:", ":") --> {'','aa','','b',''} ---- split("axaby", "ab?") --> {'','x','y'} ---- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} +--- <pre>lua +--- 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> --- @@ -109,11 +114,11 @@ end --- ---@param s string String to split ---@param sep string Separator or pattern ----@param kwargs table Keyword arguments: +---@param 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 +---@return string[] List of split components function vim.split(s, sep, kwargs) local plain local trimempty = false @@ -156,8 +161,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 +---@generic T: table +---@param t table<T, any> (table) 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 +177,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 +192,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 +208,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 +311,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 @@ -373,7 +384,7 @@ end --- Return `nil` if the key does not exist. --- --- Examples: ---- <pre> +--- <pre>lua --- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true --- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil --- </pre> @@ -385,15 +396,14 @@ end function vim.tbl_get(o, ...) local keys = { ... } if #keys == 0 then - return + return nil end for i, k in ipairs(keys) do - if type(o[k]) ~= 'table' and next(keys, i) then - return nil - end o = o[k] if o == nil then - return + return nil + elseif type(o) ~= 'table' and next(keys, i) then + return nil end end return o @@ -405,11 +415,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|nil) Start index on src. Defaults to 1 +---@param finish (number|nil) Final index on src. Defaults to `#src` +---@return T dst function vim.list_extend(dst, src, start, finish) vim.validate({ dst = { dst, 't' }, @@ -447,6 +458,33 @@ function vim.tbl_flatten(t) return result end +--- Enumerate a table sorted by its keys. +--- +---@see Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua +--- +---@param t table List-like table +---@return iterator over sorted keys and their values +function vim.spairs(t) + assert(type(t) == 'table', string.format('Expected table, got %s', type(t))) + + -- collect the keys + local keys = {} + for k in pairs(t) do + table.insert(keys, k) + end + table.sort(keys) + + -- Return the iterator function. + -- TODO(justinmk): Return "iterator function, table {t}, and nil", like pairs()? + local i = 0 + return function() + i = i + 1 + if keys[i] then + return keys[i], t[keys[i]] + end + end +end + --- Tests if a Lua table can be treated as an array. --- --- Empty table `{}` is assumed to be an array, unless it was created by @@ -476,7 +514,7 @@ function vim.tbl_islist(t) -- TODO(bfredl): in the future, we will always be inside nvim -- then this check can be deleted. if vim._empty_dict_mt == nil then - return nil + return false end return getmetatable(t) ~= vim._empty_dict_mt end @@ -484,9 +522,9 @@ end --- Counts the number of non-nil values in table `t`. --- ---- <pre> ---- vim.tbl_count({ a=1, b=2 }) => 2 ---- vim.tbl_count({ 1, 2 }) => 2 +--- <pre>lua +--- vim.tbl_count({ a=1, b=2 }) --> 2 +--- vim.tbl_count({ 1, 2 }) --> 2 --- </pre> --- ---@see https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua @@ -504,10 +542,11 @@ end --- Creates a copy of a table containing only elements from start to end (inclusive) --- ----@param list table 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) +---@generic T +---@param list T[] (list) Table +---@param start number|nil Start range of slice +---@param finish number|nil End range of slice +---@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 @@ -518,6 +557,7 @@ end --- Trim whitespace (Lua pattern "%s") from both sides of a string. --- +---@see |luaref-patterns| ---@see https://www.lua.org/pil/20.2.html ---@param s string String to trim ---@return string String with whitespace removed from its beginning and end @@ -533,7 +573,7 @@ end ---@return string %-escaped pattern string function vim.pesc(s) vim.validate({ s = { s, 's' } }) - return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1') + return (s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1')) end --- Tests if `s` starts with `prefix`. @@ -559,7 +599,7 @@ end --- Validates a parameter specification (types and values). --- --- Usage example: ---- <pre> +--- <pre>lua --- function user.new(name, age, hobbies) --- vim.validate{ --- name={name, 'string'}, @@ -571,24 +611,24 @@ end --- </pre> --- --- Examples with explicit argument values (can be run directly): ---- <pre> +--- <pre>lua --- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} ---- => NOP (success) +--- --> NOP (success) --- --- vim.validate{arg1={1, 'table'}} ---- => error('arg1: expected table, got number') +--- --> error('arg1: expected table, got number') --- --- vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}} ---- => error('arg1: expected even number, got 3') +--- --> error('arg1: expected even number, got 3') --- </pre> --- --- If multiple types are valid they can be given as a list. ---- <pre> +--- <pre>lua --- vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} ---- => NOP (success) +--- --> NOP (success) --- --- vim.validate{arg1={1, {'string', table'}}} ---- => error('arg1: expected string|table, got number') +--- --> error('arg1: expected string|table, got number') --- --- </pre> --- @@ -715,5 +755,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>lua +--- 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..582922ecb6 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,425 @@ 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, lang = tree:lang() }) + 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: +--- - lang string|nil Parser language +--- - ignore_injections boolean Ignore injected languages (default true) +--- +---@return userdata|nil |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, opts.lang) + 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>lua +--- 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) +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 +end + +--- Open a window that displays a textual representation of the nodes in the language tree. +--- +--- While in the window, press "a" to toggle display of anonymous nodes, "I" to toggle the +--- display of the source language of each node, and press <Enter> to jump to the node under the +--- cursor in the source buffer. +--- +---@param opts table|nil Optional options table with the following possible keys: +--- - lang (string|nil): The language of the source buffer. If omitted, the +--- filetype of the source buffer is used. +--- - bufnr (number|nil): Buffer to draw the tree into. If omitted, a new +--- buffer is created. +--- - winid (number|nil): Window id to display the tree buffer in. If omitted, +--- a new window is created with {command}. +--- - command (string|nil): Vimscript command to create the window. Default +--- value is "topleft 60vnew". Only used when {winid} is nil. +--- - title (string|fun(bufnr:number):string|nil): Title of the window. If a +--- function, it accepts the buffer number of the source buffer as its only +--- argument and should return a string. +function M.show_tree(opts) + vim.validate({ + opts = { opts, 't', true }, + }) + + opts = opts or {} + + local Playground = require('vim.treesitter.playground') + local buf = a.nvim_get_current_buf() + local win = a.nvim_get_current_win() + local pg = assert(Playground:new(buf, opts.lang)) + + -- Close any existing playground window + if vim.b[buf].playground then + local w = vim.b[buf].playground + if a.nvim_win_is_valid(w) then + a.nvim_win_close(w, true) + end + end + + local w = opts.winid + if not w then + vim.cmd(opts.command or 'topleft 60vnew') + w = a.nvim_get_current_win() + end + + local b = opts.bufnr + if b then + a.nvim_win_set_buf(w, b) + else + b = a.nvim_win_get_buf(w) + end + + vim.b[buf].playground = w + + vim.wo[w].scrolloff = 5 + vim.wo[w].wrap = false + vim.bo[b].buflisted = false + vim.bo[b].buftype = 'nofile' + vim.bo[b].bufhidden = 'wipe' + + local title = opts.title + if not title then + local bufname = a.nvim_buf_get_name(buf) + title = string.format('Syntax tree for %s', vim.fn.fnamemodify(bufname, ':.')) + elseif type(title) == 'function' then + title = title(buf) + end + + assert(type(title) == 'string', 'Window title must be a string') + a.nvim_buf_set_name(b, title) + + pg:draw(b) + + vim.fn.matchadd('Comment', '\\[[0-9:-]\\+\\]') + vim.fn.matchadd('String', '".*"') + + a.nvim_buf_clear_namespace(buf, pg.ns, 0, -1) + a.nvim_buf_set_keymap(b, 'n', '<CR>', '', { + desc = 'Jump to the node under the cursor in the source buffer', + callback = function() + local row = a.nvim_win_get_cursor(w)[1] + local pos = pg:get(row) + a.nvim_set_current_win(win) + a.nvim_win_set_cursor(win, { pos.lnum + 1, pos.col }) + end, + }) + a.nvim_buf_set_keymap(b, 'n', 'a', '', { + desc = 'Toggle anonymous nodes', + callback = function() + pg.opts.anon = not pg.opts.anon + pg:draw(b) + end, + }) + a.nvim_buf_set_keymap(b, 'n', 'I', '', { + desc = 'Toggle language display', + callback = function() + pg.opts.lang = not pg.opts.lang + pg:draw(b) + end, + }) + + local group = a.nvim_create_augroup('treesitter/playground', {}) + + a.nvim_create_autocmd('CursorMoved', { + group = group, + buffer = b, + callback = function() + a.nvim_buf_clear_namespace(buf, pg.ns, 0, -1) + local row = a.nvim_win_get_cursor(w)[1] + local pos = pg:get(row) + a.nvim_buf_set_extmark(buf, pg.ns, pos.lnum, pos.col, { + end_row = pos.end_lnum, + end_col = math.max(0, pos.end_col), + hl_group = 'Visual', + }) + end, + }) + + a.nvim_create_autocmd('CursorMoved', { + group = group, + buffer = buf, + callback = function() + if not a.nvim_buf_is_loaded(b) then + return true + end + + a.nvim_buf_clear_namespace(b, pg.ns, 0, -1) + + local cursor = a.nvim_win_get_cursor(win) + local cursor_node = M.get_node_at_pos(buf, cursor[1] - 1, cursor[2], { + lang = opts.lang, + ignore_injections = false, + }) + if not cursor_node then + return + end + + local cursor_node_id = cursor_node:id() + for i, v in pg:iter() do + if v.id == cursor_node_id then + local start = v.depth + local end_col = start + #v.text + a.nvim_buf_set_extmark(b, pg.ns, i - 1, start, { + end_col = end_col, + hl_group = 'Visual', + }) + a.nvim_win_set_cursor(w, { i, 0 }) + break + end + end + end, + }) + + a.nvim_create_autocmd({ 'TextChanged', 'InsertLeave' }, { + group = group, + buffer = buf, + callback = function() + if not a.nvim_buf_is_loaded(b) then + return true + end + + pg = assert(Playground:new(buf, opts.lang)) + pg:draw(b) + end, + }) + + a.nvim_create_autocmd('BufLeave', { + group = group, + buffer = b, + callback = function() + a.nvim_buf_clear_namespace(buf, pg.ns, 0, -1) + end, + }) + + a.nvim_create_autocmd('BufLeave', { + group = group, + buffer = buf, + callback = function() + if not a.nvim_buf_is_loaded(b) then + return true + end + + a.nvim_buf_clear_namespace(b, pg.ns, 0, -1) + end, + }) + + a.nvim_create_autocmd('BufHidden', { + group = group, + buffer = buf, + once = true, + callback = function() + if a.nvim_win_is_valid(w) then + a.nvim_win_close(w, true) + end + end, + }) +end + return M diff --git a/runtime/lua/vim/treesitter/health.lua b/runtime/lua/vim/treesitter/health.lua index 3bd59ca282..c0a1eca0ce 100644 --- a/runtime/lua/vim/treesitter/health.lua +++ b/runtime/lua/vim/treesitter/health.lua @@ -1,36 +1,33 @@ local M = {} local ts = vim.treesitter +local health = require('vim.health') --- 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 --- Performs a healthcheck for treesitter integration function M.check() - local report_info = vim.fn['health#report_info'] - local report_ok = vim.fn['health#report_ok'] - local report_error = vim.fn['health#report_error'] local parsers = M.list_parsers() - report_info(string.format('Runtime ABI version : %d', ts.language_version)) + health.report_info(string.format('Nvim runtime ABI version: %d', ts.language_version)) for _, parser in pairs(parsers) do local parsername = vim.fn.fnamemodify(parser, ':t:r') - local is_loadable, ret = pcall(ts.language.require_language, parsername) - if not is_loadable then - report_error(string.format('Impossible to load parser for %s: %s', parsername, ret)) + if not is_loadable or not ret then + health.report_error( + string.format('Parser "%s" failed to load (path: %s): %s', parsername, parser, ret or '?') + ) elseif ret then local lang = ts.language.inspect_language(parsername) - report_ok( - string.format('Loaded parser for %s: ABI version %d', parsername, lang._abi_version) + health.report_ok( + string.format('Parser: %-10s ABI: %d, path: %s', parsername, lang._abi_version, parser) ) - else - report_error(string.format('Unable to load parser for %s', parsername)) end end end diff --git a/runtime/lua/vim/treesitter/highlighter.lua b/runtime/lua/vim/treesitter/highlighter.lua index e27a5fa9c3..d77a0d0d03 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,10 @@ function TSHighlighter.new(tree, opts) end end - a.nvim_buf_set_option(self.bufnr, 'syntax', '') + self.orig_spelloptions = vim.bo[self.bufnr].spelloptions + + vim.bo[self.bufnr].syntax = '' + vim.b[self.bufnr].ts_highlight = true TSHighlighter.active[self.bufnr] = self @@ -196,9 +100,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 @@ -209,6 +117,14 @@ function TSHighlighter:destroy() if TSHighlighter.active[self.bufnr] then TSHighlighter.active[self.bufnr] = nil end + + if vim.api.nvim_buf_is_loaded(self.bufnr) then + vim.bo[self.bufnr].spelloptions = self.orig_spelloptions + vim.b[self.bufnr].ts_highlight = nil + if vim.g.syntax_on == 1 then + a.nvim_exec_autocmds('FileType', { group = 'syntaxset', buffer = self.bufnr }) + end + end end ---@private @@ -246,8 +162,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 +175,7 @@ function TSHighlighter:get_query(lang) end ---@private -local function on_line_impl(self, buf, line) +local function on_line_impl(self, buf, line, is_spell_nav) self.tree:for_each_tree(function(tstree, tree) if not tstree then return @@ -294,14 +212,26 @@ 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 capture_name = highlighter_query:query().captures[capture] + local spell = nil + if capture_name == 'spell' then + spell = true + elseif capture_name == 'nospell' then + spell = false + end + + -- Give nospell a higher priority so it always overrides spell captures. + local spell_pri_offset = capture_name == 'nospell' and 1 or 0 + + if hl and end_row >= line and (not is_spell_nav or spell ~= nil) then a.nvim_buf_set_extmark(buf, ns, start_row, start_col, { end_line = end_row, end_col = end_col, hl_group = hl, ephemeral = true, - priority = tonumber(metadata.priority) or 100, -- Low but leaves room below + priority = (tonumber(metadata.priority) or 100) + spell_pri_offset, -- Low but leaves room below conceal = metadata.conceal, + spell = spell, }) end if start_row > line then @@ -318,7 +248,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 +289,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..a1e96f8ef2 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,52 @@ 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) + if tree then + return tree:root():named_descendant_for_range(unpack(range)) + end +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/playground.lua b/runtime/lua/vim/treesitter/playground.lua new file mode 100644 index 0000000000..bb073290c6 --- /dev/null +++ b/runtime/lua/vim/treesitter/playground.lua @@ -0,0 +1,186 @@ +local api = vim.api + +local M = {} + +---@class Playground +---@field ns number API namespace +---@field opts table Options table with the following keys: +--- - anon (boolean): If true, display anonymous nodes +--- - lang (boolean): If true, display the language alongside each node +--- +---@class Node +---@field id number Node id +---@field text string Node text +---@field named boolean True if this is a named (non-anonymous) node +---@field depth number Depth of the node within the tree +---@field lnum number Beginning line number of this node in the source buffer +---@field col number Beginning column number of this node in the source buffer +---@field end_lnum number Final line number of this node in the source buffer +---@field end_col number Final column number of this node in the source buffer +---@field lang string Source language of this node + +--- Traverse all child nodes starting at {node}. +--- +--- This is a recursive function. The {depth} parameter indicates the current recursion level. +--- {lang} is a string indicating the language of the tree currently being traversed. Each traversed +--- node is added to {tree}. When recursion completes, {tree} is an array of all nodes in the order +--- they were visited. +--- +--- {injections} is a table mapping node ids from the primary tree to language tree injections. Each +--- injected language has a series of trees nested within the primary language's tree, and the root +--- node of each of these trees is contained within a node in the primary tree. The {injections} +--- table maps nodes in the primary tree to root nodes of injected trees. +--- +---@param node userdata Starting node to begin traversal |tsnode| +---@param depth number Current recursion depth +---@param lang string Language of the tree currently being traversed +---@param injections table Mapping of node ids to root nodes of injected language trees (see +--- explanation above) +---@param tree Node[] Output table containing a list of tables each representing a node in the tree +---@private +local function traverse(node, depth, lang, injections, tree) + local injection = injections[node:id()] + if injection then + traverse(injection.root, depth, injection.lang, injections, tree) + end + + for child, field in node:iter_children() do + local type = child:type() + local lnum, col, end_lnum, end_col = child:range() + local named = child:named() + local text + if named then + if field then + text = string.format('%s: (%s)', field, type) + else + text = string.format('(%s)', type) + end + else + text = string.format('"%s"', type:gsub('\n', '\\n')) + end + + table.insert(tree, { + id = child:id(), + text = text, + named = named, + depth = depth, + lnum = lnum, + col = col, + end_lnum = end_lnum, + end_col = end_col, + lang = lang, + }) + + traverse(child, depth + 1, lang, injections, tree) + end + + return tree +end + +--- Create a new Playground object. +--- +---@param bufnr number Source buffer number +---@param lang string|nil Language of source buffer +--- +---@return Playground|nil +---@return string|nil Error message, if any +--- +---@private +function M.new(self, bufnr, lang) + local ok, parser = pcall(vim.treesitter.get_parser, bufnr or 0, lang) + if not ok then + return nil, 'No parser available for the given buffer' + end + + -- For each child tree (injected language), find the root of the tree and locate the node within + -- the primary tree that contains that root. Add a mapping from the node in the primary tree to + -- the root in the child tree to the {injections} table. + local root = parser:parse()[1]:root() + local injections = {} + parser:for_each_child(function(child, lang_) + child:for_each_tree(function(tree) + local r = tree:root() + local node = root:named_descendant_for_range(r:range()) + if node then + injections[node:id()] = { + lang = lang_, + root = r, + } + end + end) + end) + + local nodes = traverse(root, 0, parser:lang(), injections, {}) + + local named = {} + for _, v in ipairs(nodes) do + if v.named then + named[#named + 1] = v + end + end + + local t = { + ns = api.nvim_create_namespace(''), + nodes = nodes, + named = named, + opts = { + anon = false, + lang = false, + }, + } + + setmetatable(t, self) + self.__index = self + return t +end + +--- Write the contents of this Playground into {bufnr}. +--- +---@param bufnr number Buffer number to write into. +---@private +function M.draw(self, bufnr) + vim.bo[bufnr].modifiable = true + local lines = {} + for _, item in self:iter() do + lines[#lines + 1] = table.concat({ + string.rep(' ', item.depth), + item.text, + item.lnum == item.end_lnum + and string.format(' [%d:%d-%d]', item.lnum + 1, item.col + 1, item.end_col) + or string.format( + ' [%d:%d-%d:%d]', + item.lnum + 1, + item.col + 1, + item.end_lnum + 1, + item.end_col + ), + self.opts.lang and string.format(' %s', item.lang) or '', + }) + end + api.nvim_buf_set_lines(bufnr, 0, -1, false, lines) + vim.bo[bufnr].modifiable = false +end + +--- Get node {i} from this Playground object. +--- +--- The node number is dependent on whether or not anonymous nodes are displayed. +--- +---@param i number Node number to get +---@return Node +---@private +function M.get(self, i) + local t = self.opts.anon and self.nodes or self.named + return t[i] +end + +--- Iterate over all of the nodes in this Playground object. +--- +---@return function Iterator over all nodes in this Playground +---@return table +---@return number +---@private +function M.iter(self) + return ipairs(self.opts.anon and self.nodes or self.named) +end + +return M diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua index 103e85abfd..dbf134573d 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,9 @@ 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:table, pattern:string, bufnr:number, predicate:string[]) +--- - see |vim.treesitter.query.add_directive()| for argument meanings function M.add_predicate(name, handler, force) if predicate_handlers[name] and not force then error(string.format('Overriding %s', name)) @@ -385,9 +436,13 @@ 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:table, pattern:string, bufnr:number, predicate:string[], metadata:table) +--- - match: see |treesitter-query| +--- - node-level data are accessible via `match[capture_id]` +--- - pattern: see |treesitter-query| +--- - predicate: list of strings containing the full directive being called, e.g. +--- `(node (#set! conceal "-"))` would get the predicate `{ "#set!", "conceal", "-" }` function M.add_directive(name, handler, force) if directive_handlers[name] and not force then error(string.format('Overriding %s', name)) @@ -397,12 +452,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,18 +545,17 @@ 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> +--- <pre>lua --- 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: @@ -510,13 +565,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,15 +602,14 @@ 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: ---- ---- <pre> +--- Here is an example iterating over all captures in every match: +--- <pre>lua --- 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] @@ -567,13 +622,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/lua/vim/ui.lua b/runtime/lua/vim/ui.lua index 6f1ce3089d..8f5be15221 100644 --- a/runtime/lua/vim/ui.lua +++ b/runtime/lua/vim/ui.lua @@ -21,7 +21,7 @@ local M = {} --- --- --- Example: ---- <pre> +--- <pre>lua --- vim.ui.select({ 'tabs', 'spaces' }, { --- prompt = 'Select tabs or spaces:', --- format_item = function(item) @@ -73,11 +73,12 @@ end --- user inputs. ---@param on_confirm function ((input|nil) -> ()) --- Called once the user confirms or abort the input. ---- `input` is what the user typed. +--- `input` is what the user typed (it might be +--- an empty string if nothing was entered), or --- `nil` if the user aborted the dialog. --- --- Example: ---- <pre> +--- <pre>lua --- vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input) --- vim.o.shiftwidth = tonumber(input) --- end) @@ -88,11 +89,17 @@ function M.input(opts, on_confirm) }) opts = (opts and not vim.tbl_isempty(opts)) and opts or vim.empty_dict() - local input = vim.fn.input(opts) - if #input > 0 then - on_confirm(input) - else + + -- Note that vim.fn.input({}) returns an empty string when cancelled. + -- vim.ui.input() should distinguish aborting from entering an empty string. + local _canceled = vim.NIL + opts = vim.tbl_extend('keep', opts, { cancelreturn = _canceled }) + + local ok, input = pcall(vim.fn.input, opts) + if not ok or input == _canceled then on_confirm(nil) + else + on_confirm(input) end end diff --git a/runtime/menu.vim b/runtime/menu.vim index 0a5ac36095..2671bb51cb 100644 --- a/runtime/menu.vim +++ b/runtime/menu.vim @@ -2,7 +2,7 @@ " You can also use this as a start for your own set of menus. " " Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2020 Mar 29 +" Last Change: 2022 Nov 27 " Note that ":an" (short for ":anoremenu") is often used to make a menu work " in all modes and avoid side effects from mappings defined by the user. @@ -89,6 +89,21 @@ an 9999.75 &Help.-sep2- <Nop> an 9999.80 &Help.&Version :version<CR> an 9999.90 &Help.&About :intro<CR> +if exists(':tlmenu') + tlnoremenu 9999.10 &Help.&Overview<Tab><F1> <C-W>:help<CR> + tlnoremenu 9999.20 &Help.&User\ Manual <C-W>:help usr_toc<CR> + tlnoremenu 9999.30 &Help.&How-To\ Links <C-W>:help how-to<CR> + tlnoremenu <silent> 9999.40 &Help.&Find\.\.\. <C-W>:call <SID>Helpfind()<CR> + tlnoremenu 9999.45 &Help.-sep1- <Nop> + tlnoremenu 9999.50 &Help.&Credits <C-W>:help credits<CR> + tlnoremenu 9999.60 &Help.Co&pying <C-W>:help copying<CR> + tlnoremenu 9999.70 &Help.&Sponsor/Register <C-W>:help sponsor<CR> + tlnoremenu 9999.70 &Help.O&rphans <C-W>:help kcc<CR> + tlnoremenu 9999.75 &Help.-sep2- <Nop> + tlnoremenu 9999.80 &Help.&Version <C-W>:version<CR> + tlnoremenu 9999.90 &Help.&About <C-W>:intro<CR> +endif + fun! s:Helpfind() if !exists("g:menutrans_help_dialog") let g:menutrans_help_dialog = "Enter a command or word to find help on:\n\nPrepend i_ for Input mode commands (e.g.: i_CTRL-X)\nPrepend c_ for command-line editing commands (e.g.: c_<Del>)\nPrepend ' for an option name (e.g.: 'shiftwidth')" @@ -124,12 +139,7 @@ if has("diff") an 10.420 &File.Split\ Patched\ &By\.\.\. :browse vert diffpatch<CR> endif -if has("printer") - an 10.500 &File.-SEP3- <Nop> - an 10.510 &File.&Print :hardcopy<CR> - vunmenu &File.&Print - vnoremenu &File.&Print :hardcopy<CR> -elseif has("unix") +if has("unix") an 10.500 &File.-SEP3- <Nop> an 10.510 &File.&Print :w !lpr<CR> vunmenu &File.&Print @@ -702,6 +712,11 @@ func s:BMCanAdd(name, num) return 0 endif + " no name with control characters + if a:name =~ '[\x01-\x1f]' + return 0 + endif + " no special buffer, such as terminal or popup let buftype = getbufvar(a:num, '&buftype') if buftype != '' && buftype != 'nofile' && buftype != 'nowrite' @@ -1049,11 +1064,7 @@ if has("toolbar") an <silent> 1.20 ToolBar.Save :if expand("%") == ""<Bar>browse confirm w<Bar>else<Bar>confirm w<Bar>endif<CR> an 1.30 ToolBar.SaveAll :browse confirm wa<CR> - if has("printer") - an 1.40 ToolBar.Print :hardcopy<CR> - vunmenu ToolBar.Print - vnoremenu ToolBar.Print :hardcopy<CR> - elseif has("unix") + if has("unix") an 1.40 ToolBar.Print :w !lpr<CR> vunmenu ToolBar.Print vnoremenu ToolBar.Print :w !lpr<CR> diff --git a/runtime/neovim.ico b/runtime/neovim.ico Binary files differnew file mode 100644 index 0000000000..e0c151c966 --- /dev/null +++ b/runtime/neovim.ico diff --git a/runtime/nvim.appdata.xml b/runtime/nvim.appdata.xml index 1464c27694..7411a7190a 100644 --- a/runtime/nvim.appdata.xml +++ b/runtime/nvim.appdata.xml @@ -26,6 +26,9 @@ </screenshots> <releases> + <release date="2022-12-29" version="0.8.2"/> + <release date="2022-11-14" version="0.8.1"/> + <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..200254321e 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 Dec 16 " If there already is an option window, jump to that one. let buf = bufnr('option-window') @@ -20,7 +20,7 @@ let s:cpo_save = &cpo set cpo&vim " function to be called when <CR> is hit in the option-window -fun! <SID>CR() +func <SID>CR() " If on a continued comment line, go back to the first comment line let lnum = search("^[^\t]", 'bWcn') @@ -47,10 +47,10 @@ fun! <SID>CR() elseif match(line, '^ \=[0-9]') >= 0 exe "norm! /" . line . "\<CR>zt" endif -endfun +endfunc " function to be called when <Space> is hit in the option-window -fun! <SID>Space() +func <SID>Space() let lnum = line(".") let line = getline(lnum) @@ -67,16 +67,17 @@ fun! <SID>Space() endif endif -endfun +endfunc -let s:local_to_window = '(local to window)' -let s:local_to_buffer = '(local to buffer)' -let s:global_or_local = '(global or local to buffer)' +let s:local_to_window = gettext('(local to window)') +let s:local_to_buffer = gettext('(local to buffer)') +let s:global_or_local = gettext('(global or local to buffer)') " find the window in which the option applies " returns 0 for global option, 1 for local option, -1 for error -fun! <SID>Find(lnum) - if getline(a:lnum - 1) =~ "(local to" +func <SID>Find(lnum) + let line = getline(a:lnum - 1) + if line =~ s:local_to_window || line =~ s:local_to_buffer let local = 1 let thiswin = winnr() wincmd p @@ -95,10 +96,10 @@ fun! <SID>Find(lnum) let local = -1 endif return local -endfun +endfunc " Update a "set" line in the option window -fun! <SID>Update(lnum, line, local, thiswin) +func <SID>Update(lnum, line, local, thiswin) " get the new value of the option and update the option window line if match(a:line, "=") >= 0 let name = substitute(a:line, '^ \tset \([^=]*\)=.*', '\1', "") @@ -123,7 +124,7 @@ fun! <SID>Update(lnum, line, local, thiswin) endif endif set nomodified -endfun +endfunc " Reset 'title' and 'icon' to make it work faster. " Reset 'undolevels' to avoid undo'ing until the buffer is empty. @@ -149,13 +150,13 @@ exe $OPTWIN_CMD . ' new option-window' setlocal ts=15 tw=0 noro buftype=nofile " Insert help and a "set" command for each option. -call append(0, '" Each "set" line shows the current value of an option (on the left).') -call append(1, '" Hit <CR> on a "set" line to execute it.') -call append(2, '" A boolean option will be toggled.') -call append(3, '" For other options you can edit the value before hitting <CR>.') -call append(4, '" Hit <CR> on a help line to open a help window on this option.') -call append(5, '" Hit <CR> on an index line to jump there.') -call append(6, '" Hit <Space> on a "set" line to refresh it.') +call append(0, gettext('" Each "set" line shows the current value of an option (on the left).')) +call append(1, gettext('" Hit <Enter> on a "set" line to execute it.')) +call append(2, gettext('" A boolean option will be toggled.')) +call append(3, gettext('" For other options you can edit the value before hitting <Enter>.')) +call append(4, gettext('" Hit <Enter> on a help line to open a help window on this option.')) +call append(5, gettext('" Hit <Enter> on an index line to jump there.')) +call append(6, gettext('" Hit <Space> on a "set" line to refresh it.')) " These functions are called often below. Keep them fast! @@ -170,34 +171,34 @@ func <SID>AddOption(name, text) endfunc " Init a local binary option -fun! <SID>BinOptionL(name) +func <SID>BinOptionL(name) let val = getwinvar(winnr('#'), '&' . a:name) call append("$", substitute(substitute(" \tset " . val . a:name . "\t" . \!val . a:name, "0", "no", ""), "1", "", "")) -endfun +endfunc " Init a global binary option -fun! <SID>BinOptionG(name, val) +func <SID>BinOptionG(name, val) call append("$", substitute(substitute(" \tset " . a:val . a:name . "\t" . \!a:val . a:name, "0", "no", ""), "1", "", "")) -endfun +endfunc " Init a local string option -fun! <SID>OptionL(name) +func <SID>OptionL(name) let val = escape(getwinvar(winnr('#'), '&' . a:name), " \t\\\"|") call append("$", " \tset " . a:name . "=" . val) -endfun +endfunc " Init a global string option -fun! <SID>OptionG(name, val) +func <SID>OptionG(name, val) call append("$", " \tset " . a:name . "=" . escape(a:val, " \t\\\"|")) -endfun +endfunc let s:idx = 1 let s:lnum = line("$") call append("$", "") -fun! <SID>Header(text) +func <SID>Header(text) let line = s:idx . " " . a:text if s:idx < 10 let line = " " . line @@ -208,15 +209,15 @@ fun! <SID>Header(text) call append(s:lnum, line) let s:idx = s:idx + 1 let s:lnum = s:lnum + 1 -endfun +endfunc " Get the value of 'pastetoggle'. It could be a special key. -fun! <SID>PTvalue() +func <SID>PTvalue() redir @a silent set pt redir END return substitute(@a, '[^=]*=\(.*\)', '\1', "") -endfun +endfunc " Restore the previous value of 'cpoptions' here, it's used below. let &cpo = s:cpo_save @@ -224,1054 +225,1016 @@ let &cpo = s:cpo_save " List of all options, organized by function. " The text should be sufficient to know what the option is used for. -call <SID>Header("important") -call append("$", "compatible\tbehave very Vi compatible (not advisable)") +call <SID>Header(gettext("important")) +call <SID>AddOption("compatible", gettext("behave very Vi compatible (not advisable)")) call <SID>BinOptionG("cp", &cp) -call append("$", "cpoptions\tlist of flags to specify Vi compatibility") +call <SID>AddOption("cpoptions", gettext("list of flags to specify Vi compatibility")) call <SID>OptionG("cpo", &cpo) -call append("$", "paste\tpaste mode, insert typed text literally") +call <SID>AddOption("paste", gettext("paste mode, insert typed text literally")) call <SID>BinOptionG("paste", &paste) -call append("$", "pastetoggle\tkey sequence to toggle paste mode") +call <SID>AddOption("pastetoggle", gettext("key sequence to toggle paste mode")) if &pt =~ "\x80" call append("$", " \tset pt=" . <SID>PTvalue()) else call <SID>OptionG("pt", &pt) endif -call append("$", "runtimepath\tlist of directories used for runtime files and plugins") +call <SID>AddOption("runtimepath", gettext("list of directories used for runtime files and plugins")) call <SID>OptionG("rtp", &rtp) -call append("$", "packpath\tlist of directories used for plugin packages") +call <SID>AddOption("packpath", gettext("list of directories used for plugin packages")) call <SID>OptionG("pp", &pp) -call append("$", "helpfile\tname of the main help file") +call <SID>AddOption("helpfile", gettext("name of the main help file")) call <SID>OptionG("hf", &hf) -call <SID>Header("moving around, searching and patterns") -call append("$", "whichwrap\tlist of flags specifying which commands wrap to another line") -call append("$", "\t(local to window)") -call <SID>OptionL("ww") -call append("$", "startofline\tmany jump commands move the cursor to the first non-blank") -call append("$", "\tcharacter of a line") +call <SID>Header(gettext("moving around, searching and patterns")) +call <SID>AddOption("whichwrap", gettext("list of flags specifying which commands wrap to another line")) +call <SID>OptionG("ww", &ww) +call <SID>AddOption("startofline", gettext("many jump commands move the cursor to the first non-blank\ncharacter of a line")) call <SID>BinOptionG("sol", &sol) -call append("$", "paragraphs\tnroff macro names that separate paragraphs") +call <SID>AddOption("paragraphs", gettext("nroff macro names that separate paragraphs")) call <SID>OptionG("para", ¶) -call append("$", "sections\tnroff macro names that separate sections") +call <SID>AddOption("sections", gettext("nroff macro names that separate sections")) call <SID>OptionG("sect", §) -call append("$", "path\tlist of directory names used for file searching") -call append("$", "\t(global or local to buffer)") +call <SID>AddOption("path", gettext("list of directory names used for file searching")) +call append("$", "\t" .. s:global_or_local) call <SID>OptionG("pa", &pa) -call <SID>AddOption("cdhome", ":cd without argument goes to the home directory") +call <SID>AddOption("cdhome", gettext(":cd without argument goes to the home directory")) call <SID>BinOptionG("cdh", &cdh) -call append("$", "cdpath\tlist of directory names used for :cd") +call <SID>AddOption("cdpath", gettext("list of directory names used for :cd")) call <SID>OptionG("cd", &cd) if exists("+autochdir") - call append("$", "autochdir\tchange to directory of file in buffer") + call <SID>AddOption("autochdir", gettext("change to directory of file in buffer")) call <SID>BinOptionG("acd", &acd) endif -call append("$", "wrapscan\tsearch commands wrap around the end of the buffer") +call <SID>AddOption("wrapscan", gettext("search commands wrap around the end of the buffer")) call <SID>BinOptionG("ws", &ws) -call append("$", "incsearch\tshow match for partly typed search command") +call <SID>AddOption("incsearch", gettext("show match for partly typed search command")) call <SID>BinOptionG("is", &is) -call append("$", "magic\tchange the way backslashes are used in search patterns") +call <SID>AddOption("magic", gettext("change the way backslashes are used in search patterns")) call <SID>BinOptionG("magic", &magic) -call append("$", "regexpengine\tselect the default regexp engine used") +call <SID>AddOption("regexpengine", gettext("select the default regexp engine used")) call <SID>OptionG("re", &re) -call append("$", "ignorecase\tignore case when using a search pattern") +call <SID>AddOption("ignorecase", gettext("ignore case when using a search pattern")) call <SID>BinOptionG("ic", &ic) -call append("$", "smartcase\toverride 'ignorecase' when pattern has upper case characters") +call <SID>AddOption("smartcase", gettext("override 'ignorecase' when pattern has upper case characters")) call <SID>BinOptionG("scs", &scs) -call append("$", "casemap\twhat method to use for changing case of letters") +call <SID>AddOption("casemap", gettext("what method to use for changing case of letters")) call <SID>OptionG("cmp", &cmp) -call append("$", "maxmempattern\tmaximum amount of memory in Kbyte used for pattern matching") +call <SID>AddOption("maxmempattern", gettext("maximum amount of memory in Kbyte used for pattern matching")) call append("$", " \tset mmp=" . &mmp) -call append("$", "define\tpattern for a macro definition line") -call append("$", "\t(global or local to buffer)") +call <SID>AddOption("define", gettext("pattern for a macro definition line")) +call append("$", "\t" .. s:global_or_local) call <SID>OptionG("def", &def) if has("find_in_path") - call append("$", "include\tpattern for an include-file line") - call append("$", "\t(local to buffer)") + call <SID>AddOption("include", gettext("pattern for an include-file line")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("inc") - call append("$", "includeexpr\texpression used to transform an include line to a file name") - call append("$", "\t(local to buffer)") + call <SID>AddOption("includeexpr", gettext("expression used to transform an include line to a file name")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("inex") endif -call <SID>Header("tags") -call append("$", "tagbsearch\tuse binary searching in tags files") +call <SID>Header(gettext("tags")) +call <SID>AddOption("tagbsearch", gettext("use binary searching in tags files")) call <SID>BinOptionG("tbs", &tbs) -call append("$", "taglength\tnumber of significant characters in a tag name or zero") +call <SID>AddOption("taglength", gettext("number of significant characters in a tag name or zero")) call append("$", " \tset tl=" . &tl) -call append("$", "tags\tlist of file names to search for tags") -call append("$", "\t(global or local to buffer)") +call <SID>AddOption("tags", gettext("list of file names to search for tags")) +call append("$", "\t" .. s:global_or_local) call <SID>OptionG("tag", &tag) -call append("$", "tagcase\thow to handle case when searching in tags files:") -call append("$", "\t\"followic\" to follow 'ignorecase', \"ignore\" or \"match\"") -call append("$", "\t(global or local to buffer)") +call <SID>AddOption("tagcase", gettext("how to handle case when searching in tags files:\n\"followic\" to follow 'ignorecase', \"ignore\" or \"match\"")) +call append("$", "\t" .. s:global_or_local) call <SID>OptionG("tc", &tc) -call append("$", "tagrelative\tfile names in a tags file are relative to the tags file") +call <SID>AddOption("tagrelative", gettext("file names in a tags file are relative to the tags file")) call <SID>BinOptionG("tr", &tr) -call append("$", "tagstack\ta :tag command will use the tagstack") +call <SID>AddOption("tagstack", gettext("a :tag command will use the tagstack")) call <SID>BinOptionG("tgst", &tgst) -call append("$", "showfulltag\twhen completing tags in Insert mode show more info") +call <SID>AddOption("showfulltag", gettext("when completing tags in Insert mode show more info")) call <SID>BinOptionG("sft", &sft) if has("eval") - call append("$", "tagfunc\ta function to be used to perform tag searches") - call append("$", "\t(local to buffer)") + call <SID>AddOption("tagfunc", gettext("a function to be used to perform tag searches")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("tfu") endif -if has("cscope") - call append("$", "cscopeprg\tcommand for executing cscope") - call <SID>OptionG("csprg", &csprg) - call append("$", "cscopetag\tuse cscope for tag commands") - call <SID>BinOptionG("cst", &cst) - call append("$", "cscopetagorder\t0 or 1; the order in which \":cstag\" performs a search") - call append("$", " \tset csto=" . &csto) - call append("$", "cscopeverbose\tgive messages when adding a cscope database") - call <SID>BinOptionG("csverb", &csverb) - call append("$", "cscopepathcomp\thow many components of the path to show") - call append("$", " \tset cspc=" . &cspc) - call append("$", "cscopequickfix\twhen to open a quickfix window for cscope") - call <SID>OptionG("csqf", &csqf) - call append("$", "cscoperelative\tfile names in a cscope file are relative to that file") - call <SID>BinOptionG("csre", &csre) -endif -call <SID>Header("displaying text") -call append("$", "scroll\tnumber of lines to scroll for CTRL-U and CTRL-D") -call append("$", "\t(local to window)") +call <SID>Header(gettext("displaying text")) +call <SID>AddOption("scroll", gettext("number of lines to scroll for CTRL-U and CTRL-D")) +call append("$", "\t" .. s:local_to_window) call <SID>OptionL("scr") -call append("$", "scrolloff\tnumber of screen lines to show around the cursor") +call <SID>AddOption("scrolloff", gettext("number of screen lines to show around the cursor")) call append("$", " \tset so=" . &so) -call append("$", "wrap\tlong lines wrap") -call append("$", "\t(local to window)") +call <SID>AddOption("wrap", gettext("long lines wrap")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("wrap") -call append("$", "linebreak\twrap long lines at a character in 'breakat'") -call append("$", "\t(local to window)") +call <SID>AddOption("linebreak", gettext("wrap long lines at a character in 'breakat'")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("lbr") -call append("$", "breakindent\tpreserve indentation in wrapped text") -call append("$", "\t(local to window)") +call <SID>AddOption("breakindent", gettext("preserve indentation in wrapped text")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("bri") -call append("$", "breakindentopt\tadjust breakindent behaviour") -call append("$", "\t(local to window)") +call <SID>AddOption("breakindentopt", gettext("adjust breakindent behaviour")) +call append("$", "\t" .. s:local_to_window) call <SID>OptionL("briopt") -call append("$", "breakat\twhich characters might cause a line break") +call <SID>AddOption("breakat", gettext("which characters might cause a line break")) call <SID>OptionG("brk", &brk) -call append("$", "showbreak\tstring to put before wrapped screen lines") +call <SID>AddOption("showbreak", gettext("string to put before wrapped screen lines")) call <SID>OptionG("sbr", &sbr) -call append("$", "sidescroll\tminimal number of columns to scroll horizontally") +call <SID>AddOption("sidescroll", gettext("minimal number of columns to scroll horizontally")) call append("$", " \tset ss=" . &ss) -call append("$", "sidescrolloff\tminimal number of columns to keep left and right of the cursor") +call <SID>AddOption("sidescrolloff", gettext("minimal number of columns to keep left and right of the cursor")) call append("$", " \tset siso=" . &siso) -call append("$", "display\tinclude \"lastline\" to show the last line even if it doesn't fit") -call append("$", "\tinclude \"uhex\" to show unprintable characters as a hex number") +call <SID>AddOption("display", gettext("include \"lastline\" to show the last line even if it doesn't fit\ninclude \"uhex\" to show unprintable characters as a hex number")) call <SID>OptionG("dy", &dy) -call append("$", "fillchars\tcharacters to use for the status line, folds and filler lines") +call <SID>AddOption("fillchars", gettext("characters to use for the status line, folds and filler lines")) call <SID>OptionG("fcs", &fcs) -call append("$", "cmdheight\tnumber of lines used for the command-line") +call <SID>AddOption("cmdheight", gettext("number of lines used for the command-line")) call append("$", " \tset ch=" . &ch) -call append("$", "columns\twidth of the display") +call <SID>AddOption("columns", gettext("width of the display")) call append("$", " \tset co=" . &co) -call append("$", "lines\tnumber of lines in the display") +call <SID>AddOption("lines", gettext("number of lines in the display")) call append("$", " \tset lines=" . &lines) -call append("$", "window\tnumber of lines to scroll for CTRL-F and CTRL-B") +call <SID>AddOption("window", gettext("number of lines to scroll for CTRL-F and CTRL-B")) call append("$", " \tset window=" . &window) -call append("$", "lazyredraw\tdon't redraw while executing macros") +call <SID>AddOption("lazyredraw", gettext("don't redraw while executing macros")) call <SID>BinOptionG("lz", &lz) if has("reltime") - call append("$", "redrawtime\ttimeout for 'hlsearch' and :match highlighting in msec") + call <SID>AddOption("redrawtime", gettext("timeout for 'hlsearch' and :match highlighting in msec")) call append("$", " \tset rdt=" . &rdt) endif -call append("$", "writedelay\tdelay in msec for each char written to the display") -call append("$", "\t(for debugging)") +call <SID>AddOption("writedelay", gettext("delay in msec for each char written to the display\n(for debugging)")) call append("$", " \tset wd=" . &wd) -call append("$", "list\tshow <Tab> as ^I and end-of-line as $") -call append("$", "\t(local to window)") +call <SID>AddOption("list", gettext("show <Tab> as ^I and end-of-line as $")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("list") -call append("$", "listchars\tlist of strings used for list mode") +call <SID>AddOption("listchars", gettext("list of strings used for list mode")) call <SID>OptionG("lcs", &lcs) -call append("$", "number\tshow the line number for each line") -call append("$", "\t(local to window)") +call <SID>AddOption("number", gettext("show the line number for each line")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("nu") -call append("$", "relativenumber\tshow the relative line number for each line") -call append("$", "\t(local to window)") +call <SID>AddOption("relativenumber", gettext("show the relative line number for each line")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("rnu") if has("linebreak") - call append("$", "numberwidth\tnumber of columns to use for the line number") - call append("$", "\t(local to window)") + call <SID>AddOption("numberwidth", gettext("number of columns to use for the line number")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("nuw") endif if has("conceal") - call append("$", "conceallevel\tcontrols whether concealable text is hidden") - call append("$", "\t(local to window)") + call <SID>AddOption("conceallevel", gettext("controls whether concealable text is hidden")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("cole") - call append("$", "concealcursor\tmodes in which text in the cursor line can be concealed") - call append("$", "\t(local to window)") + call <SID>AddOption("concealcursor", gettext("modes in which text in the cursor line can be concealed")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("cocu") endif -call <SID>Header("syntax, highlighting and spelling") -call append("$", "background\t\"dark\" or \"light\"; the background color brightness") +call <SID>Header(gettext("syntax, highlighting and spelling")) +call <SID>AddOption("background", gettext("\"dark\" or \"light\"; the background color brightness")) call <SID>OptionG("bg", &bg) -call append("$", "filetype\ttype of file; triggers the FileType event when set") -call append("$", "\t(local to buffer)") +call <SID>AddOption("filetype", gettext("type of file; triggers the FileType event when set")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("ft") if has("syntax") - call append("$", "syntax\tname of syntax highlighting used") - call append("$", "\t(local to buffer)") + call <SID>AddOption("syntax", gettext("name of syntax highlighting used")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("syn") - call append("$", "synmaxcol\tmaximum column to look for syntax items") - call append("$", "\t(local to buffer)") + call <SID>AddOption("synmaxcol", gettext("maximum column to look for syntax items")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("smc") endif -call append("$", "highlight\twhich highlighting to use for various occasions") +call <SID>AddOption("highlight", gettext("which highlighting to use for various occasions")) call <SID>OptionG("hl", &hl) -call append("$", "hlsearch\thighlight all matches for the last used search pattern") +call <SID>AddOption("hlsearch", gettext("highlight all matches for the last used search pattern")) call <SID>BinOptionG("hls", &hls) if has("termguicolors") - call append("$", "termguicolors\tuse GUI colors for the terminal") + call <SID>AddOption("termguicolors", gettext("use GUI colors for the terminal")) call <SID>BinOptionG("tgc", &tgc) endif if has("syntax") - call append("$", "cursorcolumn\thighlight the screen column of the cursor") - call append("$", "\t(local to window)") + call <SID>AddOption("cursorcolumn", gettext("highlight the screen column of the cursor")) + call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("cuc") - call append("$", "cursorline\thighlight the screen line of the cursor") - call append("$", "\t(local to window)") + call <SID>AddOption("cursorline", gettext("highlight the screen line of the cursor")) + call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("cul") - call append("$", "cursorlineopt\tspecifies which area 'cursorline' highlights") - call append("$", "\t(local to window)") + call <SID>AddOption("cursorlineopt", gettext("specifies which area 'cursorline' highlights")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("culopt") - call append("$", "colorcolumn\tcolumns to highlight") - call append("$", "\t(local to window)") + call <SID>AddOption("colorcolumn", gettext("columns to highlight")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("cc") - call append("$", "spell\thighlight spelling mistakes") - call append("$", "\t(local to window)") + call <SID>AddOption("spell", gettext("highlight spelling mistakes")) + call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("spell") - call append("$", "spelllang\tlist of accepted languages") - call append("$", "\t(local to buffer)") + call <SID>AddOption("spelllang", gettext("list of accepted languages")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("spl") - call append("$", "spellfile\tfile that \"zg\" adds good words to") - call append("$", "\t(local to buffer)") + call <SID>AddOption("spellfile", gettext("file that \"zg\" adds good words to")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("spf") - call append("$", "spellcapcheck\tpattern to locate the end of a sentence") - call append("$", "\t(local to buffer)") + call <SID>AddOption("spellcapcheck", gettext("pattern to locate the end of a sentence")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("spc") - call append("$", "spelloptions\tflags to change how spell checking works") - call append("$", "\t(local to buffer)") + call <SID>AddOption("spelloptions", gettext("flags to change how spell checking works")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("spo") - call append("$", "spellsuggest\tmethods used to suggest corrections") + call <SID>AddOption("spellsuggest", gettext("methods used to suggest corrections")) call <SID>OptionG("sps", &sps) - call append("$", "mkspellmem\tamount of memory used by :mkspell before compressing") + call <SID>AddOption("mkspellmem", gettext("amount of memory used by :mkspell before compressing")) call <SID>OptionG("msm", &msm) endif -call <SID>Header("multiple windows") -call append("$", "laststatus\t0, 1, 2 or 3; when to use a status line for the last window") +call <SID>Header(gettext("multiple windows")) +call <SID>AddOption("laststatus", gettext("0, 1, 2 or 3; when to use a status line for the last window")) call append("$", " \tset ls=" . &ls) if has("statusline") - call append("$", "statusline\talternate format to be used for a status line") + call <SID>AddOption("statuscolumn", gettext("custom format for the status column")) + call append("$", "\t" .. s:local_to_window) + call <SID>OptionG("stc", &stc) + call <SID>AddOption("statusline", gettext("alternate format to be used for a status line")) call <SID>OptionG("stl", &stl) endif -call append("$", "equalalways\tmake all windows the same size when adding/removing windows") +call <SID>AddOption("equalalways", gettext("make all windows the same size when adding/removing windows")) call <SID>BinOptionG("ea", &ea) -call append("$", "eadirection\tin which direction 'equalalways' works: \"ver\", \"hor\" or \"both\"") +call <SID>AddOption("eadirection", gettext("in which direction 'equalalways' works: \"ver\", \"hor\" or \"both\"")) call <SID>OptionG("ead", &ead) -call append("$", "winheight\tminimal number of lines used for the current window") +call <SID>AddOption("winheight", gettext("minimal number of lines used for the current window")) call append("$", " \tset wh=" . &wh) -call append("$", "winminheight\tminimal number of lines used for any window") +call <SID>AddOption("winminheight", gettext("minimal number of lines used for any window")) call append("$", " \tset wmh=" . &wmh) -call append("$", "winfixheight\tkeep the height of the window") -call append("$", "\t(local to window)") +call <SID>AddOption("winfixheight", gettext("keep the height of the window")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("wfh") -call append("$", "winfixwidth\tkeep the width of the window") -call append("$", "\t(local to window)") +call <SID>AddOption("winfixwidth", gettext("keep the width of the window")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("wfw") -call append("$", "winwidth\tminimal number of columns used for the current window") +call <SID>AddOption("winwidth", gettext("minimal number of columns used for the current window")) call append("$", " \tset wiw=" . &wiw) -call append("$", "winminwidth\tminimal number of columns used for any window") +call <SID>AddOption("winminwidth", gettext("minimal number of columns used for any window")) call append("$", " \tset wmw=" . &wmw) -call append("$", "helpheight\tinitial height of the help window") +call <SID>AddOption("helpheight", gettext("initial height of the help window")) call append("$", " \tset hh=" . &hh) if has("quickfix") - " call append("$", "previewpopup\tuse a popup window for preview") + " call <SID>AddOption("previewpopup", gettext("use a popup window for preview")) " call append("$", " \tset pvp=" . &pvp) - call append("$", "previewheight\tdefault height for the preview window") + call <SID>AddOption("previewheight", gettext("default height for the preview window")) call append("$", " \tset pvh=" . &pvh) - call append("$", "previewwindow\tidentifies the preview window") - call append("$", "\t(local to window)") + call <SID>AddOption("previewwindow", gettext("identifies the preview window")) + call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("pvw") endif -call append("$", "hidden\tdon't unload a buffer when no longer shown in a window") +call <SID>AddOption("hidden", gettext("don't unload a buffer when no longer shown in a window")) call <SID>BinOptionG("hid", &hid) -call append("$", "switchbuf\t\"useopen\" and/or \"split\"; which window to use when jumping") -call append("$", "\tto a buffer") +call <SID>AddOption("switchbuf", gettext("\"useopen\" and/or \"split\"; which window to use when jumping\nto a buffer")) call <SID>OptionG("swb", &swb) -call append("$", "splitbelow\ta new window is put below the current one") +call <SID>AddOption("splitbelow", gettext("a new window is put below the current one")) call <SID>BinOptionG("sb", &sb) -call append("$", "splitright\ta new window is put right of the current one") +call <SID>AddOption("splitkeep", gettext("determines scroll behavior for split windows")) +call <SID>BinOptionG("spk", &spk) +call <SID>AddOption("splitright", gettext("a 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") -call append("$", "\t(local to window)") +call <SID>AddOption("scrollbind", gettext("this window scrolls together with other bound windows")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("scb") -call append("$", "scrollopt\t\"ver\", \"hor\" and/or \"jump\"; list of options for 'scrollbind'") +call <SID>AddOption("scrollopt", gettext("\"ver\", \"hor\" and/or \"jump\"; list of options for 'scrollbind'")) call <SID>OptionG("sbo", &sbo) -call append("$", "cursorbind\tthis window's cursor moves together with other bound windows") -call append("$", "\t(local to window)") +call <SID>AddOption("cursorbind", gettext("this window's cursor moves together with other bound windows")) +call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("crb") if has("terminal") - call append("$", "termsize\tsize of a terminal window") - call append("$", "\t(local to window)") + call <SID>AddOption("termsize", gettext("size of a terminal window")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("tms") - call append("$", "termkey\tkey that precedes Vim commands in a terminal window") - call append("$", "\t(local to window)") + call <SID>AddOption("termkey", gettext("key that precedes Vim commands in a terminal window")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("tk") endif -call <SID>Header("multiple tab pages") -call append("$", "showtabline\t0, 1 or 2; when to use a tab pages line") +call <SID>Header(gettext("multiple tab pages")) +call <SID>AddOption("showtabline", gettext("0, 1 or 2; when to use a tab pages line")) call append("$", " \tset stal=" . &stal) -call append("$", "tabpagemax\tmaximum number of tab pages to open for -p and \"tab all\"") +call <SID>AddOption("tabpagemax", gettext("maximum number of tab pages to open for -p and \"tab all\"")) call append("$", " \tset tpm=" . &tpm) -call append("$", "tabline\tcustom tab pages line") +call <SID>AddOption("tabline", gettext("custom tab pages line")) call <SID>OptionG("tal", &tal) if has("gui") - call append("$", "guitablabel\tcustom tab page label for the GUI") + call <SID>AddOption("guitablabel", gettext("custom tab page label for the GUI")) call <SID>OptionG("gtl", >l) - call append("$", "guitabtooltip\tcustom tab page tooltip for the GUI") + call <SID>AddOption("guitabtooltip", gettext("custom tab page tooltip for the GUI")) call <SID>OptionG("gtt", >t) endif -call <SID>Header("terminal") -call append("$", "scrolljump\tminimal number of lines to scroll at a time") +call <SID>Header(gettext("terminal")) +call <SID>AddOption("scrolljump", gettext("minimal number of lines to scroll at a time")) call append("$", " \tset sj=" . &sj) if has("gui") || has("msdos") || has("win32") - call append("$", "guicursor\tspecifies what the cursor looks like in different modes") + call <SID>AddOption("guicursor", gettext("specifies what the cursor looks like in different modes")) call <SID>OptionG("gcr", &gcr) endif if has("title") let &title = s:old_title - call append("$", "title\tshow info in the window title") + call <SID>AddOption("title", gettext("show info in the window title")) call <SID>BinOptionG("title", &title) set notitle - call append("$", "titlelen\tpercentage of 'columns' used for the window title") + call <SID>AddOption("titlelen", gettext("percentage of 'columns' used for the window title")) call append("$", " \tset titlelen=" . &titlelen) - call append("$", "titlestring\twhen not empty, string to be used for the window title") + call <SID>AddOption("titlestring", gettext("when not empty, string to be used for the window title")) call <SID>OptionG("titlestring", &titlestring) - call append("$", "titleold\tstring to restore the title to when exiting Vim") + call <SID>AddOption("titleold", gettext("string to restore the title to when exiting Vim")) call <SID>OptionG("titleold", &titleold) let &icon = s:old_icon - call append("$", "icon\tset the text of the icon for this window") + call <SID>AddOption("icon", gettext("set the text of the icon for this window")) call <SID>BinOptionG("icon", &icon) set noicon - call append("$", "iconstring\twhen not empty, text for the icon of this window") + call <SID>AddOption("iconstring", gettext("when not empty, text for the icon of this window")) call <SID>OptionG("iconstring", &iconstring) endif -call <SID>Header("using the mouse") -call append("$", "mouse\tlist of flags for using the mouse") +call <SID>Header(gettext("using the mouse")) +call <SID>AddOption("mouse", gettext("list of flags for using the mouse")) call <SID>OptionG("mouse", &mouse) if has("gui") - call append("$", "mousefocus\tthe window with the mouse pointer becomes the current one") + call <SID>AddOption("mousefocus", gettext("the window with the mouse pointer becomes the current one")) call <SID>BinOptionG("mousef", &mousef) - call append("$", "mousehide\thide the mouse pointer while typing") + call <SID>AddOption("mousehide", gettext("hide the mouse pointer while typing")) call <SID>BinOptionG("mh", &mh) endif -call append("$", "mousemodel\t\"extend\", \"popup\" or \"popup_setpos\"; what the right") -call append("$", "\tmouse button is used for") +call <SID>AddOption("mousemodel", gettext("\"extend\", \"popup\" or \"popup_setpos\"; what the right\nmouse button is used for")) call <SID>OptionG("mousem", &mousem) -call append("$", "mousetime\tmaximum time in msec to recognize a double-click") +call <SID>AddOption("mousetime", gettext("maximum time in msec to recognize a double-click")) call append("$", " \tset mouset=" . &mouset) if has("mouseshape") - call append("$", "mouseshape\twhat the mouse pointer looks like in different modes") + call <SID>AddOption("mouseshape", gettext("what the mouse pointer looks like in different modes")) call <SID>OptionG("mouses", &mouses) endif if has("gui") - call <SID>Header("GUI") - call append("$", "guifont\tlist of font names to be used in the GUI") + call <SID>Header(gettext("GUI")) + call <SID>AddOption("guifont", gettext("list of font names to be used in the GUI")) call <SID>OptionG("gfn", &gfn) if has("xfontset") - call append("$", "guifontset\tpair of fonts to be used, for multibyte editing") + call <SID>AddOption("guifontset", gettext("pair of fonts to be used, for multibyte editing")) call <SID>OptionG("gfs", &gfs) endif - call append("$", "guifontwide\tlist of font names to be used for double-wide characters") + call <SID>AddOption("guifontwide", gettext("list of font names to be used for double-wide characters")) call <SID>OptionG("gfw", &gfw) - call append("$", "guioptions\tlist of flags that specify how the GUI works") + call <SID>AddOption("guioptions", gettext("list of flags that specify how the GUI works")) call <SID>OptionG("go", &go) if has("gui_gtk") - call append("$", "toolbar\t\"icons\", \"text\" and/or \"tooltips\"; how to show the toolbar") + call <SID>AddOption("toolbar", gettext("\"icons\", \"text\" and/or \"tooltips\"; how to show the toolbar")) call <SID>OptionG("tb", &tb) if has("gui_gtk2") - call append("$", "toolbariconsize\tsize of toolbar icons") + call <SID>AddOption("toolbariconsize", gettext("size of toolbar icons")) call <SID>OptionG("tbis", &tbis) endif endif if has("browse") - call append("$", "browsedir\t\"last\", \"buffer\" or \"current\": which directory used for the file browser") + call <SID>AddOption("browsedir", gettext("\"last\", \"buffer\" or \"current\": which directory used for the file browser")) call <SID>OptionG("bsdir", &bsdir) endif if has("multi_lang") - call append("$", "langmenu\tlanguage to be used for the menus") + call <SID>AddOption("langmenu", gettext("language to be used for the menus")) call <SID>OptionG("langmenu", &lm) endif - call append("$", "menuitems\tmaximum number of items in one menu") + call <SID>AddOption("menuitems", gettext("maximum number of items in one menu")) call append("$", " \tset mis=" . &mis) if has("winaltkeys") - call append("$", "winaltkeys\t\"no\", \"yes\" or \"menu\"; how to use the ALT key") + call <SID>AddOption("winaltkeys", gettext("\"no\", \"yes\" or \"menu\"; how to use the ALT key")) call <SID>OptionG("wak", &wak) endif - call append("$", "linespace\tnumber of pixel lines to use between characters") + call <SID>AddOption("linespace", gettext("number of pixel lines to use between characters")) call append("$", " \tset lsp=" . &lsp) if has("balloon_eval") || has("balloon_eval_term") - call append("$", "balloondelay\tdelay in milliseconds before a balloon may pop up") + call <SID>AddOption("balloondelay", gettext("delay in milliseconds before a balloon may pop up")) call append("$", " \tset bdlay=" . &bdlay) if has("balloon_eval") - call append("$", "ballooneval\tuse balloon evaluation in the GUI") + call <SID>AddOption("ballooneval", gettext("use balloon evaluation in the GUI")) call <SID>BinOptionG("beval", &beval) endif if has("balloon_eval_term") - call append("$", "balloonevalterm\tuse balloon evaluation in the terminal") + call <SID>AddOption("balloonevalterm", gettext("use balloon evaluation in the terminal")) call <SID>BinOptionG("bevalterm", &beval) endif if has("eval") - call append("$", "balloonexpr\texpression to show in balloon eval") + call <SID>AddOption("balloonexpr", gettext("expression to show in balloon eval")) call append("$", " \tset bexpr=" . &bexpr) endif endif endif -if has("printer") - call <SID>Header("printing") - call append("$", "printoptions\tlist of items that control the format of :hardcopy output") - call <SID>OptionG("popt", &popt) - call append("$", "printdevice\tname of the printer to be used for :hardcopy") - call <SID>OptionG("pdev", &pdev) - if has("postscript") - call append("$", "printexpr\texpression used to print the PostScript file for :hardcopy") - call <SID>OptionG("pexpr", &pexpr) - endif - call append("$", "printfont\tname of the font to be used for :hardcopy") - call <SID>OptionG("pfn", &pfn) - call append("$", "printheader\tformat of the header used for :hardcopy") - call <SID>OptionG("pheader", &pheader) - if has("postscript") - call append("$", "printencoding\tencoding used to print the PostScript file for :hardcopy") - call <SID>OptionG("penc", &penc) - endif - call append("$", "printmbcharset\tthe CJK character set to be used for CJK output from :hardcopy") - call <SID>OptionG("pmbcs", &pmbcs) - call append("$", "printmbfont\tlist of font names to be used for CJK output from :hardcopy") - call <SID>OptionG("pmbfn", &pmbfn) -endif - -call <SID>Header("messages and info") -call append("$", "terse\tadd 's' flag in 'shortmess' (don't show search message)") +call <SID>Header(gettext("messages and info")) +call <SID>AddOption("terse", gettext("add 's' flag in 'shortmess' (don't show search message)")) call <SID>BinOptionG("terse", &terse) -call append("$", "shortmess\tlist of flags to make messages shorter") +call <SID>AddOption("shortmess", gettext("list of flags to make messages shorter")) call <SID>OptionG("shm", &shm) -call append("$", "showcmd\tshow (partial) command keys in the status line") +call <SID>AddOption("showcmd", gettext("show (partial) command keys in location given by 'showcmdloc'")) let &sc = s:old_sc call <SID>BinOptionG("sc", &sc) set nosc -call append("$", "showmode\tdisplay the current mode in the status line") +call <SID>AddOption("showcmdloc", gettext("location where to show the (partial) command keys for 'showcmd'")) + call <SID>OptionG("sloc", &sloc) +call <SID>AddOption("showmode", gettext("display the current mode in the status line")) call <SID>BinOptionG("smd", &smd) -call append("$", "ruler\tshow cursor position below each window") +call <SID>AddOption("ruler", gettext("show cursor position below each window")) let &ru = s:old_ru call <SID>BinOptionG("ru", &ru) set noru if has("statusline") - call append("$", "rulerformat\talternate format to be used for the ruler") + call <SID>AddOption("rulerformat", gettext("alternate format to be used for the ruler")) call <SID>OptionG("ruf", &ruf) endif -call append("$", "report\tthreshold for reporting number of changed lines") +call <SID>AddOption("report", gettext("threshold for reporting number of changed lines")) call append("$", " \tset report=" . &report) -call append("$", "verbose\tthe higher the more messages are given") +call <SID>AddOption("verbose", gettext("the higher the more messages are given")) call append("$", " \tset vbs=" . &vbs) -call append("$", "verbosefile\tfile to write messages in") +call <SID>AddOption("verbosefile", gettext("file to write messages in")) call <SID>OptionG("vfile", &vfile) -call append("$", "more\tpause listings when the screen is full") +call <SID>AddOption("more", gettext("pause listings when the screen is full")) call <SID>BinOptionG("more", &more) if has("dialog_con") || has("dialog_gui") - call append("$", "confirm\tstart a dialog when a command fails") + call <SID>AddOption("confirm", gettext("start a dialog when a command fails")) call <SID>BinOptionG("cf", &cf) endif -call append("$", "errorbells\tring the bell for error messages") +call <SID>AddOption("errorbells", gettext("ring the bell for error messages")) call <SID>BinOptionG("eb", &eb) -call append("$", "visualbell\tuse a visual bell instead of beeping") +call <SID>AddOption("visualbell", gettext("use a visual bell instead of beeping")) call <SID>BinOptionG("vb", &vb) -call append("$", "belloff\tdo not ring the bell for these reasons") +call <SID>AddOption("belloff", gettext("do not ring the bell for these reasons")) call <SID>OptionG("belloff", &belloff) if has("multi_lang") - call append("$", "helplang\tlist of preferred languages for finding help") + call <SID>AddOption("helplang", gettext("list of preferred languages for finding help")) call <SID>OptionG("hlg", &hlg) endif -call <SID>Header("selecting text") -call append("$", "selection\t\"old\", \"inclusive\" or \"exclusive\"; how selecting text behaves") +call <SID>Header(gettext("selecting text")) +call <SID>AddOption("selection", gettext("\"old\", \"inclusive\" or \"exclusive\"; how selecting text behaves")) call <SID>OptionG("sel", &sel) -call append("$", "selectmode\t\"mouse\", \"key\" and/or \"cmd\"; when to start Select mode") -call append("$", "\tinstead of Visual mode") +call <SID>AddOption("selectmode", gettext("\"mouse\", \"key\" and/or \"cmd\"; when to start Select mode\ninstead of Visual mode")) call <SID>OptionG("slm", &slm) if has("clipboard") - call append("$", "clipboard\t\"unnamed\" to use the * register like unnamed register") - call append("$", "\t\"autoselect\" to always put selected text on the clipboard") + call <SID>AddOption("clipboard", gettext("\"unnamed\" to use the * register like unnamed register\n\"autoselect\" to always put selected text on the clipboard")) call <SID>OptionG("cb", &cb) endif -call append("$", "keymodel\t\"startsel\" and/or \"stopsel\"; what special keys can do") +call <SID>AddOption("keymodel", gettext("\"startsel\" and/or \"stopsel\"; what special keys can do")) call <SID>OptionG("km", &km) -call <SID>Header("editing text") -call append("$", "undolevels\tmaximum number of changes that can be undone") -call append("$", "\t(global or local to buffer)") +call <SID>Header(gettext("editing text")) +call <SID>AddOption("undolevels", gettext("maximum number of changes that can be undone")) +call append("$", "\t" .. s:global_or_local) call append("$", " \tset ul=" . s:old_ul) -call append("$", "undofile\tautomatically save and restore undo history") +call <SID>AddOption("undofile", gettext("automatically save and restore undo history")) call <SID>BinOptionG("udf", &udf) -call append("$", "undodir\tlist of directories for undo files") +call <SID>AddOption("undodir", gettext("list of directories for undo files")) call <SID>OptionG("udir", &udir) -call append("$", "undoreload\tmaximum number lines to save for undo on a buffer reload") +call <SID>AddOption("undoreload", gettext("maximum number lines to save for undo on a buffer reload")) call append("$", " \tset ur=" . &ur) -call append("$", "modified\tchanges have been made and not written to a file") +call <SID>AddOption("modified", gettext("changes have been made and not written to a file")) call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("mod") -call append("$", "readonly\tbuffer is not to be written") +call <SID>AddOption("readonly", gettext("buffer is not to be written")) call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("ro") -call <SID>AddOption("modifiable", "changes to the text are possible") +call <SID>AddOption("modifiable", gettext("changes to the text are possible")) call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("ma") -call append("$", "textwidth\tline length above which to break a line") +call <SID>AddOption("textwidth", gettext("line length above which to break a line")) call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("tw") -call append("$", "wrapmargin\tmargin from the right in which to break a line") +call <SID>AddOption("wrapmargin", gettext("margin from the right in which to break a line")) call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("wm") -call append("$", "backspace\tspecifies what <BS>, CTRL-W, etc. can do in Insert mode") +call <SID>AddOption("backspace", gettext("specifies what <BS>, CTRL-W, etc. can do in Insert mode")) call append("$", " \tset bs=" . &bs) -call append("$", "comments\tdefinition of what comment lines look like") -call append("$", "\t(local to buffer)") +call <SID>AddOption("comments", gettext("definition of what comment lines look like")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("com") -call append("$", "formatoptions\tlist of flags that tell how automatic formatting works") -call append("$", "\t(local to buffer)") +call <SID>AddOption("formatoptions", gettext("list of flags that tell how automatic formatting works")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("fo") -call append("$", "formatlistpat\tpattern to recognize a numbered list") -call append("$", "\t(local to buffer)") +call <SID>AddOption("formatlistpat", gettext("pattern to recognize a numbered list")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("flp") if has("eval") - call append("$", "formatexpr\texpression used for \"gq\" to format lines") - call append("$", "\t(local to buffer)") + call <SID>AddOption("formatexpr", gettext("expression used for \"gq\" to format lines")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("fex") endif if has("insert_expand") - call append("$", "complete\tspecifies how Insert mode completion works for CTRL-N and CTRL-P") - call append("$", "\t(local to buffer)") + call <SID>AddOption("complete", gettext("specifies how Insert mode completion works for CTRL-N and CTRL-P")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("cpt") - call append("$", "completeopt\twhether to use a popup menu for Insert mode completion") + call <SID>AddOption("completeopt", gettext("whether to use a popup menu for Insert mode completion")) call <SID>OptionG("cot", &cot) - call append("$", "pumheight\tmaximum height of the popup menu") + call <SID>AddOption("pumheight", gettext("maximum height of the popup menu")) call <SID>OptionG("ph", &ph) - if exists("&pw") - call append("$", "pumwidth\tminimum width of the popup menu") - call <SID>OptionG("pw", &pw) - endif - call append("$", "completefunc\tuser defined function for Insert mode completion") - call append("$", "\t(local to buffer)") + call <SID>AddOption("pumwidth", gettext("minimum width of the popup menu")) + call <SID>OptionG("pw", &pw) + call <SID>AddOption("completefunc", gettext("user defined function for Insert mode completion")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("cfu") - call append("$", "omnifunc\tfunction for filetype-specific Insert mode completion") - call append("$", "\t(local to buffer)") + call <SID>AddOption("omnifunc", gettext("function for filetype-specific Insert mode completion")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("ofu") - call append("$", "dictionary\tlist of dictionary files for keyword completion") - call append("$", "\t(global or local to buffer)") + call <SID>AddOption("dictionary", gettext("list of dictionary files for keyword completion")) + call append("$", "\t" .. s:global_or_local) call <SID>OptionG("dict", &dict) - call append("$", "thesaurus\tlist of thesaurus files for keyword completion") - call append("$", "\t(global or local to buffer)") + call <SID>AddOption("thesaurus", gettext("list of thesaurus files for keyword completion")) + call append("$", "\t" .. s:global_or_local) call <SID>OptionG("tsr", &tsr) + call <SID>AddOption("thesaurusfunc", gettext("function used for thesaurus completion")) + call append("$", "\t" .. s:global_or_local) + call <SID>OptionG("tsrfu", &tsrfu) endif -call append("$", "infercase\tadjust case of a keyword completion match") -call append("$", "\t(local to buffer)") +call <SID>AddOption("infercase", gettext("adjust case of a keyword completion match")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("inf") if has("digraphs") - call append("$", "digraph\tenable entering digraphs with c1 <BS> c2") + call <SID>AddOption("digraph", gettext("enable entering digraphs with c1 <BS> c2")) call <SID>BinOptionG("dg", &dg) endif -call append("$", "tildeop\tthe \"~\" command behaves like an operator") +call <SID>AddOption("tildeop", gettext("the \"~\" command behaves like an operator")) call <SID>BinOptionG("top", &top) -call <SID>AddOption("operatorfunc", "function called for the \"g@\" operator") +call <SID>AddOption("operatorfunc", gettext("function called for the \"g@\" operator")) call <SID>OptionG("opfunc", &opfunc) -call append("$", "showmatch\twhen inserting a bracket, briefly jump to its match") +call <SID>AddOption("showmatch", gettext("when inserting a bracket, briefly jump to its match")) call <SID>BinOptionG("sm", &sm) -call append("$", "matchtime\ttenth of a second to show a match for 'showmatch'") +call <SID>AddOption("matchtime", gettext("tenth of a second to show a match for 'showmatch'")) call append("$", " \tset mat=" . &mat) -call append("$", "matchpairs\tlist of pairs that match for the \"%\" command") +call <SID>AddOption("matchpairs", gettext("list of pairs that match for the \"%\" command")) call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("mps") -call append("$", "joinspaces\tuse two spaces after '.' when joining a line") +call <SID>AddOption("joinspaces", gettext("use two spaces after '.' when joining a line")) call <SID>BinOptionG("js", &js) -call <SID>AddOption("nrformats", "\"alpha\", \"octal\", \"hex\", \"bin\" and/or \"unsigned\"; number formats\nrecognized for CTRL-A and CTRL-X commands") +call <SID>AddOption("nrformats", gettext("\"alpha\", \"octal\", \"hex\", \"bin\" and/or \"unsigned\"; number formats\nrecognized for CTRL-A and CTRL-X commands")) call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("nf") -call <SID>Header("tabs and indenting") -call append("$", "tabstop\tnumber of spaces a <Tab> in the text stands for") -call append("$", "\t(local to buffer)") +call <SID>Header(gettext("tabs and indenting")) +call <SID>AddOption("tabstop", gettext("number of spaces a <Tab> in the text stands for")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("ts") -call append("$", "shiftwidth\tnumber of spaces used for each step of (auto)indent") -call append("$", "\t(local to buffer)") +call <SID>AddOption("shiftwidth", gettext("number of spaces used for each step of (auto)indent")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("sw") if has("vartabs") - call append("$", "vartabstop\tlist of number of spaces a tab counts for") - call append("$", "\t(local to buffer)") + call <SID>AddOption("vartabstop", gettext("list of number of spaces a tab counts for")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("vts") - call append("$", "varsofttabstop\tlist of number of spaces a soft tabsstop counts for") - call append("$", "\t(local to buffer)") + call <SID>AddOption("varsofttabstop", gettext("list of number of spaces a soft tabsstop counts for")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("vsts") endif -call append("$", "smarttab\ta <Tab> in an indent inserts 'shiftwidth' spaces") +call <SID>AddOption("smarttab", gettext("a <Tab> in an indent inserts 'shiftwidth' spaces")) call <SID>BinOptionG("sta", &sta) -call append("$", "softtabstop\tif non-zero, number of spaces to insert for a <Tab>") -call append("$", "\t(local to buffer)") +call <SID>AddOption("softtabstop", gettext("if non-zero, number of spaces to insert for a <Tab>")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("sts") -call append("$", "shiftround\tround to 'shiftwidth' for \"<<\" and \">>\"") +call <SID>AddOption("shiftround", gettext("round to 'shiftwidth' for \"<<\" and \">>\"")) call <SID>BinOptionG("sr", &sr) -call append("$", "expandtab\texpand <Tab> to spaces in Insert mode") -call append("$", "\t(local to buffer)") +call <SID>AddOption("expandtab", gettext("expand <Tab> to spaces in Insert mode")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("et") -call append("$", "autoindent\tautomatically set the indent of a new line") -call append("$", "\t(local to buffer)") +call <SID>AddOption("autoindent", gettext("automatically set the indent of a new line")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("ai") if has("smartindent") - call append("$", "smartindent\tdo clever autoindenting") - call append("$", "\t(local to buffer)") + call <SID>AddOption("smartindent", gettext("do clever autoindenting")) + call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("si") endif if has("cindent") - call append("$", "cindent\tenable specific indenting for C code") - call append("$", "\t(local to buffer)") + call <SID>AddOption("cindent", gettext("enable specific indenting for C code")) + call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("cin") - call append("$", "cinoptions\toptions for C-indenting") - call append("$", "\t(local to buffer)") + call <SID>AddOption("cinoptions", gettext("options for C-indenting")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("cino") - call append("$", "cinkeys\tkeys that trigger C-indenting in Insert mode") - call append("$", "\t(local to buffer)") + call <SID>AddOption("cinkeys", gettext("keys that trigger C-indenting in Insert mode")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("cink") - call append("$", "cinwords\tlist of words that cause more C-indent") - call append("$", "\t(local to buffer)") + call <SID>AddOption("cinwords", gettext("list of words that cause more C-indent")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("cinw") - call append("$", "cinscopedecls\tlist of scope declaration names used by cino-g") - call append("$", "\t(local to buffer)") + call <SID>AddOption("cinscopedecls", gettext("list of scope declaration names used by cino-g")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("cinsd") - call append("$", "indentexpr\texpression used to obtain the indent of a line") - call append("$", "\t(local to buffer)") + call <SID>AddOption("indentexpr", gettext("expression used to obtain the indent of a line")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("inde") - call append("$", "indentkeys\tkeys that trigger indenting with 'indentexpr' in Insert mode") - call append("$", "\t(local to buffer)") + call <SID>AddOption("indentkeys", gettext("keys that trigger indenting with 'indentexpr' in Insert mode")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("indk") endif -call append("$", "copyindent\tcopy whitespace for indenting from previous line") -call append("$", "\t(local to buffer)") +call <SID>AddOption("copyindent", gettext("copy whitespace for indenting from previous line")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("ci") -call append("$", "preserveindent\tpreserve kind of whitespace when changing indent") -call append("$", "\t(local to buffer)") +call <SID>AddOption("preserveindent", gettext("preserve kind of whitespace when changing indent")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("pi") if has("lispindent") - call append("$", "lisp\tenable lisp mode") - call append("$", "\t(local to buffer)") + call <SID>AddOption("lisp", gettext("enable lisp mode")) + call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("lisp") - call append("$", "lispwords\twords that change how lisp indenting works") + call <SID>AddOption("lispwords", gettext("words that change how lisp indenting works")) call <SID>OptionL("lw") + call <SID>AddOption("lispoptions", gettext("options for Lisp indenting")) + call <SID>OptionL("lop") endif if has("folding") - call <SID>Header("folding") - call <SID>AddOption("foldenable", "unset to display all folds open") + call <SID>Header(gettext("folding")) + call <SID>AddOption("foldenable", gettext("unset to display all folds open")) call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("fen") - call append("$", "foldlevel\tfolds with a level higher than this number will be closed") + call <SID>AddOption("foldlevel", gettext("folds with a level higher than this number will be closed")) call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fdl") - call append("$", "foldlevelstart\tvalue for 'foldlevel' when starting to edit a file") + call <SID>AddOption("foldlevelstart", gettext("value for 'foldlevel' when starting to edit a file")) call append("$", " \tset fdls=" . &fdls) - call append("$", "foldcolumn\twidth of the column used to indicate folds") - call append("$", "\t(local to window)") + call <SID>AddOption("foldcolumn", gettext("width of the column used to indicate folds")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fdc") - call append("$", "foldtext\texpression used to display the text of a closed fold") - call append("$", "\t(local to window)") + call <SID>AddOption("foldtext", gettext("expression used to display the text of a closed fold")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fdt") - call append("$", "foldclose\tset to \"all\" to close a fold when the cursor leaves it") + call <SID>AddOption("foldclose", gettext("set to \"all\" to close a fold when the cursor leaves it")) call <SID>OptionG("fcl", &fcl) - call append("$", "foldopen\tspecifies for which commands a fold will be opened") + call <SID>AddOption("foldopen", gettext("specifies for which commands a fold will be opened")) call <SID>OptionG("fdo", &fdo) - call append("$", "foldminlines\tminimum number of screen lines for a fold to be closed") - call append("$", "\t(local to window)") + call <SID>AddOption("foldminlines", gettext("minimum number of screen lines for a fold to be closed")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fml") - call append("$", "commentstring\ttemplate for comments; used to put the marker in") + call <SID>AddOption("commentstring", gettext("template for comments; used to put the marker in")) call <SID>OptionL("cms") - call <SID>AddOption("foldmethod", "folding type: \"manual\", \"indent\", \"expr\", \"marker\",\n\"syntax\" or \"diff\"") + call <SID>AddOption("foldmethod", gettext("folding type: \"manual\", \"indent\", \"expr\", \"marker\",\n\"syntax\" or \"diff\"")) call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fdm") - call append("$", "foldexpr\texpression used when 'foldmethod' is \"expr\"") + call <SID>AddOption("foldexpr", gettext("expression used when 'foldmethod' is \"expr\"")) call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fde") - call append("$", "foldignore\tused to ignore lines when 'foldmethod' is \"indent\"") + call <SID>AddOption("foldignore", gettext("used to ignore lines when 'foldmethod' is \"indent\"")) call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fdi") - call append("$", "foldmarker\tmarkers used when 'foldmethod' is \"marker\"") + call <SID>AddOption("foldmarker", gettext("markers used when 'foldmethod' is \"marker\"")) call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fmr") - call append("$", "foldnestmax\tmaximum fold depth for when 'foldmethod' is \"indent\" or \"syntax\"") + call <SID>AddOption("foldnestmax", gettext("maximum fold depth for when 'foldmethod' is \"indent\" or \"syntax\"")) call append("$", "\t" .. s:local_to_window) call <SID>OptionL("fdn") endif if has("diff") - call <SID>Header("diff mode") - call append("$", "diff\tuse diff mode for the current window") - call append("$", "\t(local to window)") + call <SID>Header(gettext("diff mode")) + call <SID>AddOption("diff", gettext("use diff mode for the current window")) + call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("diff") - call append("$", "diffopt\toptions for using diff mode") + call <SID>AddOption("diffopt", gettext("options for using diff mode")) call <SID>OptionG("dip", &dip) - call append("$", "diffexpr\texpression used to obtain a diff file") + call <SID>AddOption("diffexpr", gettext("expression used to obtain a diff file")) call <SID>OptionG("dex", &dex) - call append("$", "patchexpr\texpression used to patch a file") + call <SID>AddOption("patchexpr", gettext("expression used to patch a file")) call <SID>OptionG("pex", &pex) endif -call <SID>Header("mapping") -call append("$", "maxmapdepth\tmaximum depth of mapping") +call <SID>Header(gettext("mapping")) +call <SID>AddOption("maxmapdepth", gettext("maximum depth of mapping")) call append("$", " \tset mmd=" . &mmd) -call append("$", "remap\trecognize mappings in mapped keys") -call append("$", "timeout\tallow timing out halfway into a mapping") +call <SID>AddOption("timeout", gettext("allow timing out halfway into a mapping")) call <SID>BinOptionG("to", &to) -call append("$", "ttimeout\tallow timing out halfway into a key code") +call <SID>AddOption("ttimeout", gettext("allow timing out halfway into a key code")) call <SID>BinOptionG("ttimeout", &ttimeout) -call append("$", "timeoutlen\ttime in msec for 'timeout'") +call <SID>AddOption("timeoutlen", gettext("time in msec for 'timeout'")) call append("$", " \tset tm=" . &tm) -call append("$", "ttimeoutlen\ttime in msec for 'ttimeout'") +call <SID>AddOption("ttimeoutlen", gettext("time in msec for 'ttimeout'")) call append("$", " \tset ttm=" . &ttm) -call <SID>Header("reading and writing files") -call append("$", "modeline\tenable using settings from modelines when reading a file") -call append("$", "\t(local to buffer)") +call <SID>Header(gettext("reading and writing files")) +call <SID>AddOption("modeline", gettext("enable using settings from modelines when reading a file")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("ml") -call append("$", "modelineexpr\tallow setting expression options from a modeline") +call <SID>AddOption("modelineexpr", gettext("allow setting expression options from a modeline")) call <SID>BinOptionG("mle", &mle) -call append("$", "modelines\tnumber of lines to check for modelines") +call <SID>AddOption("modelines", gettext("number of lines to check for modelines")) call append("$", " \tset mls=" . &mls) -call append("$", "binary\tbinary file editing") -call append("$", "\t(local to buffer)") +call <SID>AddOption("binary", gettext("binary file editing")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("bin") -call append("$", "endofline\tlast line in the file has an end-of-line") -call append("$", "\t(local to buffer)") +call <SID>AddOption("endofline", gettext("last line in the file has an end-of-line")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("eol") -call append("$", "fixendofline\tfixes missing end-of-line at end of text file") -call append("$", "\t(local to buffer)") +call <SID>AddOption("endoffile", gettext("last line in the file followed by CTRL-Z")) +call append("$", "\t" .. s:local_to_buffer) +call <SID>BinOptionL("eof") +call <SID>AddOption("fixendofline", gettext("fixes missing end-of-line at end of text file")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("fixeol") -call append("$", "bomb\tprepend a Byte Order Mark to the file") -call append("$", "\t(local to buffer)") +call <SID>AddOption("bomb", gettext("prepend a Byte Order Mark to the file")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("bomb") -call append("$", "fileformat\tend-of-line format: \"dos\", \"unix\" or \"mac\"") -call append("$", "\t(local to buffer)") +call <SID>AddOption("fileformat", gettext("end-of-line format: \"dos\", \"unix\" or \"mac\"")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("ff") -call append("$", "fileformats\tlist of file formats to look for when editing a file") +call <SID>AddOption("fileformats", gettext("list of file formats to look for when editing a file")) call <SID>OptionG("ffs", &ffs) -call append("$", "\t(local to buffer)") -call append("$", "write\twriting files is allowed") +call <SID>AddOption("write", gettext("writing files is allowed")) call <SID>BinOptionG("write", &write) -call append("$", "writebackup\twrite a backup file before overwriting a file") +call <SID>AddOption("writebackup", gettext("write a backup file before overwriting a file")) call <SID>BinOptionG("wb", &wb) -call append("$", "backup\tkeep a backup after overwriting a file") +call <SID>AddOption("backup", gettext("keep a backup after overwriting a file")) call <SID>BinOptionG("bk", &bk) -call append("$", "backupskip\tpatterns that specify for which files a backup is not made") +call <SID>AddOption("backupskip", gettext("patterns that specify for which files a backup is not made")) call append("$", " \tset bsk=" . &bsk) -call append("$", "backupcopy\twhether to make the backup as a copy or rename the existing file") -call append("$", "\t(global or local to buffer)") +call <SID>AddOption("backupcopy", gettext("whether to make the backup as a copy or rename the existing file")) +call append("$", "\t" .. s:global_or_local) call append("$", " \tset bkc=" . &bkc) -call append("$", "backupdir\tlist of directories to put backup files in") +call <SID>AddOption("backupdir", gettext("list of directories to put backup files in")) call <SID>OptionG("bdir", &bdir) -call append("$", "backupext\tfile name extension for the backup file") +call <SID>AddOption("backupext", gettext("file name extension for the backup file")) call <SID>OptionG("bex", &bex) -call append("$", "autowrite\tautomatically write a file when leaving a modified buffer") +call <SID>AddOption("autowrite", gettext("automatically write a file when leaving a modified buffer")) call <SID>BinOptionG("aw", &aw) -call append("$", "autowriteall\tas 'autowrite', but works with more commands") +call <SID>AddOption("autowriteall", gettext("as 'autowrite', but works with more commands")) call <SID>BinOptionG("awa", &awa) -call append("$", "writeany\talways write without asking for confirmation") +call <SID>AddOption("writeany", gettext("always write without asking for confirmation")) call <SID>BinOptionG("wa", &wa) -call append("$", "autoread\tautomatically read a file when it was modified outside of Vim") -call append("$", "\t(global or local to buffer)") +call <SID>AddOption("autoread", gettext("automatically read a file when it was modified outside of Vim")) +call append("$", "\t" .. s:global_or_local) call <SID>BinOptionG("ar", &ar) -call append("$", "patchmode\tkeep oldest version of a file; specifies file name extension") +call <SID>AddOption("patchmode", gettext("keep oldest version of a file; specifies file name extension")) call <SID>OptionG("pm", &pm) -call append("$", "fsync\tforcibly sync the file to disk after writing it") +call <SID>AddOption("fsync", gettext("forcibly sync the file to disk after writing it")) call <SID>BinOptionG("fs", &fs) -call <SID>Header("the swap file") -call append("$", "directory\tlist of directories for the swap file") +call <SID>Header(gettext("the swap file")) +call <SID>AddOption("directory", gettext("list of directories for the swap file")) call <SID>OptionG("dir", &dir) -call append("$", "swapfile\tuse a swap file for this buffer") -call append("$", "\t(local to buffer)") +call <SID>AddOption("swapfile", gettext("use a swap file for this buffer")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("swf") -call append("$", "updatecount\tnumber of characters typed to cause a swap file update") +call <SID>AddOption("updatecount", gettext("number of characters typed to cause a swap file update")) call append("$", " \tset uc=" . &uc) -call append("$", "updatetime\ttime in msec after which the swap file will be updated") +call <SID>AddOption("updatetime", gettext("time in msec after which the swap file will be updated")) call append("$", " \tset ut=" . &ut) -call <SID>Header("command line editing") -call <SID>AddOption("history", "how many command lines are remembered") +call <SID>Header(gettext("command line editing")) +call <SID>AddOption("history", gettext("how many command lines are remembered")) call append("$", " \tset hi=" . &hi) -call append("$", "wildchar\tkey that triggers command-line expansion") +call <SID>AddOption("wildchar", gettext("key that triggers command-line expansion")) call append("$", " \tset wc=" . &wc) -call append("$", "wildcharm\tlike 'wildchar' but can also be used in a mapping") +call <SID>AddOption("wildcharm", gettext("like 'wildchar' but can also be used in a mapping")) call append("$", " \tset wcm=" . &wcm) -call append("$", "wildmode\tspecifies how command line completion works") +call <SID>AddOption("wildmode", gettext("specifies how command line completion works")) call <SID>OptionG("wim", &wim) if has("wildoptions") - call append("$", "wildoptions\tempty or \"tagfile\" to list file name of matching tags") + call <SID>AddOption("wildoptions", gettext("empty or \"tagfile\" to list file name of matching tags")) call <SID>OptionG("wop", &wop) endif -call append("$", "suffixes\tlist of file name extensions that have a lower priority") +call <SID>AddOption("suffixes", gettext("list of file name extensions that have a lower priority")) call <SID>OptionG("su", &su) if has("file_in_path") - call append("$", "suffixesadd\tlist of file name extensions added when searching for a file") - call append("$", "\t(local to buffer)") + call <SID>AddOption("suffixesadd", gettext("list of file name extensions added when searching for a file")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("sua") endif if has("wildignore") - call append("$", "wildignore\tlist of patterns to ignore files for file name completion") + call <SID>AddOption("wildignore", gettext("list of patterns to ignore files for file name completion")) call <SID>OptionG("wig", &wig) endif -call append("$", "fileignorecase\tignore case when using file names") +call <SID>AddOption("fileignorecase", gettext("ignore case when using file names")) call <SID>BinOptionG("fic", &fic) -call append("$", "wildignorecase\tignore case when completing file names") +call <SID>AddOption("wildignorecase", gettext("ignore case when completing file names")) call <SID>BinOptionG("wic", &wic) if has("wildmenu") - call append("$", "wildmenu\tcommand-line completion shows a list of matches") + call <SID>AddOption("wildmenu", gettext("command-line completion shows a list of matches")) call <SID>BinOptionG("wmnu", &wmnu) endif -call append("$", "cedit\tkey used to open the command-line window") +call <SID>AddOption("cedit", gettext("key used to open the command-line window")) call <SID>OptionG("cedit", &cedit) -call append("$", "cmdwinheight\theight of the command-line window") +call <SID>AddOption("cmdwinheight", gettext("height of the command-line window")) call <SID>OptionG("cwh", &cwh) -call <SID>Header("executing external commands") -call append("$", "shell\tname of the shell program used for external commands") +call <SID>Header(gettext("executing external commands")) +call <SID>AddOption("shell", gettext("name of the shell program used for external commands")) call <SID>OptionG("sh", &sh) -call append("$", "shellquote\tcharacter(s) to enclose a shell command in") +call <SID>AddOption("shellquote", gettext("character(s) to enclose a shell command in")) call <SID>OptionG("shq", &shq) -call append("$", "shellxquote\tlike 'shellquote' but include the redirection") +call <SID>AddOption("shellxquote", gettext("like 'shellquote' but include the redirection")) call <SID>OptionG("sxq", &sxq) -call append("$", "shellxescape\tcharacters to escape when 'shellxquote' is (") +call <SID>AddOption("shellxescape", gettext("characters to escape when 'shellxquote' is (")) call <SID>OptionG("sxe", &sxe) -call append("$", "shellcmdflag\targument for 'shell' to execute a command") +call <SID>AddOption("shellcmdflag", gettext("argument for 'shell' to execute a command")) call <SID>OptionG("shcf", &shcf) -call append("$", "shellredir\tused to redirect command output to a file") +call <SID>AddOption("shellredir", gettext("used to redirect command output to a file")) call <SID>OptionG("srr", &srr) -call append("$", "shelltemp\tuse a temp file for shell commands instead of using a pipe") +call <SID>AddOption("shelltemp", gettext("use a temp file for shell commands instead of using a pipe")) call <SID>BinOptionG("stmp", &stmp) -call append("$", "equalprg\tprogram used for \"=\" command") -call append("$", "\t(global or local to buffer)") +call <SID>AddOption("equalprg", gettext("program used for \"=\" command")) +call append("$", "\t" .. s:global_or_local) call <SID>OptionG("ep", &ep) -call append("$", "formatprg\tprogram used to format lines with \"gq\" command") +call <SID>AddOption("formatprg", gettext("program used to format lines with \"gq\" command")) call <SID>OptionG("fp", &fp) -call append("$", "keywordprg\tprogram used for the \"K\" command") +call <SID>AddOption("keywordprg", gettext("program used for the \"K\" command")) call <SID>OptionG("kp", &kp) -call append("$", "warn\twarn when using a shell command and a buffer has changes") +call <SID>AddOption("warn", gettext("warn when using a shell command and a buffer has changes")) call <SID>BinOptionG("warn", &warn) if has("quickfix") - call <SID>Header("running make and jumping to errors (quickfix)") - call append("$", "errorfile\tname of the file that contains error messages") + call <SID>Header(gettext("running make and jumping to errors (quickfix)")) + call <SID>AddOption("errorfile", gettext("name of the file that contains error messages")) call <SID>OptionG("ef", &ef) - call append("$", "errorformat\tlist of formats for error messages") - call append("$", "\t(global or local to buffer)") + call <SID>AddOption("errorformat", gettext("list of formats for error messages")) + call append("$", "\t" .. s:global_or_local) call <SID>OptionG("efm", &efm) - call append("$", "makeprg\tprogram used for the \":make\" command") - call append("$", "\t(global or local to buffer)") + call <SID>AddOption("makeprg", gettext("program used for the \":make\" command")) + call append("$", "\t" .. s:global_or_local) call <SID>OptionG("mp", &mp) - call append("$", "shellpipe\tstring used to put the output of \":make\" in the error file") + call <SID>AddOption("shellpipe", gettext("string used to put the output of \":make\" in the error file")) call <SID>OptionG("sp", &sp) - call append("$", "makeef\tname of the errorfile for the 'makeprg' command") + call <SID>AddOption("makeef", gettext("name of the errorfile for the 'makeprg' command")) call <SID>OptionG("mef", &mef) - call append("$", "grepprg\tprogram used for the \":grep\" command") - call append("$", "\t(global or local to buffer)") + call <SID>AddOption("grepprg", gettext("program used for the \":grep\" command")) + call append("$", "\t" .. s:global_or_local) call <SID>OptionG("gp", &gp) - call append("$", "grepformat\tlist of formats for output of 'grepprg'") + call <SID>AddOption("grepformat", gettext("list of formats for output of 'grepprg'")) call <SID>OptionG("gfm", &gfm) - call append("$", "makeencoding\tencoding of the \":make\" and \":grep\" output") - call append("$", "\t(global or local to buffer)") + call <SID>AddOption("makeencoding", gettext("encoding of the \":make\" and \":grep\" output")) + call append("$", "\t" .. s:global_or_local) call <SID>OptionG("menc", &menc) endif if has("win32") - call <SID>Header("system specific") - call <SID>AddOption("shellslash", "use forward slashes in file names; for Unix-like shells") + call <SID>Header(gettext("system specific")) + call <SID>AddOption("shellslash", gettext("use forward slashes in file names; for Unix-like shells")) call <SID>BinOptionG("ssl", &ssl) - call <SID>AddOption("completeslash", "specifies slash/backslash used for completion") + call <SID>AddOption("completeslash", gettext("specifies slash/backslash used for completion")) call <SID>OptionG("csl", &csl) endif -call <SID>Header("language specific") -call append("$", "isfname\tspecifies the characters in a file name") +call <SID>Header(gettext("language specific")) +call <SID>AddOption("isfname", gettext("specifies the characters in a file name")) call <SID>OptionG("isf", &isf) -call append("$", "isident\tspecifies the characters in an identifier") +call <SID>AddOption("isident", gettext("specifies the characters in an identifier")) call <SID>OptionG("isi", &isi) -call append("$", "iskeyword\tspecifies the characters in a keyword") -call append("$", "\t(local to buffer)") +call <SID>AddOption("iskeyword", gettext("specifies the characters in a keyword")) +call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("isk") -call append("$", "isprint\tspecifies printable characters") +call <SID>AddOption("isprint", gettext("specifies printable characters")) call <SID>OptionG("isp", &isp) if has("textobjects") - call append("$", "quoteescape\tspecifies escape characters in a string") - call append("$", "\t(local to buffer)") + call <SID>AddOption("quoteescape", gettext("specifies escape characters in a string")) + call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("qe") endif if has("rightleft") - call append("$", "rightleft\tdisplay the buffer right-to-left") - call append("$", "\t(local to window)") + call <SID>AddOption("rightleft", gettext("display the buffer right-to-left")) + call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("rl") - call append("$", "rightleftcmd\twhen to edit the command-line right-to-left") - call append("$", "\t(local to window)") + call <SID>AddOption("rightleftcmd", gettext("when to edit the command-line right-to-left")) + call append("$", "\t" .. s:local_to_window) call <SID>OptionL("rlc") - call append("$", "revins\tinsert characters backwards") + call <SID>AddOption("revins", gettext("insert characters backwards")) call <SID>BinOptionG("ri", &ri) - call append("$", "allowrevins\tallow CTRL-_ in Insert and Command-line mode to toggle 'revins'") + call <SID>AddOption("allowrevins", gettext("allow CTRL-_ in Insert and Command-line mode to toggle 'revins'")) call <SID>BinOptionG("ari", &ari) - call append("$", "aleph\tthe ASCII code for the first letter of the Hebrew alphabet") + call <SID>AddOption("aleph", gettext("the ASCII code for the first letter of the Hebrew alphabet")) call append("$", " \tset al=" . &al) - call append("$", "hkmap\tuse Hebrew keyboard mapping") + call <SID>AddOption("hkmap", gettext("use Hebrew keyboard mapping")) call <SID>BinOptionG("hk", &hk) - call append("$", "hkmapp\tuse phonetic Hebrew keyboard mapping") + call <SID>AddOption("hkmapp", gettext("use phonetic Hebrew keyboard mapping")) call <SID>BinOptionG("hkp", &hkp) endif if has("arabic") - call append("$", "arabic\tprepare for editing Arabic text") - call append("$", "\t(local to window)") + call <SID>AddOption("arabic", gettext("prepare for editing Arabic text")) + call append("$", "\t" .. s:local_to_window) call <SID>BinOptionL("arab") - call append("$", "arabicshape\tperform shaping of Arabic characters") + call <SID>AddOption("arabicshape", gettext("perform shaping of Arabic characters")) call <SID>BinOptionG("arshape", &arshape) - call append("$", "termbidi\tterminal will perform bidi handling") + call <SID>AddOption("termbidi", gettext("terminal will perform bidi handling")) call <SID>BinOptionG("tbidi", &tbidi) endif if has("keymap") - call append("$", "keymap\tname of a keyboard mapping") + call <SID>AddOption("keymap", gettext("name of a keyboard mapping")) call <SID>OptionL("kmp") endif if has("langmap") - call append("$", "langmap\tlist of characters that are translated in Normal mode") + call <SID>AddOption("langmap", gettext("list of characters that are translated in Normal mode")) call <SID>OptionG("lmap", &lmap) - call append("$", "langremap\tapply 'langmap' to mapped characters") + call <SID>AddOption("langremap", gettext("apply 'langmap' to mapped characters")) call <SID>BinOptionG("lrm", &lrm) endif if has("xim") - call append("$", "imdisable\twhen set never use IM; overrules following IM options") + call <SID>AddOption("imdisable", gettext("when set never use IM; overrules following IM options")) call <SID>BinOptionG("imd", &imd) endif -call append("$", "iminsert\tin Insert mode: 1: use :lmap; 2: use IM; 0: neither") -call append("$", "\t(local to window)") +call <SID>AddOption("iminsert", gettext("in Insert mode: 1: use :lmap; 2: use IM; 0: neither")) +call append("$", "\t" .. s:local_to_window) call <SID>OptionL("imi") -call append("$", "imsearch\tentering a search pattern: 1: use :lmap; 2: use IM; 0: neither") -call append("$", "\t(local to window)") +call <SID>AddOption("imsearch", gettext("entering a search pattern: 1: use :lmap; 2: use IM; 0: neither")) +call append("$", "\t" .. s:local_to_window) call <SID>OptionL("ims") if has("xim") - call append("$", "imcmdline\twhen set always use IM when starting to edit a command line") + call <SID>AddOption("imcmdline", gettext("when set always use IM when starting to edit a command line")) call <SID>BinOptionG("imc", &imc) - call append("$", "imstatusfunc\tfunction to obtain IME status") + call <SID>AddOption("imstatusfunc", gettext("function to obtain IME status")) call <SID>OptionG("imsf", &imsf) - call append("$", "imactivatefunc\tfunction to enable/disable IME") + call <SID>AddOption("imactivatefunc", gettext("function to enable/disable IME")) call <SID>OptionG("imaf", &imaf) endif -call <SID>Header("multi-byte characters") -call <SID>AddOption("encoding", "character encoding used in Nvim: \"utf-8\"") +call <SID>Header(gettext("multi-byte characters")) +call <SID>AddOption("encoding", gettext("character encoding used in Nvim: \"utf-8\"")) call <SID>OptionG("enc", &enc) -call append("$", "fileencoding\tcharacter encoding for the current file") +call <SID>AddOption("fileencoding", gettext("character encoding for the current file")) call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("fenc") -call append("$", "fileencodings\tautomatically detected character encodings") +call <SID>AddOption("fileencodings", gettext("automatically detected character encodings")) call <SID>OptionG("fencs", &fencs) -call append("$", "charconvert\texpression used for character encoding conversion") +call <SID>AddOption("charconvert", gettext("expression used for character encoding conversion")) call <SID>OptionG("ccv", &ccv) -call append("$", "delcombine\tdelete combining (composing) characters on their own") +call <SID>AddOption("delcombine", gettext("delete combining (composing) characters on their own")) call <SID>BinOptionG("deco", &deco) -call append("$", "maxcombine\tmaximum number of combining (composing) characters displayed") +call <SID>AddOption("maxcombine", gettext("maximum number of combining (composing) characters displayed")) call <SID>OptionG("mco", &mco) if has("xim") && has("gui_gtk") - call append("$", "imactivatekey\tkey that activates the X input method") + call <SID>AddOption("imactivatekey", gettext("key that activates the X input method")) call <SID>OptionG("imak", &imak) endif -call append("$", "ambiwidth\twidth of ambiguous width characters") +call <SID>AddOption("ambiwidth", gettext("width of ambiguous width characters")) call <SID>OptionG("ambw", &ambw) -call append("$", "emoji\temoji characters are full width") +call <SID>AddOption("emoji", gettext("emoji characters are full width")) call <SID>BinOptionG("emo", &emo) -call <SID>Header("various") -call <SID>AddOption("virtualedit", "when to use virtual editing: \"block\", \"insert\", \"all\"\nand/or \"onemore\"") +call <SID>Header(gettext("various")) +call <SID>AddOption("virtualedit", gettext("when to use virtual editing: \"block\", \"insert\", \"all\"\nand/or \"onemore\"")) call <SID>OptionG("ve", &ve) -call append("$", "eventignore\tlist of autocommand events which are to be ignored") +call <SID>AddOption("eventignore", gettext("list of autocommand events which are to be ignored")) call <SID>OptionG("ei", &ei) -call append("$", "loadplugins\tload plugin scripts when starting up") +call <SID>AddOption("loadplugins", gettext("load plugin scripts when starting up")) call <SID>BinOptionG("lpl", &lpl) -call append("$", "exrc\tenable reading .vimrc/.exrc/.gvimrc in the current directory") +call <SID>AddOption("exrc", gettext("enable reading .vimrc/.exrc/.gvimrc in the current directory")) call <SID>BinOptionG("ex", &ex) -call append("$", "secure\tsafer working with script files in the current directory") +call <SID>AddOption("secure", gettext("safer working with script files in the current directory")) call <SID>BinOptionG("secure", &secure) -call append("$", "gdefault\tuse the 'g' flag for \":substitute\"") +call <SID>AddOption("gdefault", gettext("use the 'g' flag for \":substitute\"")) call <SID>BinOptionG("gd", &gd) if exists("+opendevice") - call append("$", "opendevice\tallow reading/writing devices") + call <SID>AddOption("opendevice", gettext("allow reading/writing devices")) call <SID>BinOptionG("odev", &odev) endif if exists("+maxfuncdepth") - call append("$", "maxfuncdepth\tmaximum depth of function calls") + call <SID>AddOption("maxfuncdepth", gettext("maximum depth of function calls")) call append("$", " \tset mfd=" . &mfd) endif if has("mksession") - call append("$", "sessionoptions\tlist of words that specifies what to put in a session file") + call <SID>AddOption("sessionoptions", gettext("list of words that specifies what to put in a session file")) call <SID>OptionG("ssop", &ssop) - call append("$", "viewoptions\tlist of words that specifies what to save for :mkview") + call <SID>AddOption("viewoptions", gettext("list of words that specifies what to save for :mkview")) call <SID>OptionG("vop", &vop) - call append("$", "viewdir\tdirectory where to store files with :mkview") + call <SID>AddOption("viewdir", gettext("directory where to store files with :mkview")) call <SID>OptionG("vdir", &vdir) endif if has("shada") - call append("$", "viminfo\tlist that specifies what to write in the ShaDa file") + call <SID>AddOption("viminfo", gettext("list that specifies what to write in the ShaDa file")) call <SID>OptionG("vi", &vi) endif if has("quickfix") - call append("$", "bufhidden\twhat happens with a buffer when it's no longer in a window") + call <SID>AddOption("bufhidden", gettext("what happens with a buffer when it's no longer in a window")) call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("bh") - call <SID>AddOption("buftype", "empty, \"nofile\", \"nowrite\", \"quickfix\", etc.: type of buffer") + call <SID>AddOption("buftype", gettext("empty, \"nofile\", \"nowrite\", \"quickfix\", etc.: type of buffer")) call append("$", "\t" .. s:local_to_buffer) call <SID>OptionL("bt") endif -call append("$", "buflisted\twhether the buffer shows up in the buffer list") -call append("$", "\t(local to buffer)") +call <SID>AddOption("buflisted", gettext("whether the buffer shows up in the buffer list")) +call append("$", "\t" .. s:local_to_buffer) call <SID>BinOptionL("bl") -call append("$", "debug\tset to \"msg\" to see all error messages") +call <SID>AddOption("debug", gettext("set to \"msg\" to see all error messages")) call append("$", " \tset debug=" . &debug) -call append("$", "signcolumn\twhether to show the signcolumn") -call append("$", "\t(local to window)") +call <SID>AddOption("signcolumn", gettext("whether to show the signcolumn")) +call append("$", "\t" .. s:local_to_window) call <SID>OptionL("scl") set cpo&vim @@ -1297,13 +1260,13 @@ if has("syntax") endif endif if exists("&mzschemedll") - call append("$", "mzschemedll\tname of the Tcl dynamic library") + call <SID>AddOption("mzschemedll", gettext("name of the MzScheme dynamic library")) call <SID>OptionG("mzschemedll", &mzschemedll) - call append("$", "mzschemegcdll\tname of the Tcl GC dynamic library") + call <SID>AddOption("mzschemegcdll", gettext("name of the MzScheme GC dynamic library")) call <SID>OptionG("mzschemegcdll", &mzschemegcdll) endif if has('pythonx') - call append("$", "pyxversion\twhether to use Python 2 or 3") + call <SID>AddOption("pyxversion", gettext("whether to use Python 2 or 3")) call append("$", " \tset pyx=" . &wd) endif @@ -1320,7 +1283,7 @@ augroup optwin \ call <SID>unload() | delfun <SID>unload augroup END -fun! <SID>unload() +func <SID>unload() delfun <SID>CR delfun <SID>Space delfun <SID>Find @@ -1331,7 +1294,7 @@ fun! <SID>unload() delfun <SID>BinOptionG delfun <SID>Header au! optwin -endfun +endfunc " Restore the previous value of 'title' and 'icon'. let &title = s:old_title diff --git a/runtime/pack/dist/opt/cfilter/plugin/cfilter.lua b/runtime/pack/dist/opt/cfilter/plugin/cfilter.lua new file mode 100644 index 0000000000..20c158da65 --- /dev/null +++ b/runtime/pack/dist/opt/cfilter/plugin/cfilter.lua @@ -0,0 +1,114 @@ +---------------------------------------- +-- This file is generated via github.com/tjdevries/vim9jit +-- For any bugs, please first consider reporting there. +---------------------------------------- + +-- Ignore "value assigned to a local variable is unused" because +-- we can't guarantee that local variables will be used by plugins +-- luacheck: ignore 311 + +local vim9 = require('_vim9script') +local M = {} +local Qf_filter = nil +-- vim9script + +-- # cfilter.vim: Plugin to filter entries from a quickfix/location list +-- # Last Change: Jun 30, 2022 +-- # Maintainer: Yegappan Lakshmanan (yegappan AT yahoo DOT com) +-- # Version: 2.0 +-- # +-- # Commands to filter the quickfix list: +-- # :Cfilter[!] /{pat}/ +-- # Create a new quickfix list from entries matching {pat} in the current +-- # quickfix list. Both the file name and the text of the entries are +-- # matched against {pat}. If ! is supplied, then entries not matching +-- # {pat} are used. The pattern can be optionally enclosed using one of +-- # the following characters: ', ", /. If the pattern is empty, then the +-- # last used search pattern is used. +-- # :Lfilter[!] /{pat}/ +-- # Same as :Cfilter but operates on the current location list. +-- # + +Qf_filter = function(qf, searchpat, bang) + qf = vim9.bool(qf) + local Xgetlist = function() end + local Xsetlist = function() end + local cmd = '' + local firstchar = '' + local lastchar = '' + local pat = '' + local title = '' + local Cond = function() end + local items = {} + + if vim9.bool(qf) then + Xgetlist = function(...) + return vim.fn['getqflist'](...) + end + Xsetlist = function(...) + return vim.fn['setqflist'](...) + end + cmd = ':Cfilter' .. bang + else + Xgetlist = function(...) + return vim9.fn_ref(M, 'getloclist', vim.deepcopy({ 0 }), ...) + end + + Xsetlist = function(...) + return vim9.fn_ref(M, 'setloclist', vim.deepcopy({ 0 }), ...) + end + + cmd = ':Lfilter' .. bang + end + + firstchar = vim9.index(searchpat, 0) + lastchar = vim9.slice(searchpat, -1, nil) + if firstchar == lastchar and (firstchar == '/' or firstchar == '"' or firstchar == "'") then + pat = vim9.slice(searchpat, 1, -2) + if pat == '' then + -- # Use the last search pattern + pat = vim.fn.getreg('/') + end + else + pat = searchpat + end + + if pat == '' then + return + end + + if bang == '!' then + Cond = function(_, val) + return vim9.ops.NotRegexpMatches(val.text, pat) + and vim9.ops.NotRegexpMatches(vim9.fn.bufname(val.bufnr), pat) + end + else + Cond = function(_, val) + return vim9.ops.RegexpMatches(val.text, pat) + or vim9.ops.RegexpMatches(vim9.fn.bufname(val.bufnr), pat) + end + end + + items = vim9.fn_mut('filter', { Xgetlist(), Cond }, { replace = 0 }) + title = cmd .. ' /' .. pat .. '/' + Xsetlist({}, ' ', { ['title'] = title, ['items'] = items }) +end + +vim.api.nvim_create_user_command('Cfilter', function(__vim9_arg_1) + Qf_filter(true, __vim9_arg_1.args, (__vim9_arg_1.bang and '!' or '')) +end, { + bang = true, + nargs = '+', + complete = nil, +}) + +vim.api.nvim_create_user_command('Lfilter', function(__vim9_arg_1) + Qf_filter(false, __vim9_arg_1.args, (__vim9_arg_1.bang and '!' or '')) +end, { + bang = true, + nargs = '+', + complete = nil, +}) + +-- # vim: shiftwidth=2 sts=2 expandtab +return M diff --git a/runtime/pack/dist/opt/cfilter/plugin/cfilter.vim b/runtime/pack/dist/opt/cfilter/plugin/cfilter.vim deleted file mode 100644 index fe4455fe2e..0000000000 --- a/runtime/pack/dist/opt/cfilter/plugin/cfilter.vim +++ /dev/null @@ -1,62 +0,0 @@ -" cfilter.vim: Plugin to filter entries from a quickfix/location list -" Last Change: Aug 23, 2018 -" Maintainer: Yegappan Lakshmanan (yegappan AT yahoo DOT com) -" Version: 1.1 -" -" Commands to filter the quickfix list: -" :Cfilter[!] /{pat}/ -" Create a new quickfix list from entries matching {pat} in the current -" quickfix list. Both the file name and the text of the entries are -" matched against {pat}. If ! is supplied, then entries not matching -" {pat} are used. The pattern can be optionally enclosed using one of -" the following characters: ', ", /. If the pattern is empty, then the -" last used search pattern is used. -" :Lfilter[!] /{pat}/ -" Same as :Cfilter but operates on the current location list. -" -if exists("loaded_cfilter") - finish -endif -let loaded_cfilter = 1 - -func s:Qf_filter(qf, searchpat, bang) - if a:qf - let Xgetlist = function('getqflist') - let Xsetlist = function('setqflist') - let cmd = ':Cfilter' . a:bang - else - let Xgetlist = function('getloclist', [0]) - let Xsetlist = function('setloclist', [0]) - let cmd = ':Lfilter' . a:bang - endif - - let firstchar = a:searchpat[0] - let lastchar = a:searchpat[-1:] - if firstchar == lastchar && - \ (firstchar == '/' || firstchar == '"' || firstchar == "'") - let pat = a:searchpat[1:-2] - if pat == '' - " Use the last search pattern - let pat = @/ - endif - else - let pat = a:searchpat - endif - - if pat == '' - return - endif - - if a:bang == '!' - let cond = 'v:val.text !~# pat && bufname(v:val.bufnr) !~# pat' - else - let cond = 'v:val.text =~# pat || bufname(v:val.bufnr) =~# pat' - endif - - let items = filter(Xgetlist(), cond) - let title = cmd . ' /' . pat . '/' - call Xsetlist([], ' ', {'title' : title, 'items' : items}) -endfunc - -com! -nargs=+ -bang Cfilter call s:Qf_filter(1, <q-args>, <q-bang>) -com! -nargs=+ -bang Lfilter call s:Qf_filter(0, <q-args>, <q-bang>) diff --git a/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim b/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim index 802ebd42b5..99fd7dba42 100644 --- a/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim +++ b/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim @@ -2,7 +2,7 @@ " " Author: Bram Moolenaar " Copyright: Vim license applies, see ":help license" -" Last Change: 2022 Jun 24 +" Last Change: 2022 Nov 10 " " WORK IN PROGRESS - The basics works stable, more to come " Note: In general you need at least GDB 7.12 because this provides the @@ -154,10 +154,16 @@ func s:StartDebug_internal(dict) let s:save_columns = 0 let s:allleft = 0 - if exists('g:termdebug_wide') - if &columns < g:termdebug_wide + let wide = 0 + if exists('g:termdebug_config') + let wide = get(g:termdebug_config, 'wide', 0) + elseif exists('g:termdebug_wide') + let wide = g:termdebug_wide + endif + if wide > 0 + if &columns < wide let s:save_columns = &columns - let &columns = g:termdebug_wide + let &columns = wide " If we make the Vim window wider, use the whole left half for the debug " windows. let s:allleft = 1 @@ -168,7 +174,12 @@ func s:StartDebug_internal(dict) endif " Override using a terminal window by setting g:termdebug_use_prompt to 1. - let use_prompt = exists('g:termdebug_use_prompt') && g:termdebug_use_prompt + let use_prompt = 0 + if exists('g:termdebug_config') + let use_prompt = get(g:termdebug_config, 'use_prompt', 0) + elseif exists('g:termdebug_use_prompt') + let use_prompt = g:termdebug_use_prompt + endif if !has('win32') && !use_prompt let s:way = 'terminal' else @@ -903,7 +914,14 @@ func s:InstallCommands() endif if has('menu') && &mouse != '' - call s:InstallWinbar() + " install the window toolbar by default, can be disabled in the config + let winbar = 1 + if exists('g:termdebug_config') + let winbar = get(g:termdebug_config, 'winbar', 1) + endif + if winbar + call s:InstallWinbar() + endif let popup = 1 if exists('g:termdebug_config') @@ -964,14 +982,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/pack/dist/opt/vimball/doc/vimball.txt b/runtime/pack/dist/opt/vimball/doc/vimball.txt index 9965a216e4..602fe85954 100644 --- a/runtime/pack/dist/opt/vimball/doc/vimball.txt +++ b/runtime/pack/dist/opt/vimball/doc/vimball.txt @@ -88,7 +88,7 @@ MAKING A VIMBALL *:MkVimball* If you wish to force slashes into the filename, that can also be done by using the exclamation mark (ie. :MkVimball! path/filename). - The tip at http://vim.wikia.com/wiki/Using_VimBall_with_%27Make%27 + The tip at https://vim.wikia.com/wiki/Using_VimBall_with_%27Make%27 has a good idea on how to automate the production of vimballs using make. @@ -171,12 +171,12 @@ WINDOWS *vimball-windows* > Item Tool/Suite Free Website ---- ---------- ---- ------- - 7zip tool y http://www.7-zip.org/ - Winzip tool n http://www.winzip.com/downwz.htm - unxutils suite y http://unxutils.sourceforge.net/ - cygwin suite y http://www.cygwin.com/ - GnuWin32 suite y http://gnuwin32.sourceforge.net/ - MinGW suite y http://www.mingw.org/ + 7zip tool y https://www.7-zip.org/ + Winzip tool n https://www.winzip.com/downwz.htm + unxutils suite y https://unxutils.sourceforge.net/ + cygwin suite y https://www.cygwin.com/ + GnuWin32 suite y https://gnuwin32.sourceforge.net/ + MinGW suite y https://www.mingw.org/ < ============================================================================== diff --git a/runtime/plugin/editorconfig.lua b/runtime/plugin/editorconfig.lua new file mode 100644 index 0000000000..54cd0e828e --- /dev/null +++ b/runtime/plugin/editorconfig.lua @@ -0,0 +1,13 @@ +local group = vim.api.nvim_create_augroup('editorconfig', {}) +vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead', 'BufFilePost' }, { + group = group, + callback = function(args) + -- Buffer-local enable has higher priority + local enable = vim.F.if_nil(vim.b.editorconfig, vim.F.if_nil(vim.g.editorconfig, true)) + if not enable then + return + end + + require('editorconfig').config(args.buf) + end, +}) 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..3982489b92 100644 --- a/runtime/plugin/matchparen.vim +++ b/runtime/plugin/matchparen.vim @@ -1,12 +1,11 @@ " Vim plugin for showing matching parens " Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2021 Apr 08 +" Last Change: 2022 Dec 01 " 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,8 +19,8 @@ endif augroup matchparen " Replace all matchparen autocommands - autocmd! CursorMoved,CursorMovedI,WinEnter * call s:Highlight_Matching_Pair() - autocmd! WinLeave * call s:Remove_Matches() + autocmd! CursorMoved,CursorMovedI,WinEnter,BufWinEnter,WinScrolled * call s:Highlight_Matching_Pair() + autocmd! WinLeave,BufLeave * call s:Remove_Matches() if exists('##TextChanged') autocmd! TextChanged,TextChangedI * call s:Highlight_Matching_Pair() endif diff --git a/runtime/plugin/nvim.lua b/runtime/plugin/nvim.lua new file mode 100644 index 0000000000..815886f896 --- /dev/null +++ b/runtime/plugin/nvim.lua @@ -0,0 +1,7 @@ +vim.api.nvim_create_user_command('Inspect', function(cmd) + if cmd.bang then + vim.pretty_print(vim.inspect_pos()) + else + vim.show_pos() + end +end, { desc = 'Inspect highlights and extmarks at the cursor', bang = true }) diff --git a/runtime/print/ascii.ps b/runtime/print/ascii.ps deleted file mode 100644 index 5fcffb655f..0000000000 --- a/runtime/print/ascii.ps +++ /dev/null @@ -1,22 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-ascii -%%Version: 1.0 0 -%%EndComments -/VIM-ascii[ -32{/.notdef}repeat -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -128{/.notdef}repeat] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cidfont.ps b/runtime/print/cidfont.ps deleted file mode 100644 index a06ebc8c4c..0000000000 --- a/runtime/print/cidfont.ps +++ /dev/null @@ -1,26 +0,0 @@ -%!PS-Adobe-3.0 Resource-ProcSet -%%Title: VIM-CIDFont -%%Version: 1.0 0 -%%EndComments -% Editing of this file is NOT RECOMMENDED. You run a very good risk of causing -% all PostScript printing from VIM failing if you do. PostScript is not called -% a write-only language for nothing! -/CP currentpacking d T setpacking -/SB 256 string d -/CIDN? systemdict/composefont known d /GS? systemdict/.makeoperator known d -CIDN?{ -GS?{/vim_findresource{2 copy resourcestatus not{1 index SB cvs runlibfile}{ -pop pop}ifelse findresource}bd/vim_composefont{0 get/CIDFont vim_findresource -exch/CMap vim_findresource exch[exch]composefont pop}bd}{/vim_findresource -/findresource ld/vim_composefont{composefont pop}bd}ifelse -}{ -/vim_fontname{0 get SB cvs length dup SB exch(-)putinterval 1 add dup SB exch -dup 256 exch sub getinterval 3 -1 roll exch cvs length add SB exch 0 exch -getinterval cvn}bd/vim_composefont{vim_fontname findfont d}bd -} ifelse -/cfs{exch scalefont d}bd -/sffs{findfont 3 1 roll 1 index mul exch 2 index/FontMatrix get matrix copy -scale makefont d}bd -CP setpacking -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cns_roman.ps b/runtime/print/cns_roman.ps deleted file mode 100644 index dba385cae0..0000000000 --- a/runtime/print/cns_roman.ps +++ /dev/null @@ -1,23 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-cns_roman -%%Version: 1.0 0 -%%EndComments -% Different to ASCII at code point 126 -/VIM-cns_roman[ -32{/.notdef}repeat -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /overline /.notdef -128{/.notdef}repeat] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cp1250.ps b/runtime/print/cp1250.ps deleted file mode 100644 index 9e733cc760..0000000000 --- a/runtime/print/cp1250.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-cp1250 -%%Version: 1.0 0 -%%EndComments -/VIM-cp1250[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /tilde /.notdef -/Euro /.notdef /quotesinglbase /.notdef /quotedblbase /ellipsis /dagger /daggerdbl -/.notdef /perthousand /Scaron /guilsinglleft /Sacute /Tcaron /Zcaron /Zacute -/.notdef /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash -/.notdef /trademark /scaron /guilsinglright /sacute /tcaron /zcaron /zacute -/space /caron /breve /Lslash /currency /Aogonek /brokenbar /section -/dieresis /copyright /Scedilla /guillemotleft /logicalnot /hyphen /registered /Zdotaccent -/degree /plusminus /ogonek /lslash /acute /mu /paragraph /periodcentered -/cedilla /aogonek /scedilla /guillemotright /Lcaron /hungarumlaut /lcaron /zdotaccent -/Racute /Aacute /Acircumflex /Abreve /Adieresis /Lacute /Cacute /Ccedilla -/Ccaron /Eacute /Eogonek /Edieresis /Ecaron /Iacute /Icircumflex /Dcaron -/Dcroat /Nacute /Ncaron /Oacute /Ocircumflex /Ohungarumlaut /Odieresis /multiply -/Rcaron /Uring /Uacute /Uhungarumlaut /Udieresis /Yacute /Tcedilla /germandbls -/racute /aacute /acircumflex /abreve /adieresis /lacute /cacute /ccedilla -/ccaron /eacute /eogonek /edieresis /ecaron /iacute /icircumflex /dcaron -/dcroat /nacute /ncaron /oacute /ocircumflex /ohungarumlaut /odieresis /divide -/rcaron /uring /uacute /uhungarumlaut /udieresis /yacute /tcedilla /dotaccent] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cp1251.ps b/runtime/print/cp1251.ps deleted file mode 100644 index 7137504e7a..0000000000 --- a/runtime/print/cp1251.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-cp1251 -%%Version: 1.0 0 -%%EndComments -/VIM-cp1251[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/afii10051 /afii10052 /quotesinglbase /afii10100 /quotedblbase /ellipsis /dagger /daggerdbl -/Euro /perthousand /afii10058 /guilsinglleft /afii10059 /afii10061 /afii10060 /afii10145 -/afii10099 /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash -/.notdef /trademark /afii10106 /guilsinglright /afii10107 /afii10109 /afii10108 /afii10193 -/space /afii10062 /afii10110 /afii10057 /currency /afii10050 /brokenbar /section -/afii10023 /copyright /afii10053 /guillemotleft /logicalnot /hyphen /registered /afii10056 -/degree /plusminus /afii10055 /afii10103 /afii10098 /mu /paragraph /periodcentered -/afii10071 /afii61352 /afii10101 /guillemotright /afii10105 /afii10054 /afii10102 /afii10104 -/afii10017 /afii10018 /afii10019 /afii10020 /afii10021 /afii10022 /afii10024 /afii10025 -/afii10026 /afii10027 /afii10028 /afii10029 /afii10030 /afii10031 /afii10032 /afii10033 -/afii10034 /afii10035 /afii10036 /afii10037 /afii10038 /afii10039 /afii10040 /afii10041 -/afii10042 /afii10043 /afii10044 /afii10045 /afii10046 /afii10047 /afii10048 /afii10049 -/afii10065 /afii10066 /afii10067 /afii10068 /afii10069 /afii10070 /afii10072 /afii10073 -/afii10074 /afii10075 /afii10076 /afii10077 /afii10078 /afii10079 /afii10080 /afii10081 -/afii10082 /afii10083 /afii10084 /afii10085 /afii10086 /afii10087 /afii10088 /afii10089 -/afii10090 /afii10091 /afii10092 /afii10093 /afii10094 /afii10095 /afii10096 /afii10097] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cp1252.ps b/runtime/print/cp1252.ps deleted file mode 100644 index a4dd7e675f..0000000000 --- a/runtime/print/cp1252.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-cp1252 -%%Version: 1.0 0 -%%EndComments -/VIM-cp1252[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/Euro /.notdef /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl -/circumflex /perthousand /Scaron /guilsinglleft /OE /.notdef /Zcaron /.notdef -/.notdef /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash -/tilde /trademark /scaron /guilsinglright /oe /.notdef /zcaron /Ydieresis -/space /exclamdown /cent /sterling /currency /yen /brokenbar /section -/dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron -/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered -/cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown -/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla -/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis -/Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply -/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls -/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla -/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis -/eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide -/oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cp1253.ps b/runtime/print/cp1253.ps deleted file mode 100644 index 0482232af1..0000000000 --- a/runtime/print/cp1253.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-cp1253 -%%Version: 1.0 0 -%%EndComments -/VIM-cp1253[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl -/.notdef /perthousand /.notdef /guilsinglleft /.notdef /.notdef /.notdef /.notdef -/.notdef /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash -/.notdef /trademark /.notdef /guilsinglright /.notdef /.notdef /.notdef /.notdef -/space /dieresistonos /Alphatonos /sterling /currency /yen /brokenbar /section -/dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /emdash -/degree /plusminus /twosuperior /threesuperior /tonos /mu /paragraph /periodcentered -/Epsilontonos /Etatonos /Iotatonos /guillemotright /Omicrontonos /onehalf /Upsilontonos /Omegatonos -/iotadieresistonos /Alpha /Beta /Gamma /Delta /Epsilon /Zeta /Eta -/Theta /Iota /Kappa /Lambda /Mu /Nu /Xi /Omicron -/Pi /Rho /.notdef /Sigma /Tau /Upsilon /Phi /Chi -/Psi /Omega /Iotadieresis /Upsilondieresis /alphatonos /epsilontonos /etatonos /iotatonos -/upsilondieresistonos /alpha /beta /gamma /delta /epsilon /zeta /eta -/theta /iota /kappa /lambda /mu /nu /xi /omicron -/pi /rho /sigma1 /sigma /tau /upsilon /phi /chi -/psi /omega /iotadieresis /upsilondieresis /omicrontonos /upsilontonos /omegatonos /.notdef] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cp1254.ps b/runtime/print/cp1254.ps deleted file mode 100644 index 9fe7e47710..0000000000 --- a/runtime/print/cp1254.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-cp1254 -%%Version: 1.0 0 -%%EndComments -/VIM-cp1254[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/Euro /.notdef /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl -/circumflex /perthousand /Scaron /guilsinglleft /OE /.notdef /Zcaron /.notdef -/.notdef /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash -/tilde /trademark /scaron /guilsinglright /oe /.notdef /zcaron /Ydieresis -/space /exclamdown /cent /sterling /currency /yen /brokenbar /section -/dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron -/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered -/cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown -/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla -/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis -/Gbreve /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply -/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Idotaccent /Scedilla /germandbls -/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla -/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis -/gbreve /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide -/oslash /ugrave /uacute /ucircumflex /udieresis /dotlessi /scedilla /ydieresis] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cp1255.ps b/runtime/print/cp1255.ps deleted file mode 100644 index cd82f46a0e..0000000000 --- a/runtime/print/cp1255.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-cp1255 -%%Version: 1.0 0 -%%EndComments -/VIM-cp1255[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl -/circumflex /perthousand /.notdef /guilsinglleft /.notdef /.notdef /.notdef /.notdef -/.notdef /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash -/tilde /trademark /.notdef /guilsinglright /.notdef /.notdef /.notdef /.notdef -/space /.notdef /cent /sterling /newsheqelsign /yen /brokenbar /section -/dieresis /copyright /.notdef /guillemotleft /logicalnot /hyphen /registered /macron -/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered -/.notdef /onesuperior /.notdef /guillemotright /onequarter /onehalf /threequarters /.notdef -/sheva /hatafsegol /hatafpatah /hatafqamats /hiriq /tsere /segol /patah -/qamats /holam /.notdef /qubuts /dagesh /meteg /maqaf /rafe -/paseq /shindot /sindot /sofpasuq /doublevav /vavyod /doubleyod /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/alef /bet /gimel /dalet /he /vav /zayin /het -/tet /yod /finalkaf /kaf /lamed /finalmem /mem /finalnun -/nun /samekh /ayin /finalpe /pe /finaltsadi /tsadi /qof -/resh /shin /tav /.notdef /.notdef /.notdef /.notdef /.notdef] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/cp1257.ps b/runtime/print/cp1257.ps deleted file mode 100644 index 2e5d7a7b2d..0000000000 --- a/runtime/print/cp1257.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-cp1257 -%%Version: 1.0 0 -%%EndComments -/VIM-cp1257[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /quotesinglbase /.notdef /quotedblbase /ellipsis /dagger /daggerdbl -/.notdef /perthousand /.notdef /guilsinglleft /.notdef /.notdef /.notdef /.notdef -/.notdef /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash -/.notdef /trademark /.notdef /guilsinglright /.notdef /.notdef /.notdef /.notdef -/space /caron /breve /sterling /currency /.notdef /brokenbar /section -/dieresis /copyright /Rcedilla /guillemotleft /logicalnot /hyphen /registered /AE -/degree /plusminus /ogonek /threesuperior /acute /mu /paragraph /periodcentered -/cedilla /onesuperior /rcedilla /guillemotright /onequarter /onehalf /threequarters /ae -/Aogonek /Iogonek /Amacron /Cacute /Adieresis /Aring /Eogonek /Emacron -/Ccaron /Eacute /Zacute /Edot /Gcedilla /Kcedilla /Imacron /Lcedilla -/Scaron /Nacute /Ncedilla /Oacute /Omacron /Otilde /Odieresis /multiply -/Uogonek /Lslash /Sacute /Umacron /Udieresis /Zdotaccent /Zcaron /germandbls -/aogonek /iogonek /amacron /cacute /adieresis /aring /eogonek /emacron -/ccaron /eacute /zacute /edot /gcedilla /kcedilla /imacron /lcedilla -/scaron /nacute /ncedilla /oacute /omacron /otilde /odieresis /divide -/uogonek /lslash /sacute /umacron /udieresis /zdotaccent /zcaron /dotaccent] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/gb_roman.ps b/runtime/print/gb_roman.ps deleted file mode 100644 index fa78dbf5d6..0000000000 --- a/runtime/print/gb_roman.ps +++ /dev/null @@ -1,23 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-gb_roman -%%Version: 1.0 0 -%%EndComments -% Different to ASCII at code points 36 and 126 -/VIM-gb_roman[ -32{/.notdef}repeat -/space /exclam /quotedbl /numbersign /yuan /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /overline /.notdef -128{/.notdef}repeat] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/hp-roman8.ps b/runtime/print/hp-roman8.ps deleted file mode 100644 index d71b876db1..0000000000 --- a/runtime/print/hp-roman8.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-hp-roman8 -%%Version: 1.0 0 -%%EndComments -/VIM-hp-roman8[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /Agrave /Acircumflex /Egrave /Ecircumflex /Edieresis /Icircumflex /Idieresis -/acute /grave /circumflex /dieresis /tilde /Ugrave /Ucircumflex /lira -/macron /Yacute /yacute /degree /Ccedilla /ccedilla /Ntilde /ntilde -/exclamdown /questiondown /currency /sterling /yen /section /florin /cent -/acircumflex /ecircumflex /ocircumflex /ucircumflex /aacute /eacute /oacute /uacute -/agrave /egrave /ograve /ugrave /adieresis /edieresis /odieresis /udieresis -/Aring /icircumflex /Oslash /AE /aring /iacute /oslash /ae -/Adieresis /igrave /Odieresis /Udieresis /Eacute /idieresis /germandbls /Ocircumflex -/Aacute /Atilde /atilde /Eth /eth /Iacute /Igrave /Oacute -/Ograve /Otilde /otilde /Scaron /scaron /Uacute /Ydieresis /ydieresis -/Thorn /thorn /periodcentered /mu /paragraph /threequarters /hyphen /onequarter -/onehalf /ordfeminine /ordmasculine /guillemotleft /filledbox /guillemotright /plusminus /.notdef] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-10.ps b/runtime/print/iso-8859-10.ps deleted file mode 100644 index 7d8e2a0f96..0000000000 --- a/runtime/print/iso-8859-10.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-10 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-10[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /hyphen /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /Aogonek /Emacron /Gcedilla /Imacron /Itilde /Kcedilla /section -/Lcedilla /Dcroat /Scaron /Tbar /Zcaron /endash /Umacron /Eng -/degree /aogonek /emacron /gcedilla /imacron /itilde /kcedilla /periodcentered -/lcedilla /dcroat /scaron /tbar /zcaron /emdash /umacron /eng -/Amacron /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Iogonek -/Ccaron /Eacute /Eogonek /Edieresis /Edot /Iacute /Icircumflex /Idieresis -/Eth /Ncedilla /Omacron /Oacute /Ocircumflex /Otilde /Odieresis /Utilde -/Oslash /Uogonek /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls -/amacron /aacute /acircumflex /atilde /adieresis /aring /ae /iogonek -/ccaron /eacute /eogonek /edieresis /edot /iacute /icircumflex /idieresis -/eth /ncedilla /omacron /oacute /ocircumflex /otilde /odieresis /utilde -/oslash /uogonek /uacute /ucircumflex /udieresis /yacute /thorn /kgreenlandic] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-11.ps b/runtime/print/iso-8859-11.ps deleted file mode 100644 index 78f775befc..0000000000 --- a/runtime/print/iso-8859-11.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-11 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-11[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /uni0E01 /uni0E02 /uni0E03 /uni0E04 /uni0E05 /uni0E06 /uni0E07 -/uni0E08 /uni0E09 /uni0E0A /uni0E0B /uni0E0C /uni0E0D /uni0E0E /uni0E0F -/uni0E10 /uni0E11 /uni0E12 /uni0E13 /uni0E14 /uni0E15 /uni0E16 /uni0E17 -/uni0E18 /uni0E19 /uni0E1A /uni0E1B /uni0E1C /uni0E1D /uni0E1E /uni0E1F -/uni0E20 /uni0E21 /uni0E22 /uni0E23 /uni0E24 /uni0E25 /uni0E26 /uni0E27 -/uni0E28 /uni0E29 /uni0E2A /uni0E2B /uni0E2C /uni0E2D /uni0E2E /uni0E2F -/uni0E30 /uni0E31 /uni0E32 /uni0E33 /uni0E34 /uni0E35 /uni0E36 /uni0E37 -/uni0E38 /uni0E39 /uni0E3A /.notdef /space /.notdef /.notdef /uni0E3F -/uni0E40 /uni0E41 /uni0E42 /uni0E43 /uni0E44 /uni0E45 /uni0E46 /uni0E47 -/uni0E48 /uni0E49 /uni0E4A /uni0E4B /uni0E4C /uni0E4D /uni0E4E /uni0E4F -/uni0E50 /uni0E51 /uni0E52 /uni0E53 /uni0E54 /uni0E55 /uni0E56 /uni0E57 - /uni0E58 /uni0E59 /uni0E5A /.notdef /.notdef /.notdef /.notdef /.notdef] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-13.ps b/runtime/print/iso-8859-13.ps deleted file mode 100644 index b4348f6619..0000000000 --- a/runtime/print/iso-8859-13.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-13 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-13[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /quotedblright /cent /sterling /currency /quotedblbase /brokenbar /section -/Oslash /copyright /Rcedilla /guillemotleft /logicalnot /hyphen /registered /AE -/degree /plusminus /twosuperior /threesuperior /quotedblleft /mu /paragraph /periodcentered -/oslash /onesuperior /rcedilla /guillemotright /onequarter /onehalf /threequarters /ae -/Aogonek /Iogonek /Amacron /Cacute /Adieresis /Aring /Eogonek /Emacron -/Ccaron /Eacute /Zacute /Edot /Gcedilla /Kcedilla /Imacron /Lcedilla -/Scaron /Nacute /Ncedilla /Oacute /Omacron /Otilde /Odieresis /multiply -/Uogonek /Lslash /Sacute /Umacron /Udieresis /Zdotaccent /Zcaron /germandbls -/aogonek /iogonek /amacron /cacute /adieresis /aring /eogonek /emacron -/ccaron /eacute /zacute /edot /gcedilla /kcedilla /imacron /lcedilla -/scaron /nacute /ncedilla /oacute /omacron /otilde /odieresis /divide -/uogonek /lslash /sacute /umacron /udieresis /zdotaccent /zcaron /quoteright] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-14.ps b/runtime/print/iso-8859-14.ps deleted file mode 100644 index cdfe04268a..0000000000 --- a/runtime/print/iso-8859-14.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-14 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-14[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /uni1E02 /uni1E03 /sterling /Cdotaccent /cdotaccent /uni1E0A /section -/Wgrave /copyright /Wacute /uni1E0B /Ygrave /hyphen /registered /Ydieresis -/uni1E1E /uni1E1F /Gdotaccent /gdotaccent /uni1E40 /uni1E41 /paragraph /uni1E56 -/wgrave /uni1E57 /wacute /uni1E60 /ygrave /Wdieresis /wdieresis /uni1E61 -/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla -/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis -/Wcircumflex /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /uni1E6A -/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Ycircumflex /germandbls -/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla -/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis -/wcircumflex /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /uni1E6B -/oslash /ugrave /uacute /ucircumflex /udieresis /yacute /ycircumflex /ydieresis] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-15.ps b/runtime/print/iso-8859-15.ps deleted file mode 100644 index 46ea691ff1..0000000000 --- a/runtime/print/iso-8859-15.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-15 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-15[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclamdown /cent /sterling /Euro /yen /Scaron /section -/scaron /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron -/degree /plusminus /twosuperior /threesuperior /Zcaron /mu /paragraph /periodcentered -/zcaron /onesuperior /ordmasculine /guillemotright /OE /oe /Ydieresis /questiondown -/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla -/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis -/Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply -/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls -/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla -/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis -/eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide -/oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-2.ps b/runtime/print/iso-8859-2.ps deleted file mode 100644 index f6e1933be7..0000000000 --- a/runtime/print/iso-8859-2.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-2 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-2[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /Aogonek /breve /Lslash /currency /Lcaron /Sacute /section -/dieresis /Scaron /Scedilla /Tcaron /Zacute /hyphen /Zcaron /Zdotaccent -/degree /aogonek /ogonek /lslash /acute /lcaron /sacute /caron -/cedilla /scaron /scedilla /tcaron /zacute /hungarumlaut /zcaron /zdotaccent -/Racute /Aacute /Acircumflex /Abreve /Adieresis /Lacute /Cacute /Ccedilla -/Ccaron /Eacute /Eogonek /Edieresis /Ecaron /Iacute /Icircumflex /Dcaron -/Dcroat /Nacute /Ncaron /Oacute /Ocircumflex /Ohungarumlaut /Odieresis /multiply -/Rcaron /Uring /Uacute /Uhungarumlaut /Udieresis /Yacute /Tcedilla /germandbls -/racute /aacute /acircumflex /abreve /adieresis /lacute /cacute /ccedilla -/ccaron /eacute /eogonek /edieresis /ecaron /iacute /icircumflex /dcaron -/dcroat /nacute /ncaron /oacute /ocircumflex /ohungarumlaut /odieresis /divide -/rcaron /uring /uacute /uhungarumlaut /udieresis /yacute /tcedilla /dotaccent] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-3.ps b/runtime/print/iso-8859-3.ps deleted file mode 100644 index b5a3474fb3..0000000000 --- a/runtime/print/iso-8859-3.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-3 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-3[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /Hbar /breve /sterling /currency /.notdef /Hcircumflex /section -/dieresis /Idot /Scedilla /Gbreve /Jcircumflex /hyphen /.notdef /Zdotaccent -/degree /hbar /twosuperior /threesuperior /acute /mu /hcircumflex /periodcentered -/cedilla /dotlessi /scedilla /gbreve /jcircumflex /onehalf /.notdef /zdotaccent -/Agrave /Aacute /Acircumflex /.notdef /Adieresis /Cdotaccent /Ccircumflex /Ccedilla -/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis -/.notdef /Ntilde /Ograve /Oacute /Ocircumflex /Gdotaccent /Odieresis /multiply -/Gcircumflex /Ugrave /Uacute /Ucircumflex /Udieresis /Ubreve /Scircumflex /germandbls -/agrave /aacute /acircumflex /.notdef /adieresis /cdotaccent /ccircumflex /ccedilla -/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis -/.notdef /ntilde /ograve /oacute /ocircumflex /gdotaccent /odieresis /divide -/gcircumflex /ugrave /uacute /ucircumflex /udieresis /ubreve /scircumflex /dotaccent] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-4.ps b/runtime/print/iso-8859-4.ps deleted file mode 100644 index c917d1ff37..0000000000 --- a/runtime/print/iso-8859-4.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-4 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-4[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /Aogonek /kgreenlandic /Rcedilla /currency /Itilde /Lcedilla /section -/dieresis /Scaron /Emacron /Gcedilla /Tbar /.notdef /Zcaron /macron -/degree /aogonek /ogonek /rcedilla /acute /itilde /lcedilla /caron -/cedilla /scaron /emacron /gcedilla /tbar /Eng /zcaron /eng -/Amacron /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Iogonek -/Ccaron /Eacute /Eogonek /Edieresis /Edot /Iacute /Icircumflex /Imacron -/Dcroat /Ncedilla /Omacron /Kcedilla /Ocircumflex /Otilde /Odieresis /multiply -/Oslash /Uogonek /Uacute /Ucircumflex /Udieresis /Utilde /Umacron /germandbls -/amacron /aacute /acircumflex /atilde /adieresis /aring /ae /iogonek -/ccaron /eacute /eogonek /edieresis /edot /iacute /icircumflex /imacron -/dcroat /ncedilla /omacron /kcedilla /ocircumflex /otilde /odieresis /divide -/oslash /uogonek /uacute /ucircumflex /udieresis /utilde /umacron /dotaccent] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-5.ps b/runtime/print/iso-8859-5.ps deleted file mode 100644 index dbe9628900..0000000000 --- a/runtime/print/iso-8859-5.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-5 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-5[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /afii10023 /afii10051 /afii10052 /afii10053 /afii10054 /afii10055 /afii10056 -/afii10057 /afii10058 /afii10059 /afii10060 /afii10061 /.notdef /afii10062 /afii10145 -/afii10017 /afii10018 /afii10019 /afii10020 /afii10021 /afii10022 /afii10024 /afii10025 -/afii10026 /afii10027 /afii10028 /afii10029 /afii10030 /afii10031 /afii10032 /afii10033 -/afii10034 /afii10035 /afii10036 /afii10037 /afii10038 /afii10039 /afii10040 /afii10041 -/afii10042 /afii10043 /afii10044 /afii10045 /afii10046 /afii10047 /afii10048 /afii10049 -/afii10065 /afii10066 /afii10067 /afii10068 /afii10069 /afii10070 /afii10072 /afii10073 -/afii10074 /afii10075 /afii10076 /afii10077 /afii10078 /afii10079 /afii10080 /afii10081 -/afii10082 /afii10083 /afii10084 /afii10085 /afii10086 /afii10087 /afii10088 /afii10089 -/afii10090 /afii10091 /afii10092 /afii10093 /afii10094 /afii10095 /afii10096 /afii10097 -/afii61352 /afii10071 /afii10099 /afii10100 /afii10101 /afii10102 /afii10103 /afii10104 -/afii10105 /afii10106 /afii10107 /afii10108 /afii10109 /section /afii10110 /afii10193] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-7.ps b/runtime/print/iso-8859-7.ps deleted file mode 100644 index fc16bf1a61..0000000000 --- a/runtime/print/iso-8859-7.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-7 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-7[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /quotereversed /quoteright /sterling /.notdef /.notdef /brokenbar /section -/dieresis /copyright /.notdef /guillemotleft /logicalnot /.notdef /.notdef /emdash -/degree /plusminus /twosuperior /threesuperior /tonos /dieresistonos /Alphatonos /periodcentered -/Epsilontonos /Etatonos /Iotatonos /guillemotright /Omicrontonos /onehalf /Upsilontonos /Omegatonos -/iotadieresistonos /Alpha /Beta /Gamma /Delta /Epsilon /Zeta /Eta -/Theta /Iota /Kappa /Lambda /Mu /Nu /Xi /Omicron -/Pi /Rho /.notdef /Sigma /Tau /Upsilon /Phi /Chi -/Psi /Omega /Iotadieresis /Upsilondieresis /alphatonos /epsilontonos /etatonos /iotatonos -/upsilondieresistonos /alpha /beta /gamma /delta /epsilon /zeta /eta -/theta /iota /kappa /lambda /mu /nu /xi /omicron -/pi /rho /sigma1 /sigma /tau /upsilon /phi /chi -/psi /omega /iotadieresis /upsilondieresis /omicrontonos /upsilontonos /omegatonos /.notdef] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-8.ps b/runtime/print/iso-8859-8.ps deleted file mode 100644 index 15193cc8ea..0000000000 --- a/runtime/print/iso-8859-8.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-8 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-8[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /.notdef /cent /sterling /currency /yen /brokenbar /section -/dieresis /copyright /multiply /guillemotleft /logicalnot /hyphen /registered /macron -/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered -/cedilla /onesuperior /divide /guillemotright /onequarter /onehalf /threequarters /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /underscoredbl -/alef /bet /gimel /dalet /he /vav /zayin /het -/tet /yod /finalkaf /kaf /lamed /finalmem /mem /finalnun -/nun /samekh /ayin /finalpe /pe /finaltsadi /tsadi /qof -/resh /shin /tav /.notdef /.notdef /.notdef /.notdef /.notdef] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/iso-8859-9.ps b/runtime/print/iso-8859-9.ps deleted file mode 100644 index d40f6e9864..0000000000 --- a/runtime/print/iso-8859-9.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-iso-8859-9 -%%Version: 1.0 0 -%%EndComments -/VIM-iso-8859-9[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclamdown /cent /sterling /currency /yen /brokenbar /section -/dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron -/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered -/cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown -/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla -/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis -/Gbreve /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply -/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Idotaccent /Scedilla /germandbls -/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla -/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis -/gbreve /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide -/oslash /ugrave /uacute /ucircumflex /udieresis /dotlessi /scedilla /ydieresis] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/jis_roman.ps b/runtime/print/jis_roman.ps deleted file mode 100644 index f24a8069a3..0000000000 --- a/runtime/print/jis_roman.ps +++ /dev/null @@ -1,23 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-jis_roman -%%Version: 1.0 0 -%%EndComments -% Different to ASCII at code points 92 and 126 -/VIM-jis_roman[ -32{/.notdef}repeat -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /yen /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /overline /.notdef -128{/.notdef}repeat] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/koi8-r.ps b/runtime/print/koi8-r.ps deleted file mode 100644 index d42daabb49..0000000000 --- a/runtime/print/koi8-r.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-koi8-r -%%Version: 1.0 0 -%%EndComments -/VIM-koi8-r[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/SF100000 /SF110000 /SF010000 /SF030000 /SF020000 /SF040000 /SF080000 /SF090000 -/SF060000 /SF070000 /SF050000 /upblock /dnblock /block /lfblock /rtblock -/ltshade /shade /dkshade /integraltp /filledbox /bullet /radical /approxequal -/lessequal /greaterequal /space /integralbt /degree /twosuperior /periodcentered /divide -/SF430000 /SF240000 /SF510000 /afii10071 /SF520000 /SF390000 /SF220000 /SF210000 -/SF250000 /SF500000 /SF490000 /SF380000 /SF280000 /SF270000 /SF260000 /SF360000 -/SF370000 /SF420000 /SF190000 /afii10023 /SF200000 /SF230000 /SF470000 /SF480000 -/SF410000 /SF450000 /SF460000 /SF400000 /SF540000 /SF530000 /SF440000 /copyright -/afii10096 /afii10065 /afii10066 /afii10088 /afii10069 /afii10070 /afii10086 /afii10068 -/afii10087 /afii10074 /afii10075 /afii10076 /afii10077 /afii10078 /afii10079 /afii10080 -/afii10081 /afii10097 /afii10082 /afii10083 /afii10084 /afii10085 /afii10072 /afii10067 -/afii10094 /afii10093 /afii10073 /afii10090 /afii10095 /afii10091 /afii10089 /afii10092 -/afii10048 /afii10017 /afii10018 /afii10040 /afii10021 /afii10022 /afii10038 /afii10020 -/afii10039 /afii10026 /afii10027 /afii10028 /afii10029 /afii10030 /afii10031 /afii10032 -/afii10033 /afii10049 /afii10034 /afii10035 /afii10036 /afii10037 /afii10024 /afii10019 -/afii10046 /afii10045 /afii10025 /afii10042 /afii10047 /afii10043 /afii10041 /afii10044] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/koi8-u.ps b/runtime/print/koi8-u.ps deleted file mode 100644 index 53631049fe..0000000000 --- a/runtime/print/koi8-u.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-koi8-u -%%Version: 1.0 0 -%%EndComments -/VIM-koi8-u[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/SF100000 /SF110000 /SF010000 /SF030000 /SF020000 /SF040000 /SF080000 /SF090000 -/SF060000 /SF070000 /SF050000 /upblock /dnblock /block /lfblock /rtblock -/ltshade /shade /dkshade /integraltp /filledbox /bullet /radical /approxequal -/lessequal /greaterequal /space /integralbt /degree /twosuperior /periodcentered /divide -/SF430000 /SF240000 /SF510000 /afii10071 /afii10101 /SF390000 /afii10103 /afii10104 -/SF250000 /SF500000 /SF490000 /SF380000 /SF280000 /afii10098 /SF260000 /SF360000 -/SF370000 /SF420000 /SF190000 /afii10023 /afii10053 /SF230000 /afii10055 /afii10056 -/SF410000 /SF450000 /SF460000 /SF400000 /SF540000 /afii10050 /SF440000 /copyright -/afii10096 /afii10065 /afii10066 /afii10088 /afii10069 /afii10070 /afii10086 /afii10068 -/afii10087 /afii10074 /afii10075 /afii10076 /afii10077 /afii10078 /afii10079 /afii10080 -/afii10081 /afii10097 /afii10082 /afii10083 /afii10084 /afii10085 /afii10072 /afii10067 -/afii10094 /afii10093 /afii10073 /afii10090 /afii10095 /afii10091 /afii10089 /afii10092 -/afii10048 /afii10017 /afii10018 /afii10040 /afii10021 /afii10022 /afii10038 /afii10020 -/afii10039 /afii10026 /afii10027 /afii10028 /afii10029 /afii10030 /afii10031 /afii10032 -/afii10033 /afii10049 /afii10034 /afii10035 /afii10036 /afii10037 /afii10024 /afii10019 -/afii10046 /afii10045 /afii10025 /afii10042 /afii10047 /afii10043 /afii10041 /afii10044] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/ks_roman.ps b/runtime/print/ks_roman.ps deleted file mode 100644 index b688550a65..0000000000 --- a/runtime/print/ks_roman.ps +++ /dev/null @@ -1,23 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-ks_roman -%%Version: 1.0 0 -%%EndComments -% Different to ASCII at code points 96 and 126 -/VIM-ks_roman[ -32{/.notdef}repeat -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /won /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /overline /.notdef -128{/.notdef}repeat] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/latin1.ps b/runtime/print/latin1.ps deleted file mode 100644 index 569db9bfe0..0000000000 --- a/runtime/print/latin1.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-latin1 -%%Version: 1.0 0 -%%EndComments -/VIM-latin1[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclamdown /cent /sterling /currency /yen /brokenbar /section -/dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron -/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered -/cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown -/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla -/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis -/Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply -/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls -/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla -/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis -/eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide -/oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/mac-roman.ps b/runtime/print/mac-roman.ps deleted file mode 100644 index b0941be650..0000000000 --- a/runtime/print/mac-roman.ps +++ /dev/null @@ -1,40 +0,0 @@ -%!PS-Adobe-3.0 Resource-Encoding -%%Title: VIM-mac-roman -%%Version: 1.0 0 -%%EndComments -/VIM-mac-roman[ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle -/parenleft /parenright /asterisk /plus /comma /minus /period /slash -/zero /one /two /three /four /five /six /seven -/eight /nine /colon /semicolon /less /equal /greater /question -/at /A /B /C /D /E /F /G -/H /I /J /K /L /M /N /O -/P /Q /R /S /T /U /V /W -/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore -/grave /a /b /c /d /e /f /g -/h /i /j /k /l /m /n /o -/p /q /r /s /t /u /v /w -/x /y /z /braceleft /bar /braceright /asciitilde /.notdef -/Adieresis /Aring /Ccedilla /Eacute /Ntilde /Odieresis /Udieresis /aacute -/agrave /acircumflex /adieresis /atilde /aring /ccedilla /eacute /egrave -/ecircumflex /edieresis /iacute /igrave /icircumflex /idieresis /ntilde /oacute -/ograve /ocircumflex /odieresis /otilde /uacute /ugrave /ucircumflex /udieresis -/dagger /degree /cent /sterling /section /bullet /paragraph /germandbls -/registered /copyright /trademark /acute /dieresis /notequal /AE /Oslash -/infinity /plusminus /lessequal /greaterequal /yen /mu /partialdiff /summation -/Pi /pi /integral /ordfeminine /ordmasculine /Omega /ae /oslash -/questiondown /exclamdown /logicalnot /radical /florin /approxequal /delta /guillemotleft -/guillemotright /ellipsis /space /Agrave /Atilde /Otilde /OE /oe -/endash /emdash /quotedblleft /quotedblright /quoteleft /quoteright /divide /lozenge -/ydieresis /Ydieresis /fraction /currency /guilsinglleft /guilsinglright /fi /fl -/daggerdbl /periodcentered /quotesinglbase /quotedblbase /perthousand /Acircumflex /Ecircumflex /Aacute -/Edieresis /Egrave /Iacute /Icircumflex /Idieresis /Igrave /Oacute /Ocircumflex -/heart /Ograve /Uacute /Ucircumflex /Ugrave /dotlessi /circumflex /tilde -/macron /breve /dotaccent /ring /cedilla /hungarumlaut /ogonek /caron] -/Encoding defineresource pop -% vim:ff=unix: -%%EOF diff --git a/runtime/print/prolog.ps b/runtime/print/prolog.ps deleted file mode 100644 index 620856999f..0000000000 --- a/runtime/print/prolog.ps +++ /dev/null @@ -1,44 +0,0 @@ -%!PS-Adobe-3.0 Resource-ProcSet -%%Title: VIM-Prolog -%%Version: 1.4 1 -%%EndComments -% Editing of this file is NOT RECOMMENDED. You run a very good risk of causing -% all PostScript printing from VIM failing if you do. PostScript is not called -% a write-only language for nothing! -/packedarray where not{userdict begin/setpacking/pop load def/currentpacking -false def end}{pop}ifelse/CP currentpacking def true setpacking -/bd{bind def}bind def/ld{load def}bd/ed{exch def}bd/d/def ld -/db{dict begin}bd/cde{currentdict end}bd -/T true d/F false d -/SO null d/sv{/SO save d}bd/re{SO restore}bd -/L2 systemdict/languagelevel 2 copy known{get exec}{pop pop 1}ifelse 2 ge d -/m/moveto ld/s/show ld /ms{m s}bd /g/setgray ld/r/setrgbcolor ld/sp{showpage}bd -/gs/gsave ld/gr/grestore ld/cp/currentpoint ld -/ul{gs UW setlinewidth cp UO add 2 copy newpath m 3 1 roll add exch lineto -stroke gr}bd -/bg{gs r cp BO add 4 -2 roll rectfill gr}bd -/sl{90 rotate 0 exch translate}bd -L2{ -/sspd{mark exch{setpagedevice}stopped cleartomark}bd -/nc{1 db/NumCopies ed cde sspd}bd -/sps{3 db/Orientation ed[3 1 roll]/PageSize ed/ImagingBBox null d cde sspd}bd -/dt{2 db/Tumble ed/Duplex ed cde sspd}bd -/c{1 db/Collate ed cde sspd}bd -}{ -/nc{/#copies ed}bd -/sps{statusdict/setpage get exec}bd -/dt{statusdict/settumble 2 copy known{get exec}{pop pop pop}ifelse -statusdict/setduplexmode 2 copy known{get exec}{pop pop pop}ifelse}bd -/c{pop}bd -}ifelse -/ffs{findfont exch scalefont d}bd/sf{setfont}bd -/ref{1 db findfont dup maxlength dict/NFD ed{exch dup/FID ne{exch NFD 3 1 roll -put}{pop pop}ifelse}forall/Encoding findresource dup length 256 eq{NFD/Encoding -3 -1 roll put}{pop}ifelse NFD dup/FontType get 3 ne{/CharStrings}{/CharProcs} -ifelse 2 copy known{2 copy get dup maxlength dict copy[/questiondown/space]{2 -copy known{2 copy get 2 index/.notdef 3 -1 roll put pop exit}if pop}forall put -}{pop pop}ifelse dup NFD/FontName 3 -1 roll put NFD definefont pop end}bd -CP setpacking -(\004)cvn{}bd -% vim:ff=unix: -%%EOF 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..c0d88301bc --- /dev/null +++ b/runtime/queries/help/highlights.scm @@ -0,0 +1,25 @@ +(h1) @text.title +(h2) @text.title +(h3) @text.title +(column_heading) @text.title +(column_heading + "~" @conceal (#set! conceal "")) +(tag + "*" @conceal (#set! conceal "") + text: (_) @label) +(taglink + "|" @conceal (#set! conceal "") + text: (_) @text.reference) +(optionlink + text: (_) @text.reference) +(codespan + "`" @conceal (#set! conceal "") + text: (_) @text.literal) +(codeblock) @text.literal +(codeblock + [">" (language)] @conceal (#set! conceal "")) +(block + "<" @conceal (#set! conceal "")) +(argument) @parameter +(keycode) @string.special +(url) @text.uri diff --git a/runtime/queries/help/injections.scm b/runtime/queries/help/injections.scm new file mode 100644 index 0000000000..09bbe44e84 --- /dev/null +++ b/runtime/queries/help/injections.scm @@ -0,0 +1,3 @@ +(codeblock + (language) @language + (code) @content) diff --git a/runtime/queries/lua/highlights.scm b/runtime/queries/lua/highlights.scm new file mode 100644 index 0000000000..2c0dc5447a --- /dev/null +++ b/runtime/queries/lua/highlights.scm @@ -0,0 +1,199 @@ +;; 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")) + +(variable_list + attribute: (attribute + (["<" ">"] @punctuation.bracket + (identifier) @attribute))) + +;; 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..239b0a0b37 --- /dev/null +++ b/runtime/queries/vim/highlights.scm @@ -0,0 +1,290 @@ +(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.call) +(call_expression function: (scoped_identifier (identifier) @function.call)) +(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" + "setfiletype" + "setlocal" + "silent" + "echo" + "echon" + "echohl" + "echomsg" + "echoerr" + "autocmd" + "augroup" + "return" + "syntax" + "filetype" + "source" + "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" + "eval" +] @keyword +(map_statement cmd: _ @keyword) +(command_name) @function.macro + +;; Filetype command + +(filetype_statement [ + "detect" + "plugin" + "indent" + "on" + "off" +] @keyword) + +;; Syntax command + +(syntax_statement (keyword) @string) +(syntax_statement [ + "enable" + "on" + "off" + "reset" + "case" + "spell" + "foldlevel" + "iskeyword" + "keyword" + "match" + "cluster" + "region" + "clear" + "include" +] @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 +(integer_literal) @number +(float_literal) @float +(comment) @comment @spell +(line_continuation_comment) @comment @spell +(pattern) @string.special +(pattern_multi) @string.regex +(filename) @string +(heredoc (body) @string) +(heredoc (parameter) @keyword) +[ (marker_definition) (endmarker) ] @label +(literal_dictionary (literal_key) @label) +((scoped_identifier + (scope) @_scope . (identifier) @boolean) + (#eq? @_scope "v:") + (#any-of? @boolean "true" "false")) + +;; Operators + +[ + "||" + "&&" + "&" + "+" + "-" + "*" + "/" + "%" + ".." + "is" + "isnot" + "==" + "!=" + ">" + ">=" + "<" + "<=" + "=~" + "!~" + "=" + "+=" + "-=" + "*=" + "/=" + "%=" + ".=" + "..=" + "<<" + "=<<" + (match_case) +] @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]+)?$")) + +(inv_option "!" @operator) +(set_item "?" @operator) + +((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..fdd025bfd9 --- /dev/null +++ b/runtime/queries/vim/injections.scm @@ -0,0 +1,28 @@ +(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) +;; If we support perl at some point... +;; (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 +(line_continuation_comment) @comment diff --git a/runtime/scripts.vim b/runtime/scripts.vim deleted file mode 100644 index 2d8bfdcb05..0000000000 --- a/runtime/scripts.vim +++ /dev/null @@ -1,459 +0,0 @@ -" Vim support file to detect file types in scripts -" -" Maintainer: Bram Moolenaar <Bram@vim.org> -" Last change: 2021 Jan 22 - -" This file is called by an autocommand for every file that has just been -" loaded into a buffer. It checks if the type of file can be recognized by -" the file contents. The autocommand is in $VIMRUNTIME/filetype.vim. -" -" Note that the pattern matches are done with =~# to avoid the value of the -" 'ignorecase' option making a difference. Where case is to be ignored use -" =~? instead. Do not use =~ anywhere. - -" Only run when using legacy filetype -if !exists('g:do_legacy_filetype') - finish -endif - -" Only do the rest when the FileType autocommand has not been triggered yet. -if did_filetype() - finish -endif - -" Load the user defined scripts file first -" Only do this when the FileType autocommand has not been triggered yet -if exists("myscriptsfile") && filereadable(expand(myscriptsfile)) - execute "source " . myscriptsfile - if did_filetype() - finish - endif -endif - -" Line continuation is used here, remove 'C' from 'cpoptions' -let s:cpo_save = &cpo -set cpo&vim - -let s:line1 = getline(1) - -if s:line1 =~# "^#!" - " A script that starts with "#!". - - " Check for a line like "#!/usr/bin/env {options} bash". Turn it into - " "#!/usr/bin/bash" to make matching easier. - " Recognize only a few {options} that are commonly used. - if s:line1 =~# '^#!\s*\S*\<env\s' - let s:line1 = substitute(s:line1, '\S\+=\S\+', '', 'g') - let s:line1 = substitute(s:line1, '\(-[iS]\|--ignore-environment\|--split-string\)', '', '') - let s:line1 = substitute(s:line1, '\<env\s\+', '', '') - endif - - " Get the program name. - " Only accept spaces in PC style paths: "#!c:/program files/perl [args]". - " If the word env is used, use the first word after the space: - " "#!/usr/bin/env perl [path/args]" - " If there is no path use the first word: "#!perl [path/args]". - " Otherwise get the last word after a slash: "#!/usr/bin/perl [path/args]". - if s:line1 =~# '^#!\s*\a:[/\\]' - let s:name = substitute(s:line1, '^#!.*[/\\]\(\i\+\).*', '\1', '') - elseif s:line1 =~# '^#!.*\<env\>' - let s:name = substitute(s:line1, '^#!.*\<env\>\s\+\(\i\+\).*', '\1', '') - elseif s:line1 =~# '^#!\s*[^/\\ ]*\>\([^/\\]\|$\)' - let s:name = substitute(s:line1, '^#!\s*\([^/\\ ]*\>\).*', '\1', '') - else - let s:name = substitute(s:line1, '^#!\s*\S*[/\\]\(\i\+\).*', '\1', '') - endif - - " tcl scripts may have #!/bin/sh in the first line and "exec wish" in the - " third line. Suggested by Steven Atkinson. - if getline(3) =~# '^exec wish' - let s:name = 'wish' - endif - - " Bourne-like shell scripts: bash bash2 ksh ksh93 sh - if s:name =~# '^\(bash\d*\|\|ksh\d*\|sh\)\>' - call dist#ft#SetFileTypeSH(s:line1) " defined in filetype.vim - - " csh scripts - elseif s:name =~# '^csh\>' - if exists("g:filetype_csh") - call dist#ft#SetFileTypeShell(g:filetype_csh) - else - call dist#ft#SetFileTypeShell("csh") - endif - - " tcsh scripts - elseif s:name =~# '^tcsh\>' - call dist#ft#SetFileTypeShell("tcsh") - - " Z shell scripts - elseif s:name =~# '^zsh\>' - set ft=zsh - - " TCL scripts - elseif s:name =~# '^\(tclsh\|wish\|expectk\|itclsh\|itkwish\)\>' - set ft=tcl - - " Expect scripts - elseif s:name =~# '^expect\>' - set ft=expect - - " Gnuplot scripts - elseif s:name =~# '^gnuplot\>' - set ft=gnuplot - - " Makefiles - elseif s:name =~# 'make\>' - set ft=make - - " Pike - elseif s:name =~# '^pike\%(\>\|[0-9]\)' - set ft=pike - - " Lua - elseif s:name =~# 'lua' - set ft=lua - - " Perl - elseif s:name =~# 'perl' - set ft=perl - - " PHP - elseif s:name =~# 'php' - set ft=php - - " Python - elseif s:name =~# 'python' - set ft=python - - " Groovy - elseif s:name =~# '^groovy\>' - set ft=groovy - - " Raku - elseif s:name =~# 'raku' - set ft=raku - - " Ruby - elseif s:name =~# 'ruby' - set ft=ruby - - " JavaScript - elseif s:name =~# 'node\(js\)\=\>\|js\>' || s:name =~# 'rhino\>' - set ft=javascript - - " BC calculator - elseif s:name =~# '^bc\>' - set ft=bc - - " sed - elseif s:name =~# 'sed\>' - set ft=sed - - " OCaml-scripts - elseif s:name =~# 'ocaml' - set ft=ocaml - - " Awk scripts; also finds "gawk" - elseif s:name =~# 'awk\>' - set ft=awk - - " Website MetaLanguage - elseif s:name =~# 'wml' - set ft=wml - - " Scheme scripts - elseif s:name =~# 'scheme' - set ft=scheme - - " CFEngine scripts - elseif s:name =~# 'cfengine' - set ft=cfengine - - " Erlang scripts - elseif s:name =~# 'escript' - set ft=erlang - - " Haskell - elseif s:name =~# 'haskell' - set ft=haskell - - " Scala - elseif s:name =~# 'scala\>' - set ft=scala - - " Clojure - elseif s:name =~# 'clojure' - set ft=clojure - - " Free Pascal - elseif s:name =~# 'instantfpc\>' - set ft=pascal - - " Fennel - elseif s:name =~# 'fennel\>' - set ft=fennel - - " MikroTik RouterOS script - elseif s:name =~# 'rsc\>' - set ft=routeros - - " Fish shell - elseif s:name =~# 'fish\>' - set ft=fish - - " Gforth - elseif s:name =~# 'gforth\>' - set ft=forth - - " Icon - elseif s:name =~# 'icon\>' - set ft=icon - - " Guile - elseif s:name =~# 'guile' - set ft=scheme - - endif - unlet s:name - -else - " File does not start with "#!". - - let s:line2 = getline(2) - let s:line3 = getline(3) - let s:line4 = getline(4) - let s:line5 = getline(5) - - " Bourne-like shell scripts: sh ksh bash bash2 - if s:line1 =~# '^:$' - call dist#ft#SetFileTypeSH(s:line1) " defined in filetype.vim - - " Z shell scripts - elseif s:line1 =~# '^#compdef\>' || s:line1 =~# '^#autoload\>' || - \ "\n".s:line1."\n".s:line2."\n".s:line3."\n".s:line4."\n".s:line5 =~# '\n\s*emulate\s\+\%(-[LR]\s\+\)\=[ckz]\=sh\>' - set ft=zsh - - " ELM Mail files - elseif s:line1 =~# '^From \([a-zA-Z][a-zA-Z_0-9\.=-]*\(@[^ ]*\)\=\|-\) .* \(19\|20\)\d\d$' - set ft=mail - - " Mason - elseif s:line1 =~# '^<[%&].*>' - set ft=mason - - " Vim scripts (must have '" vim' as the first line to trigger this) - elseif s:line1 =~# '^" *[vV]im$' - set ft=vim - - " libcxx and libstdc++ standard library headers like "iostream" do not have - " an extension, recognize the Emacs file mode. - elseif s:line1 =~? '-\*-.*C++.*-\*-' - set ft=cpp - - " MOO - elseif s:line1 =~# '^\*\* LambdaMOO Database, Format Version \%([1-3]\>\)\@!\d\+ \*\*$' - set ft=moo - - " Diff file: - " - "diff" in first line (context diff) - " - "Only in " in first line - " - "--- " in first line and "+++ " in second line (unified diff). - " - "*** " in first line and "--- " in second line (context diff). - " - "# It was generated by makepatch " in the second line (makepatch diff). - " - "Index: <filename>" in the first line (CVS file) - " - "=== ", line of "=", "---", "+++ " (SVK diff) - " - "=== ", "--- ", "+++ " (bzr diff, common case) - " - "=== (removed|added|renamed|modified)" (bzr diff, alternative) - " - "# HG changeset patch" in first line (Mercurial export format) - elseif s:line1 =~# '^\(diff\>\|Only in \|\d\+\(,\d\+\)\=[cda]\d\+\>\|# It was generated by makepatch \|Index:\s\+\f\+\r\=$\|===== \f\+ \d\+\.\d\+ vs edited\|==== //\f\+#\d\+\|# HG changeset patch\)' - \ || (s:line1 =~# '^--- ' && s:line2 =~# '^+++ ') - \ || (s:line1 =~# '^\* looking for ' && s:line2 =~# '^\* comparing to ') - \ || (s:line1 =~# '^\*\*\* ' && s:line2 =~# '^--- ') - \ || (s:line1 =~# '^=== ' && ((s:line2 =~# '^=\{66\}' && s:line3 =~# '^--- ' && s:line4 =~# '^+++') || (s:line2 =~# '^--- ' && s:line3 =~# '^+++ '))) - \ || (s:line1 =~# '^=== \(removed\|added\|renamed\|modified\)') - set ft=diff - - " PostScript Files (must have %!PS as the first line, like a2ps output) - elseif s:line1 =~# '^%![ \t]*PS' - set ft=postscr - - " M4 scripts: Guess there is a line that starts with "dnl". - elseif s:line1 =~# '^\s*dnl\>' - \ || s:line2 =~# '^\s*dnl\>' - \ || s:line3 =~# '^\s*dnl\>' - \ || s:line4 =~# '^\s*dnl\>' - \ || s:line5 =~# '^\s*dnl\>' - set ft=m4 - - " AmigaDos scripts - elseif $TERM == "amiga" - \ && (s:line1 =~# "^;" || s:line1 =~? '^\.bra') - set ft=amiga - - " SiCAD scripts (must have procn or procd as the first line to trigger this) - elseif s:line1 =~? '^ *proc[nd] *$' - set ft=sicad - - " Purify log files start with "**** Purify" - elseif s:line1 =~# '^\*\*\*\* Purify' - set ft=purifylog - - " XML - elseif s:line1 =~# '<?\s*xml.*?>' - set ft=xml - - " XHTML (e.g.: PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN") - elseif s:line1 =~# '\<DTD\s\+XHTML\s' - set ft=xhtml - - " HTML (e.g.: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN") - " Avoid "doctype html", used by slim. - elseif s:line1 =~? '<!DOCTYPE\s\+html\>' - set ft=html - - " PDF - elseif s:line1 =~# '^%PDF-' - set ft=pdf - - " XXD output - elseif s:line1 =~# '^\x\{7}: \x\{2} \=\x\{2} \=\x\{2} \=\x\{2} ' - set ft=xxd - - " RCS/CVS log output - elseif s:line1 =~# '^RCS file:' || s:line2 =~# '^RCS file:' - set ft=rcslog - - " CVS commit - elseif s:line2 =~# '^CVS:' || getline("$") =~# '^CVS: ' - set ft=cvs - - " Prescribe - elseif s:line1 =~# '^!R!' - set ft=prescribe - - " Send-pr - elseif s:line1 =~# '^SEND-PR:' - set ft=sendpr - - " SNNS files - elseif s:line1 =~# '^SNNS network definition file' - set ft=snnsnet - elseif s:line1 =~# '^SNNS pattern definition file' - set ft=snnspat - elseif s:line1 =~# '^SNNS result file' - set ft=snnsres - - " Virata - elseif s:line1 =~# '^%.\{-}[Vv]irata' - \ || s:line2 =~# '^%.\{-}[Vv]irata' - \ || s:line3 =~# '^%.\{-}[Vv]irata' - \ || s:line4 =~# '^%.\{-}[Vv]irata' - \ || s:line5 =~# '^%.\{-}[Vv]irata' - set ft=virata - - " Strace - elseif s:line1 =~# '[0-9:.]* *execve(' || s:line1 =~# '^__libc_start_main' - set ft=strace - - " VSE JCL - elseif s:line1 =~# '^\* $$ JOB\>' || s:line1 =~# '^// *JOB\>' - set ft=vsejcl - - " TAK and SINDA - elseif s:line4 =~# 'K & K Associates' || s:line2 =~# 'TAK 2000' - set ft=takout - elseif s:line3 =~# 'S Y S T E M S I M P R O V E D ' - set ft=sindaout - elseif getline(6) =~# 'Run Date: ' - set ft=takcmp - elseif getline(9) =~# 'Node File 1' - set ft=sindacmp - - " DNS zone files - elseif s:line1.s:line2.s:line3.s:line4 =~# '^; <<>> DiG [0-9.]\+.* <<>>\|$ORIGIN\|$TTL\|IN\s\+SOA' - set ft=bindzone - - " BAAN - elseif s:line1 =~# '|\*\{1,80}' && s:line2 =~# 'VRC ' - \ || s:line2 =~# '|\*\{1,80}' && s:line3 =~# 'VRC ' - set ft=baan - - " Valgrind - elseif s:line1 =~# '^==\d\+== valgrind' || s:line3 =~# '^==\d\+== Using valgrind' - set ft=valgrind - - " Go docs - elseif s:line1 =~# '^PACKAGE DOCUMENTATION$' - set ft=godoc - - " Renderman Interface Bytestream - elseif s:line1 =~# '^##RenderMan' - set ft=rib - - " Scheme scripts - elseif s:line1 =~# 'exec\s\+\S*scheme' || s:line2 =~# 'exec\s\+\S*scheme' - set ft=scheme - - " Git output - elseif s:line1 =~# '^\(commit\|tree\|object\) \x\{40,\}\>\|^tag \S\+$' - set ft=git - - " Gprof (gnu profiler) - elseif s:line1 == 'Flat profile:' - \ && s:line2 == '' - \ && s:line3 =~# '^Each sample counts as .* seconds.$' - set ft=gprof - - " Erlang terms - " (See also: http://www.gnu.org/software/emacs/manual/html_node/emacs/Choosing-Modes.html#Choosing-Modes) - elseif s:line1 =~? '-\*-.*erlang.*-\*-' - set ft=erlang - - " YAML - elseif s:line1 =~# '^%YAML' - set ft=yaml - - " MikroTik RouterOS script - elseif s:line1 =~# '^#.*by RouterOS.*$' - set ft=routeros - - " Sed scripts - " #ncomment is allowed but most likely a false positive so require a space - " before any trailing comment text - elseif s:line1 =~# '^#n\%($\|\s\)' - set ft=sed - - " CVS diff - else - let s:lnum = 1 - while getline(s:lnum) =~# "^? " && s:lnum < line("$") - let s:lnum += 1 - endwhile - if getline(s:lnum) =~# '^Index:\s\+\f\+$' - set ft=diff - - " locale input files: Formal Definitions of Cultural Conventions - " filename must be like en_US, fr_FR@euro or en_US.UTF-8 - elseif expand("%") =~# '\a\a_\a\a\($\|[.@]\)\|i18n$\|POSIX$\|translit_' - let s:lnum = 1 - while s:lnum < 100 && s:lnum < line("$") - if getline(s:lnum) =~# '^LC_\(IDENTIFICATION\|CTYPE\|COLLATE\|MONETARY\|NUMERIC\|TIME\|MESSAGES\|PAPER\|TELEPHONE\|MEASUREMENT\|NAME\|ADDRESS\)$' - setf fdcc - break - endif - let s:lnum += 1 - endwhile - endif - unlet s:lnum - - endif - - unlet s:line2 s:line3 s:line4 s:line5 - -endif - -" Restore 'cpoptions' -let &cpo = s:cpo_save - -unlet s:cpo_save s:line1 diff --git a/runtime/synmenu.vim b/runtime/synmenu.vim index ba9e6a198d..a664e7689d 100644 --- a/runtime/synmenu.vim +++ b/runtime/synmenu.vim @@ -2,7 +2,7 @@ " This file is normally sourced from menu.vim. " " Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2017 Oct 28 +" Last Change: 2022 Oct 04 " Define the SetSyn function, used for the Syntax menu entries. " Set 'filetype' and also 'syntax' if it is manually selected. diff --git a/runtime/syntax/2html.vim b/runtime/syntax/2html.vim index 8adbd76950..ce6797deaa 100644 --- a/runtime/syntax/2html.vim +++ b/runtime/syntax/2html.vim @@ -1,6 +1,6 @@ " Vim syntax support file " Maintainer: Ben Fritz <fritzophrenic@gmail.com> -" Last Change: 2020 Jan 05 +" Last Change: 2022 Dec 26 " " Additional contributors: " @@ -815,202 +815,204 @@ endif " HTML header, with the title and generator ;-). Left free space for the CSS, " to be filled at the end. -call extend(s:lines, [ - \ "<html>", - \ "<head>"]) -" include encoding as close to the top as possible, but only if not already -" contained in XML information (to avoid haggling over content type) -if s:settings.encoding != "" && !s:settings.use_xhtml - if s:html5 - call add(s:lines, '<meta charset="' . s:settings.encoding . '"' . s:tag_close) - else - call add(s:lines, "<meta http-equiv=\"content-type\" content=\"text/html; charset=" . s:settings.encoding . '"' . s:tag_close) - endif -endif -call extend(s:lines, [ - \ ("<title>".expand("%:p:~")."</title>"), - \ ("<meta name=\"Generator\" content=\"Vim/".v:version/100.".".v:version%100.'"'.s:tag_close), - \ ("<meta name=\"plugin-version\" content=\"".s:pluginversion.'"'.s:tag_close) - \ ]) -call add(s:lines, '<meta name="syntax" content="'.s:current_syntax.'"'.s:tag_close) -call add(s:lines, '<meta name="settings" content="'. - \ join(filter(keys(s:settings),'s:settings[v:val]'),','). - \ ',prevent_copy='.s:settings.prevent_copy. - \ ',use_input_for_pc='.s:settings.use_input_for_pc. - \ '"'.s:tag_close) -call add(s:lines, '<meta name="colorscheme" content="'. - \ (exists('g:colors_name') - \ ? g:colors_name - \ : 'none'). '"'.s:tag_close) - -if s:settings.use_css +if !s:settings.no_doc call extend(s:lines, [ - \ "<style" . (s:html5 ? "" : " type=\"text/css\"") . ">", - \ s:settings.use_xhtml ? "" : "<!--"]) - let s:ieonly = [] - if s:settings.dynamic_folds - if s:settings.hover_unfold - " if we are doing hover_unfold, use css 2 with css 1 fallback for IE6 - call extend(s:lines, [ - \ ".FoldColumn { text-decoration: none; white-space: pre; }", - \ "", - \ "body * { margin: 0; padding: 0; }", "", - \ ".open-fold > span.Folded { display: none; }", - \ ".open-fold > .fulltext { display: inline; }", - \ ".closed-fold > .fulltext { display: none; }", - \ ".closed-fold > span.Folded { display: inline; }", - \ "", - \ ".open-fold > .toggle-open { display: none; }", - \ ".open-fold > .toggle-closed { display: inline; }", - \ ".closed-fold > .toggle-open { display: inline; }", - \ ".closed-fold > .toggle-closed { display: none; }", - \ "", "", - \ '/* opening a fold while hovering won''t be supported by IE6 and other', - \ "similar browsers, but it should fail gracefully. */", - \ ".closed-fold:hover > .fulltext { display: inline; }", - \ ".closed-fold:hover > .toggle-filler { display: none; }", - \ ".closed-fold:hover > .Folded { display: none; }"]) - " TODO: IE6 is REALLY old and I can't even test it anymore. Maybe we - " should remove this? Leave it in for now, it was working at one point, - " and doesn't affect any modern browsers. Even newer IE versions should - " support the above code and ignore the following. - let s:ieonly = [ - \ "<!--[if lt IE 7]><style type=\"text/css\">", - \ ".open-fold .fulltext { display: inline; }", - \ ".open-fold span.Folded { display: none; }", - \ ".open-fold .toggle-open { display: none; }", - \ ".open-fold .toggle-closed { display: inline; }", - \ "", - \ ".closed-fold .fulltext { display: none; }", - \ ".closed-fold span.Folded { display: inline; }", - \ ".closed-fold .toggle-open { display: inline; }", - \ ".closed-fold .toggle-closed { display: none; }", - \ "</style>", - \ "<![endif]-->", - \] + \ "<html>", + \ "<head>"]) + " include encoding as close to the top as possible, but only if not already + " contained in XML information (to avoid haggling over content type) + if s:settings.encoding != "" && !s:settings.use_xhtml + if s:html5 + call add(s:lines, '<meta charset="' . s:settings.encoding . '"' . s:tag_close) else - " if we aren't doing hover_unfold, use CSS 1 only - call extend(s:lines, [ - \ ".FoldColumn { text-decoration: none; white-space: pre; }", - \ ".open-fold .fulltext { display: inline; }", - \ ".open-fold span.Folded { display: none; }", - \ ".open-fold .toggle-open { display: none; }", - \ ".open-fold .toggle-closed { display: inline; }", - \ "", - \ ".closed-fold .fulltext { display: none; }", - \ ".closed-fold span.Folded { display: inline; }", - \ ".closed-fold .toggle-open { display: inline; }", - \ ".closed-fold .toggle-closed { display: none; }", - \]) + call add(s:lines, "<meta http-equiv=\"content-type\" content=\"text/html; charset=" . s:settings.encoding . '"' . s:tag_close) endif endif - " else we aren't doing any dynamic folding, no need for any special rules - call extend(s:lines, [ - \ s:settings.use_xhtml ? "" : '-->', - \ "</style>", - \]) - call extend(s:lines, s:ieonly) - unlet s:ieonly -endif + \ ("<title>".expand("%:p:~")."</title>"), + \ ("<meta name=\"Generator\" content=\"Vim/".v:version/100.".".v:version%100.'"'.s:tag_close), + \ ("<meta name=\"plugin-version\" content=\"".s:pluginversion.'"'.s:tag_close) + \ ]) + call add(s:lines, '<meta name="syntax" content="'.s:current_syntax.'"'.s:tag_close) + call add(s:lines, '<meta name="settings" content="'. + \ join(filter(keys(s:settings),'s:settings[v:val]'),','). + \ ',prevent_copy='.s:settings.prevent_copy. + \ ',use_input_for_pc='.s:settings.use_input_for_pc. + \ '"'.s:tag_close) + call add(s:lines, '<meta name="colorscheme" content="'. + \ (exists('g:colors_name') + \ ? g:colors_name + \ : 'none'). '"'.s:tag_close) -let s:uses_script = s:settings.dynamic_folds || s:settings.line_ids + if s:settings.use_css + call extend(s:lines, [ + \ "<style" . (s:html5 ? "" : " type=\"text/css\"") . ">", + \ s:settings.use_xhtml ? "" : "<!--"]) + let s:ieonly = [] + if s:settings.dynamic_folds + if s:settings.hover_unfold + " if we are doing hover_unfold, use css 2 with css 1 fallback for IE6 + call extend(s:lines, [ + \ ".FoldColumn { text-decoration: none; white-space: pre; }", + \ "", + \ "body * { margin: 0; padding: 0; }", "", + \ ".open-fold > span.Folded { display: none; }", + \ ".open-fold > .fulltext { display: inline; }", + \ ".closed-fold > .fulltext { display: none; }", + \ ".closed-fold > span.Folded { display: inline; }", + \ "", + \ ".open-fold > .toggle-open { display: none; }", + \ ".open-fold > .toggle-closed { display: inline; }", + \ ".closed-fold > .toggle-open { display: inline; }", + \ ".closed-fold > .toggle-closed { display: none; }", + \ "", "", + \ '/* opening a fold while hovering won''t be supported by IE6 and other', + \ "similar browsers, but it should fail gracefully. */", + \ ".closed-fold:hover > .fulltext { display: inline; }", + \ ".closed-fold:hover > .toggle-filler { display: none; }", + \ ".closed-fold:hover > .Folded { display: none; }"]) + " TODO: IE6 is REALLY old and I can't even test it anymore. Maybe we + " should remove this? Leave it in for now, it was working at one point, + " and doesn't affect any modern browsers. Even newer IE versions should + " support the above code and ignore the following. + let s:ieonly = [ + \ "<!--[if lt IE 7]><style type=\"text/css\">", + \ ".open-fold .fulltext { display: inline; }", + \ ".open-fold span.Folded { display: none; }", + \ ".open-fold .toggle-open { display: none; }", + \ ".open-fold .toggle-closed { display: inline; }", + \ "", + \ ".closed-fold .fulltext { display: none; }", + \ ".closed-fold span.Folded { display: inline; }", + \ ".closed-fold .toggle-open { display: inline; }", + \ ".closed-fold .toggle-closed { display: none; }", + \ "</style>", + \ "<![endif]-->", + \] + else + " if we aren't doing hover_unfold, use CSS 1 only + call extend(s:lines, [ + \ ".FoldColumn { text-decoration: none; white-space: pre; }", + \ ".open-fold .fulltext { display: inline; }", + \ ".open-fold span.Folded { display: none; }", + \ ".open-fold .toggle-open { display: none; }", + \ ".open-fold .toggle-closed { display: inline; }", + \ "", + \ ".closed-fold .fulltext { display: none; }", + \ ".closed-fold span.Folded { display: inline; }", + \ ".closed-fold .toggle-open { display: inline; }", + \ ".closed-fold .toggle-closed { display: none; }", + \]) + endif + endif + " else we aren't doing any dynamic folding, no need for any special rules -" insert script tag if needed -if s:uses_script - call extend(s:lines, [ - \ "", - \ "<script" . (s:html5 ? "" : " type='text/javascript'") . ">", - \ s:settings.use_xhtml ? '//<![CDATA[' : "<!--"]) -endif + call extend(s:lines, [ + \ s:settings.use_xhtml ? "" : '-->', + \ "</style>", + \]) + call extend(s:lines, s:ieonly) + unlet s:ieonly + endif -" insert javascript to toggle folds open and closed -if s:settings.dynamic_folds - call extend(s:lines, [ - \ "", - \ "function toggleFold(objID)", - \ "{", - \ " var fold;", - \ " fold = document.getElementById(objID);", - \ " if (fold.className == 'closed-fold')", - \ " {", - \ " fold.className = 'open-fold';", - \ " }", - \ " else if (fold.className == 'open-fold')", - \ " {", - \ " fold.className = 'closed-fold';", - \ " }", - \ "}" - \ ]) -endif + let s:uses_script = s:settings.dynamic_folds || s:settings.line_ids -if s:settings.line_ids - " insert javascript to get IDs from line numbers, and to open a fold before - " jumping to any lines contained therein - call extend(s:lines, [ - \ "", - \ "/* function to open any folds containing a jumped-to line before jumping to it */", - \ "function JumpToLine()", - \ "{", - \ " var lineNum;", - \ " lineNum = window.location.hash;", - \ " lineNum = lineNum.substr(1); /* strip off '#' */", - \ "", - \ " if (lineNum.indexOf('L') == -1) {", - \ " lineNum = 'L'+lineNum;", - \ " }", - \ " var lineElem = document.getElementById(lineNum);" - \ ]) + " insert script tag if needed + if s:uses_script + call extend(s:lines, [ + \ "", + \ "<script" . (s:html5 ? "" : " type='text/javascript'") . ">", + \ s:settings.use_xhtml ? '//<![CDATA[' : "<!--"]) + endif + " insert javascript to toggle folds open and closed if s:settings.dynamic_folds call extend(s:lines, [ \ "", - \ " /* navigate upwards in the DOM tree to open all folds containing the line */", - \ " var node = lineElem;", - \ " while (node && node.id != 'vimCodeElement".s:settings.id_suffix."')", + \ "function toggleFold(objID)", + \ "{", + \ " var fold;", + \ " fold = document.getElementById(objID);", + \ " if (fold.className == 'closed-fold')", + \ " {", + \ " fold.className = 'open-fold';", + \ " }", + \ " else if (fold.className == 'open-fold')", \ " {", - \ " if (node.className == 'closed-fold')", - \ " {", - \ " node.className = 'open-fold';", - \ " }", - \ " node = node.parentNode;", + \ " fold.className = 'closed-fold';", \ " }", + \ "}" \ ]) endif - call extend(s:lines, [ - \ " /* Always jump to new location even if the line was hidden inside a fold, or", - \ " * we corrected the raw number to a line ID.", - \ " */", - \ " if (lineElem) {", - \ " lineElem.scrollIntoView(true);", - \ " }", - \ " return true;", - \ "}", - \ "if ('onhashchange' in window) {", - \ " window.onhashchange = JumpToLine;", - \ "}" - \ ]) -endif -" insert script closing tag if needed -if s:uses_script - call extend(s:lines, [ - \ '', - \ s:settings.use_xhtml ? '//]]>' : '-->', - \ "</script>" - \ ]) -endif + if s:settings.line_ids + " insert javascript to get IDs from line numbers, and to open a fold before + " jumping to any lines contained therein + call extend(s:lines, [ + \ "", + \ "/* function to open any folds containing a jumped-to line before jumping to it */", + \ "function JumpToLine()", + \ "{", + \ " var lineNum;", + \ " lineNum = window.location.hash;", + \ " lineNum = lineNum.substr(1); /* strip off '#' */", + \ "", + \ " if (lineNum.indexOf('L') == -1) {", + \ " lineNum = 'L'+lineNum;", + \ " }", + \ " var lineElem = document.getElementById(lineNum);" + \ ]) + + if s:settings.dynamic_folds + call extend(s:lines, [ + \ "", + \ " /* navigate upwards in the DOM tree to open all folds containing the line */", + \ " var node = lineElem;", + \ " while (node && node.id != 'vimCodeElement".s:settings.id_suffix."')", + \ " {", + \ " if (node.className == 'closed-fold')", + \ " {", + \ " node.className = 'open-fold';", + \ " }", + \ " node = node.parentNode;", + \ " }", + \ ]) + endif + call extend(s:lines, [ + \ " /* Always jump to new location even if the line was hidden inside a fold, or", + \ " * we corrected the raw number to a line ID.", + \ " */", + \ " if (lineElem) {", + \ " lineElem.scrollIntoView(true);", + \ " }", + \ " return true;", + \ "}", + \ "if ('onhashchange' in window) {", + \ " window.onhashchange = JumpToLine;", + \ "}" + \ ]) + endif -call extend(s:lines, ["</head>", - \ "<body".(s:settings.line_ids ? " onload='JumpToLine();'" : "").">"]) + " insert script closing tag if needed + if s:uses_script + call extend(s:lines, [ + \ '', + \ s:settings.use_xhtml ? '//]]>' : '-->', + \ "</script>" + \ ]) + endif + + call extend(s:lines, ["</head>", + \ "<body".(s:settings.line_ids ? " onload='JumpToLine();'" : "").">"]) +endif if s:settings.no_pre " if we're not using CSS we use a font tag which can't have a div inside if s:settings.use_css - call extend(s:lines, ["<div id='vimCodeElement".s:settings.id_suffix."'>"]) + call extend(s:lines, ["<div id='vimCodeElement" .. s:settings.id_suffix .. "'>"]) endif else - call extend(s:lines, ["<pre id='vimCodeElement".s:settings.id_suffix."'>"]) + call extend(s:lines, ["<pre id='vimCodeElement" .. s:settings.id_suffix .. "'>"]) endif exe s:orgwin . "wincmd w" @@ -1721,12 +1723,15 @@ endif if s:settings.no_pre if !s:settings.use_css " Close off the font tag that encapsulates the whole <body> - call extend(s:lines, ["</font>", "</body>", "</html>"]) + call extend(s:lines, ["</font>"]) else - call extend(s:lines, ["</div>", "</body>", "</html>"]) + call extend(s:lines, ["</div>"]) endif else - call extend(s:lines, ["</pre>", "</body>", "</html>"]) + call extend(s:lines, ["</pre>"]) +endif +if !s:settings.no_doc + call extend(s:lines, ["</body>", "</html>"]) endif exe s:newwin . "wincmd w" @@ -1742,15 +1747,15 @@ unlet s:lines " The generated HTML is admittedly ugly and takes a LONG time to fold. " Make sure the user doesn't do syntax folding when loading a generated file, " using a modeline. -call append(line('$'), "<!-- vim: set foldmethod=manual : -->") +if !s:settings.no_modeline + call append(line('$'), "<!-- vim: set foldmethod=manual : -->") +endif " Now, when we finally know which, we define the colors and styles -if s:settings.use_css +if s:settings.use_css && !s:settings.no_doc 1;/<style\>/+1 -endif -" Normal/global attributes -if s:settings.use_css + " Normal/global attributes if s:settings.no_pre call append('.', "body { color: " . s:fgc . "; background-color: " . s:bgc . "; font-family: ". s:htmlfont ."; }") + @@ -1874,7 +1879,9 @@ if s:settings.use_css endif endif endif -else +endif + +if !s:settings.use_css && !s:settings.no_doc " For Netscape 4, set <body> attributes too, though, strictly speaking, it's " incorrect. execute '%s:<body\([^>]*\):<body bgcolor="' . s:bgc . '" text="' . s:fgc . '"\1>\r<font face="'. s:htmlfont .'"' @@ -1882,7 +1889,7 @@ endif " Gather attributes for all other classes. Do diff first so that normal " highlight groups are inserted before it. -if s:settings.use_css +if s:settings.use_css && !s:settings.no_doc if s:diff_mode call append('.', filter(map(keys(s:diffstylelist), "s:diffstylelist[v:val]"), 'v:val != ""')) endif @@ -1892,20 +1899,22 @@ if s:settings.use_css endif " Add hyperlinks -" TODO: add option to not do this? Maybe just make the color the same as the -" text highlight group normally is? -%s+\(https\=://\S\{-}\)\(\([.,;:}]\=\(\s\|$\)\)\|[\\"'<>]\|>\|<\|"\)+<a href="\1">\1</a>\2+ge +if !s:settings.no_links + %s+\(https\=://\S\{-}\)\(\([.,;:}]\=\(\s\|$\)\)\|[\\"'<>]\|>\|<\|"\)+<a href="\1">\1</a>\2+ge +endif " The DTD -if s:settings.use_xhtml - exe "normal! gg$a\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" -elseif s:html5 - exe "normal! gg0i<!DOCTYPE html>\n" -else - exe "normal! gg0i<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" +if !s:settings.no_doc + if s:settings.use_xhtml + exe "normal! gg$a\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" + elseif s:html5 + exe "normal! gg0i<!DOCTYPE html>\n" + else + exe "normal! gg0i<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" + endif endif -if s:settings.use_xhtml +if s:settings.use_xhtml && !s:settings.no_doc exe "normal! gg/<html/e\na xmlns=\"http://www.w3.org/1999/xhtml\"\e" endif diff --git a/runtime/syntax/c.vim b/runtime/syntax/c.vim index 890e9ae1a7..50878a78ea 100644 --- a/runtime/syntax/c.vim +++ b/runtime/syntax/c.vim @@ -1,7 +1,7 @@ " Vim syntax file " Language: C " Maintainer: Bram Moolenaar <Bram@vim.org> -" Last Change: 2022 Apr 24 +" Last Change: 2022 Oct 05 " Quit when a (custom) syntax file was already loaded if exists("b:current_syntax") diff --git a/runtime/syntax/cabal.vim b/runtime/syntax/cabal.vim index 92e6b8331e..74cda51266 100644 --- a/runtime/syntax/cabal.vim +++ b/runtime/syntax/cabal.vim @@ -4,7 +4,9 @@ " Maintainer: Marcin Szamotulski <profunctor@pm.me> " Previous Maintainer: Vincent Berthoux <twinside@gmail.com> " File Types: .cabal -" Last Change: 21 Nov 2020 +" Last Change: 22 Oct 2022 +" v1.6: Added support for foreign-libraries +" Added highlighting for various fields " v1.5: Incorporated changes from " https://github.com/sdiehl/haskell-vim-proto/blob/master/vim/syntax/cabal.vim " Use `syn keyword` instead of `syn match`. @@ -61,13 +63,14 @@ syn keyword cabalCategory contained \ test-suite \ source-repository \ flag + \ foreign-library \ custom-setup \ common syn match cabalCategoryTitle contained /[^{]*\ze{\?/ syn match cabalCategoryRegion \ contains=cabalCategory,cabalCategoryTitle \ nextgroup=cabalCategory skipwhite - \ /^\c\s*\(contained\|executable\|library\|benchmark\|test-suite\|source-repository\|flag\|custom-setup\|common\)\+\s*\%(.*$\|$\)/ + \ /^\c\s*\(contained\|executable\|library\|benchmark\|test-suite\|source-repository\|flag\|foreign-library\|custom-setup\|common\)\+\s*\%(.*$\|$\)/ syn keyword cabalTruth true false " cabalStatementRegion which limits the scope of cabalStatement keywords, this @@ -77,6 +80,7 @@ syn keyword cabalStatement contained containedin=cabalStatementRegion \ default-language \ default-extensions \ author + \ autogen-includes \ autogen-modules \ asm-sources \ asm-options @@ -84,7 +88,7 @@ syn keyword cabalStatement contained containedin=cabalStatementRegion \ bug-reports \ build-depends \ build-tools - \ build-tools-depends + \ build-tool-depends \ build-type \ buildable \ c-sources @@ -95,6 +99,7 @@ syn keyword cabalStatement contained containedin=cabalStatementRegion \ cmm-sources \ cmm-options \ cpp-options + \ cxx-options \ cxx-sources \ data-dir \ data-files @@ -111,7 +116,9 @@ syn keyword cabalStatement contained containedin=cabalStatementRegion \ extra-framework-dirs \ extra-ghci-libraries \ extra-lib-dirs + \ extra-lib-dirs-static \ extra-libraries + \ extra-libraries-static \ extra-library-flavours \ extra-source-files \ extra-tmp-files @@ -133,6 +140,8 @@ syn keyword cabalStatement contained containedin=cabalStatementRegion \ install-includes \ js-sources \ ld-options + \ lib-version-info + \ lib-version-linux \ license \ license-file \ location @@ -141,20 +150,26 @@ syn keyword cabalStatement contained containedin=cabalStatementRegion \ manual \ mixins \ module + \ mod-def-file \ name \ nhc98-options + \ options \ other-extensions \ other-language \ other-languages \ other-modules \ package-url \ pkgconfig-depends + \ scope \ setup-depends + \ signatures \ stability \ subdir \ synopsis + \ reexported-modules \ tag \ tested-with + \ test-module \ type \ version \ virtual-modules 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/checkhealth.vim b/runtime/syntax/checkhealth.vim index 37f1822740..4b0ce75a54 100644 --- a/runtime/syntax/checkhealth.vim +++ b/runtime/syntax/checkhealth.vim @@ -1,26 +1,21 @@ " Vim syntax file -" Language: Neovim checkhealth buffer -" Last Change: 2021 Dec 15 +" Language: Nvim :checkhealth buffer +" Last Change: 2022 Nov 10 if exists("b:current_syntax") finish endif -runtime! syntax/markdown.vim +runtime! syntax/help.vim unlet! b:current_syntax syn case match -" We do not care about markdown syntax errors -if hlexists('markdownError') - syn clear markdownError -endif - -syn keyword healthError ERROR[:] containedin=markdownCodeBlock,mkdListItemLine -syn keyword healthWarning WARNING[:] containedin=markdownCodeBlock,mkdListItemLine -syn keyword healthSuccess OK[:] containedin=markdownCodeBlock,mkdListItemLine -syn match healthHelp "|.\{-}|" containedin=markdownCodeBlock,mkdListItemLine contains=healthBar -syn match healthBar "|" contained conceal +syn keyword healthError ERROR[:] +syn keyword healthWarning WARNING[:] +syn keyword healthSuccess OK[:] +syn match helpSectionDelim "^======*\n.*$" +syn match healthHeadingChar "=" conceal cchar=─ contained containedin=helpSectionDelim hi def link healthError Error hi def link healthWarning WarningMsg diff --git a/runtime/syntax/cs.vim b/runtime/syntax/cs.vim index 722ddbedf6..104470ac4b 100644 --- a/runtime/syntax/cs.vim +++ b/runtime/syntax/cs.vim @@ -3,7 +3,7 @@ " Maintainer: Nick Jensen <nickspoon@gmail.com> " Former Maintainers: Anduin Withers <awithers@anduin.com> " Johannes Zellner <johannes@zellner.org> -" Last Change: 2022-03-01 +" Last Change: 2022-11-16 " Filenames: *.cs " License: Vim (see :h license) " Repository: https://github.com/nickspoons/vim-cs @@ -25,6 +25,9 @@ syn keyword csType bool byte char decimal double float int long object sbyte sho syn keyword csType nint nuint " contextual syn keyword csStorage enum interface namespace struct +syn match csStorage "\<record\ze\_s\+@\=\h\w*\_s*[<(:{;]" +syn match csStorage "\%(\<\%(partial\|new\|public\|protected\|internal\|private\|abstract\|sealed\|static\|unsafe\|readonly\)\)\@9<=\_s\+record\>" +syn match csStorage "\<record\ze\_s\+\%(class\|struct\)" syn match csStorage "\<delegate\>" syn keyword csRepeat break continue do for foreach goto return while syn keyword csConditional else if switch @@ -44,6 +47,9 @@ syn keyword csManagedModifier managed unmanaged contained " Modifiers syn match csUsingModifier "\<global\ze\_s\+using\>" syn keyword csAccessModifier internal private protected public +syn keyword csModifier operator nextgroup=csCheckedModifier skipwhite skipempty +syn keyword csCheckedModifier checked contained + " TODO: in new out syn keyword csModifier abstract const event override readonly sealed static virtual volatile syn match csModifier "\<\%(extern\|fixed\|unsafe\)\>" @@ -76,7 +82,7 @@ syn match csAccess "\<this\>" " Extension method parameter modifier syn match csModifier "\<this\ze\_s\+@\=\h" -syn keyword csUnspecifiedStatement as in is nameof operator out params ref sizeof stackalloc using +syn keyword csUnspecifiedStatement as in is nameof out params ref sizeof stackalloc using syn keyword csUnsupportedStatement value syn keyword csUnspecifiedKeyword explicit implicit @@ -183,7 +189,7 @@ syn match csUnicodeNumber +\\u\x\{4}+ contained contains=csUnicodeSpecifier disp syn match csUnicodeNumber +\\U00\x\{6}+ contained contains=csUnicodeSpecifier display syn match csUnicodeSpecifier +\\[uUx]+ contained display -syn region csString matchgroup=csQuote start=+"+ end=+"+ end=+$+ extend contains=csSpecialChar,csSpecialError,csUnicodeNumber,@Spell +syn region csString matchgroup=csQuote start=+"+ end=+"\%(u8\)\=+ end=+$+ extend contains=csSpecialChar,csSpecialError,csUnicodeNumber,@Spell syn match csCharacter "'[^']*'" contains=csSpecialChar,csSpecialCharError,csUnicodeNumber display syn match csCharacter "'\\''" contains=csSpecialChar display syn match csCharacter "'[^\\]'" display @@ -200,7 +206,7 @@ syn match csReal "\<\d\+\%(_\+\d\+\)*[fdm]\>" display syn case match syn cluster csNumber contains=csInteger,csReal -syn region csInterpolatedString matchgroup=csQuote start=+\$"+ end=+"+ extend contains=csInterpolation,csEscapedInterpolation,csSpecialChar,csSpecialError,csUnicodeNumber,@Spell +syn region csInterpolatedString matchgroup=csQuote start=+\$"+ end=+"\%(u8\)\=+ extend contains=csInterpolation,csEscapedInterpolation,csSpecialChar,csSpecialError,csUnicodeNumber,@Spell syn region csInterpolation matchgroup=csInterpolationDelimiter start=+{+ end=+}+ keepend contained contains=@csAll,csBraced,csBracketed,csInterpolationAlign,csInterpolationFormat syn match csEscapedInterpolation "{{" transparent contains=NONE display @@ -210,10 +216,10 @@ syn match csInterpolationFormat +:[^}]\+}+ contained contains=csInterpolationFor syn match csInterpolationAlignDel +,+ contained display syn match csInterpolationFormatDel +:+ contained display -syn region csVerbatimString matchgroup=csQuote start=+@"+ end=+"+ skip=+""+ extend contains=csVerbatimQuote,@Spell +syn region csVerbatimString matchgroup=csQuote start=+@"+ end=+"\%(u8\)\=+ skip=+""+ extend contains=csVerbatimQuote,@Spell syn match csVerbatimQuote +""+ contained -syn region csInterVerbString matchgroup=csQuote start=+$@"+ start=+@$"+ end=+"+ skip=+""+ extend contains=csInterpolation,csEscapedInterpolation,csSpecialChar,csSpecialError,csUnicodeNumber,csVerbatimQuote,@Spell +syn region csInterVerbString matchgroup=csQuote start=+$@"+ start=+@$"+ end=+"\%(u8\)\=+ skip=+""+ extend contains=csInterpolation,csEscapedInterpolation,csSpecialChar,csSpecialError,csUnicodeNumber,csVerbatimQuote,@Spell syn cluster csString contains=csString,csInterpolatedString,csVerbatimString,csInterVerbString @@ -256,6 +262,7 @@ hi def link csException Exception hi def link csModifier StorageClass hi def link csAccessModifier csModifier hi def link csAsyncModifier csModifier +hi def link csCheckedModifier csModifier hi def link csManagedModifier csModifier hi def link csUsingModifier csModifier diff --git a/runtime/syntax/debchangelog.vim b/runtime/syntax/debchangelog.vim index 9bd836801e..691c3778c1 100644 --- a/runtime/syntax/debchangelog.vim +++ b/runtime/syntax/debchangelog.vim @@ -3,7 +3,7 @@ " Maintainer: Debian Vim Maintainers " Former Maintainers: Gerfried Fuchs <alfie@ist.org> " Wichert Akkerman <wakkerma@debian.org> -" Last Change: 2022 Jul 25 +" Last Change: 2022 Oct 29 " URL: https://salsa.debian.org/vim-team/vim-debian/blob/master/syntax/debchangelog.vim " Standard syntax initialization @@ -21,9 +21,9 @@ let s:cpo = &cpo set cpo-=C let s:supported = [ \ 'oldstable', 'stable', 'testing', 'unstable', 'experimental', 'sid', 'rc-buggy', - \ 'buster', 'bullseye', 'bookworm', 'trixie', + \ 'buster', 'bullseye', 'bookworm', 'trixie', 'forky', \ - \ 'trusty', 'xenial', 'bionic', 'focal', 'jammy', 'kinetic', + \ 'trusty', 'xenial', 'bionic', 'focal', 'jammy', 'kinetic', 'lunar', \ 'devel' \ ] let s:unsupported = [ diff --git a/runtime/syntax/debsources.vim b/runtime/syntax/debsources.vim index ea9e59ea8e..9b75797b54 100644 --- a/runtime/syntax/debsources.vim +++ b/runtime/syntax/debsources.vim @@ -2,7 +2,7 @@ " Language: Debian sources.list " Maintainer: Debian Vim Maintainers " Former Maintainer: Matthijs Mohlmann <matthijs@cacholong.nl> -" Last Change: 2022 Jul 25 +" Last Change: 2022 Oct 29 " URL: https://salsa.debian.org/vim-team/vim-debian/blob/master/syntax/debsources.vim " Standard syntax initialization @@ -23,9 +23,9 @@ let s:cpo = &cpo set cpo-=C let s:supported = [ \ 'oldstable', 'stable', 'testing', 'unstable', 'experimental', 'sid', 'rc-buggy', - \ 'buster', 'bullseye', 'bookworm', 'trixie', + \ 'buster', 'bullseye', 'bookworm', 'trixie', 'forky', \ - \ 'trusty', 'xenial', 'bionic', 'focal', 'jammy', 'kinetic', + \ 'trusty', 'xenial', 'bionic', 'focal', 'jammy', 'kinetic', 'lunar', \ 'devel' \ ] let s:unsupported = [ 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/editorconfig.vim b/runtime/syntax/editorconfig.vim new file mode 100644 index 0000000000..4392d2b2d5 --- /dev/null +++ b/runtime/syntax/editorconfig.vim @@ -0,0 +1,17 @@ +runtime! syntax/dosini.vim +unlet! b:current_syntax + +syntax match editorconfigUnknownProperty "^\s*\zs\w\+\ze\s*=" +syntax keyword editorconfigProperty root + +lua<< +local props = {} +for k in pairs(require('editorconfig').properties) do + props[#props + 1] = k +end +vim.cmd(string.format('syntax keyword editorconfigProperty %s', table.concat(props, ' '))) +. + +hi def link editorconfigProperty dosiniLabel + +let b:current_syntax = 'editorconfig' 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/fstab.vim b/runtime/syntax/fstab.vim index 318488713b..7e18c267f7 100644 --- a/runtime/syntax/fstab.vim +++ b/runtime/syntax/fstab.vim @@ -2,8 +2,8 @@ " Language: fstab file " Maintainer: Radu Dineiu <radu.dineiu@gmail.com> " URL: https://raw.github.com/rid9/vim-fstab/master/syntax/fstab.vim -" Last Change: 2020 Dec 30 -" Version: 1.4 +" Last Change: 2022 Dec 11 +" Version: 1.6.2 " " Credits: " David Necas (Yeti) <yeti@physics.muni.cz> @@ -56,71 +56,124 @@ syn keyword fsMountPointKeyword contained none swap " Type syn cluster fsTypeCluster contains=fsTypeKeyword,fsTypeUnknown syn match fsTypeUnknown /\s\+\zs\w\+/ contained -syn keyword fsTypeKeyword contained adfs ados affs anon_inodefs atfs audiofs auto autofs bdev befs bfs btrfs binfmt_misc cd9660 cfs cgroup cifs coda configfs cpuset cramfs devfs devpts devtmpfs e2compr efs ext2 ext2fs ext3 ext4 fdesc ffs filecore fuse fuseblk fusectl hfs hpfs hugetlbfs iso9660 jffs jffs2 jfs kernfs lfs linprocfs mfs minix mqueue msdos ncpfs nfs nfsd nilfs2 none ntfs null nwfs overlay ovlfs pipefs portal proc procfs pstore ptyfs qnx4 reiserfs ramfs romfs securityfs shm smbfs squashfs sockfs sshfs std subfs swap sysfs sysv tcfs tmpfs udf ufs umap umsdos union usbfs userfs vfat vs3fs vxfs wrapfs wvfs xenfs xfs zisofs +syn keyword fsTypeKeyword contained adfs ados affs anon_inodefs atfs audiofs auto autofs bdev befs bfs btrfs binfmt_misc cd9660 ceph cfs cgroup cifs coda coherent configfs cpuset cramfs debugfs devfs devpts devtmpfs dlmfs e2compr ecryptfs efivarfs efs erofs exfat ext2 ext2fs ext3 ext4 f2fs fdesc ffs filecore fuse fuseblk fusectl gfs2 hfs hfsplus hpfs hugetlbfs iso9660 jffs jffs2 jfs kernfs lfs linprocfs mfs minix mqueue msdos ncpfs nfs nfs4 nfsd nilfs2 none ntfs ntfs3 null nwfs ocfs2 omfs overlay ovlfs pipefs portal proc procfs pstore ptyfs pvfs2 qnx4 qnx6 reiserfs ramfs romfs rpc_pipefs securityfs shm smbfs spufs squashfs sockfs sshfs std subfs swap sysfs sysv tcfs tmpfs ubifs udf ufs umap umsdos union usbfs userfs v9fs vfat virtiofs vs3fs vxfs wrapfs wvfs xenfs xenix xfs zisofs zonefs " Options " ------- " Options: General syn cluster fsOptionsCluster contains=fsOperator,fsOptionsGeneral,fsOptionsKeywords,fsTypeUnknown syn match fsOptionsNumber /\d\+/ +syn match fsOptionsNumberSigned /[-+]\?\d\+/ syn match fsOptionsNumberOctal /[0-8]\+/ syn match fsOptionsString /[a-zA-Z0-9_-]\+/ +syn keyword fsOptionsTrueFalse true false syn keyword fsOptionsYesNo yes no +syn keyword fsOptionsYN y n +syn keyword fsOptions01 0 1 syn cluster fsOptionsCheckCluster contains=fsOptionsExt2Check,fsOptionsFatCheck syn keyword fsOptionsSize 512 1024 2048 -syn keyword fsOptionsGeneral async atime auto bind current defaults dev devgid devmode devmtime devuid dirsync exec force fstab kudzu loop mand move noatime noauto noclusterr noclusterw nodev nodevmtime nodiratime noexec nomand norelatime nosuid nosymfollow nouser owner rbind rdonly relatime remount ro rq rw suid suiddir supermount sw sync union update user users wxallowed xx nofail failok +syn keyword fsOptionsGeneral async atime auto bind current defaults dev devgid devmode devmtime devuid dirsync exec force fstab kudzu loop managed mand move noatime noauto noclusterr noclusterw nodev nodevmtime nodiratime noexec nomand norelatime nosuid nosymfollow nouser owner pamconsole rbind rdonly relatime remount ro rq rw suid suiddir supermount sw sync union update user users wxallowed xx nofail failok lazytime syn match fsOptionsGeneral /_netdev/ +syn match fsOptionsKeywords contained /\<x-systemd\.\%(requires\|before\|after\|wanted-by\|required-by\|requires-mounts-for\|idle-timeout\|device-timeout\|mount-timeout\)=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<x-systemd\.\%(device-bound\|automount\|makefs\|growfs\|rw-only\)/ +syn match fsOptionsKeywords contained /\<x-initrd\.mount/ + +syn match fsOptionsKeywords contained /\<cache=/ nextgroup=fsOptionsCache +syn keyword fsOptionsCache yes no none strict loose fscache mmap + +syn match fsOptionsKeywords contained /\<dax=/ nextgroup=fsOptionsDax +syn keyword fsOptionsDax inode never always + +syn match fsOptionsKeywords contained /\<errors=/ nextgroup=fsOptionsErrors +syn keyword fsOptionsErrors contained continue panic withdraw remount-ro recover zone-ro zone-offline repair + +syn match fsOptionsKeywords contained /\<\%(sec\)=/ nextgroup=fsOptionsSecurityMode +syn keyword fsOptionsSecurityMode contained none krb5 krb5i ntlm ntlmi ntlmv2 ntlmv2i ntlmssp ntlmsspi sys lkey lkeyi lkeyp spkm spkmi spkmp + " Options: adfs syn match fsOptionsKeywords contained /\<\%([ug]id\|o\%(wn\|th\)mask\)=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<ftsuffix=/ nextgroup=fsOptions01 " Options: affs -syn match fsOptionsKeywords contained /\<\%(set[ug]id\|mode\|reserved\)=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<mode=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<\%(set[ug]id\|reserved\)=/ nextgroup=fsOptionsNumber syn match fsOptionsKeywords contained /\<\%(prefix\|volume\|root\)=/ nextgroup=fsOptionsString syn match fsOptionsKeywords contained /\<bs=/ nextgroup=fsOptionsSize -syn keyword fsOptionsKeywords contained protect usemp verbose +syn keyword fsOptionsKeywords contained protect usemp verbose nofilenametruncate mufs " Options: btrfs -syn match fsOptionsKeywords contained /\<\%(subvol\|subvolid\|subvolrootid\|device\|compress\|compress-force\|fatal_errors\)=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<\%(subvol\|subvolid\|subvolrootid\|device\|compress\|compress-force\|check_int_print_mask\|space_cache\)=/ nextgroup=fsOptionsString syn match fsOptionsKeywords contained /\<\%(max_inline\|alloc_start\|thread_pool\|metadata_ratio\|check_int_print_mask\)=/ nextgroup=fsOptionsNumber -syn keyword fsOptionsKeywords contained degraded nodatasum nodatacow nobarrier ssd ssd_spread noacl notreelog flushoncommit space_cache nospace_cache clear_cache user_subvol_rm_allowed autodefrag inode_cache enospc_debug recovery check_int check_int_data skip_balance discard +syn match fsOptionsKeywords contained /\<discard=/ nextgroup=fsOptionsBtrfsDiscard +syn keyword fsOptionsBtrfsDiscard sync async +syn match fsOptionsKeywords contained /\<fatal_errors=/ nextgroup=fsOptionsBtrfsFatalErrors +syn keyword fsOptionsBtrfsFatalErrors bug panic +syn match fsOptionsKeywords contained /\<fragment=/ nextgroup=fsOptionsBtrfsFragment +syn keyword fsOptionsBtrfsFragment data metadata all +syn keyword fsOptionsKeywords contained degraded datasum nodatasum datacow nodatacow barrier nobarrier ssd ssd_spread nossd nossd_spread noacl treelog notreelog flushoncommit noflushoncommit space_cache nospace_cache clear_cache user_subvol_rm_allowed autodefrag noautodefrag inode_cache noinode_cache enospc_debug noenospc_debug recovery check_int check_int_data skip_balance discard nodiscard compress compress-force nologreplay rescan_uuid_tree rescue usebackuproot " Options: cd9660 syn keyword fsOptionsKeywords contained extatt gens norrip nostrictjoilet +" Options: ceph +syn match fsOptionsKeywords contained /\<\%(mon_addr\|fsid\|rasize\|mount_timeout\|caps_max\)=/ nextgroup=fsOptionsString +syn keyword fsOptionsKeywords contained rbytes norbytes nocrc dcache nodcache noasyncreaddir noquotadf nocopyfrom +syn match fsOptionsKeywords contained /\<recover_session=/ nextgroup=fsOptionsCephRecoverSession +syn keyword fsOptionsCephRecoverSession contained no clean + +" Options: cifs +syn match fsOptionsKeywords contained /\<\%(user\|password\|credentials\|servernetbiosname\|servern\|netbiosname\|file_mode\|dir_mode\|ip\|domain\|prefixpath\)=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<\%(cruid\|backupuid\|backupgid\)=/ nextgroup=fsOptionsNumber +syn keyword fsOptionsKeywords contained forceuid forcegid guest setuids nosetuids perm noperm dynperm strictcache rwpidforward mapchars nomapchars cifsacl nocase ignorecase nobrl sfu serverino noserverino nounix fsc multiuser posixpaths noposixpaths + " Options: devpts " -- everything already defined +" Options: ecryptfs +syn match fsOptionsKeywords contained /\<\%(ecryptfs_\%(sig\|fnek_sig\|cipher\|key_bytes\)\|key\)=/ nextgroup=fsOptionsString +syn keyword fsOptionsKeywords contained ecryptfs_passthrough no_sig_cache ecryptfs_encrypted_view ecryptfs_xattr +syn match fsOptionsKeywords contained /\<ecryptfs_enable_filename_crypto=/ nextgroup=fsOptionsYN +syn match fsOptionsKeywords contained /\<verbosity=/ nextgroup=fsOptions01 + +" Options: erofs +syn match fsOptionsKeywords contained /\<cache_strategy=/ nextgroup=fsOptionsEroCacheStrategy +syn keyword fsOptionsEroCacheStrategy contained disabled readahead readaround + " Options: ext2 syn match fsOptionsKeywords contained /\<check=*/ nextgroup=@fsOptionsCheckCluster -syn match fsOptionsKeywords contained /\<errors=/ nextgroup=fsOptionsExt2Errors syn match fsOptionsKeywords contained /\<\%(res[gu]id\|sb\)=/ nextgroup=fsOptionsNumber syn keyword fsOptionsExt2Check contained none normal strict -syn keyword fsOptionsExt2Errors contained continue panic -syn match fsOptionsExt2Errors contained /\<remount-ro\>/ +syn match fsOptionsErrors contained /\<remount-ro\>/ syn keyword fsOptionsKeywords contained acl bsddf minixdf debug grpid bsdgroups minixdf nocheck nogrpid oldalloc orlov sysvgroups nouid32 nobh user_xattr nouser_xattr " Options: ext3 syn match fsOptionsKeywords contained /\<journal=/ nextgroup=fsOptionsExt3Journal syn match fsOptionsKeywords contained /\<data=/ nextgroup=fsOptionsExt3Data +syn match fsOptionsKeywords contained /\<data_err=/ nextgroup=fsOptionsExt3DataErr syn match fsOptionsKeywords contained /\<commit=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<jqfmt=/ nextgroup=fsOptionsExt3Jqfmt +syn match fsOptionsKeywords contained /\<\%(usrjquota\|grpjquota\)=/ nextgroup=fsOptionsString syn keyword fsOptionsExt3Journal contained update inum syn keyword fsOptionsExt3Data contained journal ordered writeback +syn keyword fsOptionsExt3DataErr contained ignore abort +syn keyword fsOptionsExt3Jqfmt contained vfsold vfsv0 vfsv1 syn keyword fsOptionsKeywords contained noload user_xattr nouser_xattr acl " Options: ext4 syn match fsOptionsKeywords contained /\<journal=/ nextgroup=fsOptionsExt4Journal syn match fsOptionsKeywords contained /\<data=/ nextgroup=fsOptionsExt4Data -syn match fsOptionsKeywords contained /\<barrier=/ nextgroup=fsOptionsExt4Barrier +syn match fsOptionsKeywords contained /\<barrier=/ nextgroup=fsOptions01 syn match fsOptionsKeywords contained /\<journal_dev=/ nextgroup=fsOptionsNumber syn match fsOptionsKeywords contained /\<resuid=/ nextgroup=fsOptionsNumber syn match fsOptionsKeywords contained /\<resgid=/ nextgroup=fsOptionsNumber syn match fsOptionsKeywords contained /\<sb=/ nextgroup=fsOptionsNumber -syn match fsOptionsKeywords contained /\<commit=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<\%(commit\|inode_readahead_blks\|stripe\|max_batch_time\|min_batch_time\|init_itable\|max_dir_size_kb\)=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<journal_ioprio=/ nextgroup=fsOptionsExt4JournalIoprio syn keyword fsOptionsExt4Journal contained update inum syn keyword fsOptionsExt4Data contained journal ordered writeback -syn match fsOptionsExt4Barrier /[0-1]/ -syn keyword fsOptionsKeywords contained noload extents orlov oldalloc user_xattr nouser_xattr acl noacl reservation noreservation bsddf minixdf check=none nocheck debug grpid nogroupid sysvgroups bsdgroups quota noquota grpquota usrquota bh nobh +syn keyword fsOptionsExt4JournalIoprio contained 0 1 2 3 4 5 6 7 +syn keyword fsOptionsKeywords contained noload extents orlov oldalloc user_xattr nouser_xattr acl noacl reservation noreservation bsddf minixdf check=none nocheck debug grpid nogroupid sysvgroups bsdgroups quota noquota grpquota usrquota bh nobh journal_checksum nojournal_checksum journal_async_commit delalloc nodelalloc auto_da_alloc noauto_da_alloc noinit_itable block_validity noblock_validity dioread_lock dioread_nolock i_version nombcache prjquota " Options: fat syn match fsOptionsKeywords contained /\<blocksize=/ nextgroup=fsOptionsSize @@ -135,39 +188,124 @@ syn keyword fsOptionsConv contained b t a binary text auto syn keyword fsOptionsFatType contained 12 16 32 syn keyword fsOptionsKeywords contained quiet sys_immutable showexec dots nodots +" Options: fuse +syn match fsOptionsKeywords contained /\<\%(fd\|user_id\|group_id\|blksize\)=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<\%(rootmode\)=/ nextgroup=fsOptionsString + " Options: hfs -syn match fsOptionsKeywords contained /\<\%(creator|type\)=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<\%(creator\|type\)=/ nextgroup=fsOptionsString syn match fsOptionsKeywords contained /\<\%(dir\|file\|\)_umask=/ nextgroup=fsOptionsNumberOctal syn match fsOptionsKeywords contained /\<\%(session\|part\)=/ nextgroup=fsOptionsNumber +" Options: hfsplus +syn match fsOptionsKeywords contained /\<nls=/ nextgroup=fsOptionsString +syn keyword fsOptionsKeywords contained decompose nodecompose + +" Options: f2fs +syn match fsOptionsKeywords contained /\<background_gc=/ nextgroup=fsOptionsF2fsBackgroundGc +syn keyword fsOptionsF2fsBackgroundGc contained on off sync +syn match fsOptionsKeywords contained /\<active_logs=/ nextgroup=fsOptionsF2fsActiveLogs +syn keyword fsOptionsF2fsActiveLogs contained 2 4 6 +syn match fsOptionsKeywords contained /\<alloc_mode=/ nextgroup=fsOptionsF2fsAllocMode +syn keyword fsOptionsF2fsAllocMode contained reuse default +syn match fsOptionsKeywords contained /\<fsync_mode=/ nextgroup=fsOptionsF2fsFsyncMode +syn keyword fsOptionsF2fsFsyncMode contained posix strict nobarrier +syn match fsOptionsKeywords contained /\<compress_mode=/ nextgroup=fsOptionsF2fsCompressMode +syn keyword fsOptionsF2fsCompressMode contained fs user +syn match fsOptionsKeywords contained /\<discard_unit=/ nextgroup=fsOptionsF2fsDiscardUnit +syn keyword fsOptionsF2fsDiscardUnit contained block segment section +syn match fsOptionsKeywords contained /\<memory=/ nextgroup=fsOptionsF2fsMemory +syn keyword fsOptionsF2fsMemory contained normal low +syn match fsOptionsKeywords contained /\<\%(inline_xattr_size\|reserve_root\|fault_injection\|fault_type\|io_bits\|compress_log_size\)=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<\%(prjjquota\|test_dummy_encryption\|checkpoint\|compress_algorithm\|compress_extension\|nocompress_extension\)=/ nextgroup=fsOptionsString +syn keyword fsOptionsKeyWords contained gc_merge nogc_merge disable_roll_forward no_heap disable_ext_identify inline_xattr noinline_xattr inline_data noinline_data inline_dentry noinline_dentry flush_merge fastboot extent_cache noextent_cache data_flush offusrjquota offgrpjquota offprjjquota test_dummy_encryption checkpoint_merge nocheckpoint_merge compress_chksum compress_cache inlinecrypt atgc + " Options: ffs syn keyword fsOptionsKeyWords contained noperm softdep +" Options: gfs2 +syn match fsOptionsKeywords contained /\<\%(lockproto\|locktable\)=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<\%(quota_quantum\|statfs_quantum\|statfs_percent\)=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<quota=/ nextgroup=fsOptionsGfs2Quota +syn keyword fsOptionsGfs2Quota contained off account on +syn keyword fsOptionsKeywords contained localcaching localflocks ignore_local_fs upgrade spectator meta + " Options: hpfs syn match fsOptionsKeywords contained /\<case=/ nextgroup=fsOptionsHpfsCase syn keyword fsOptionsHpfsCase contained lower asis +syn match fsOptionsKeywords contained /\<chkdsk=/ nextgroup=fsOptionsHpfsChkdsk +syn keyword fsOptionsHpfsChkdsk contained no errors always +syn match fsOptionsKeywords contained /\<eas=/ nextgroup=fsOptionsHpfsEas +syn keyword fsOptionsHpfsEas contained no ro rw +syn match fsOptionsKeywords contained /\<timeshift=/ nextgroup=fsOptionsNumberSigned " Options: iso9660 syn match fsOptionsKeywords contained /\<map=/ nextgroup=fsOptionsIsoMap syn match fsOptionsKeywords contained /\<block=/ nextgroup=fsOptionsSize -syn match fsOptionsKeywords contained /\<\%(session\|sbsector\)=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<\%(session\|sbsector\|dmode\)=/ nextgroup=fsOptionsNumber syn keyword fsOptionsIsoMap contained n o a normal off acorn -syn keyword fsOptionsKeywords contained norock nojoilet unhide cruft +syn keyword fsOptionsKeywords contained norock nojoliet hide unhide cruft overriderockperm showassoc syn keyword fsOptionsConv contained m mtext " Options: jfs syn keyword fsOptionsKeywords nointegrity integrity " Options: nfs -syn match fsOptionsKeywords contained /\<\%(rsize\|wsize\|timeo\|retrans\|acregmin\|acregmax\|acdirmin\|acdirmax\|actimeo\|retry\|port\|mountport\|mounthost\|mountprog\|mountvers\|nfsprog\|nfsvers\|namelen\)=/ nextgroup=fsOptionsString -syn keyword fsOptionsKeywords contained bg fg soft hard intr cto ac tcp udp lock nobg nofg nosoft nohard nointr noposix nocto noac notcp noudp nolock +syn match fsOptionsKeywords contained /\<lookupcache=/ nextgroup=fsOptionsNfsLookupCache +syn keyword fsOptionsNfsLookupCache contained all none pos positive +syn match fsOptionsKeywords contained /\<local_lock=/ nextgroup=fsOptionsNfsLocalLock +syn keyword fsOptionsNfsLocalLock contained all flock posix none +syn match fsOptionsKeywords contained /\<\%(mounthost\|mountprog\|nfsprog\|namelen\|proto\|mountproto\|clientaddr\)=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<\%(timeo\|retrans\|[rw]size\|acregmin\|acregmax\|acdirmin\|acdirmax\|actimeo\|retry\|port\|mountport\|mountvers\|namlen\|nfsvers\|vers\|minorversion\)=/ nextgroup=fsOptionsNumber +syn keyword fsOptionsKeywords contained bg fg soft hard intr cto ac tcp udp lock nobg nofg nosoft nohard nointr noposix nocto noac notcp noudp nolock sharecache nosharecache resvport noresvport rdirplus nordirplus + +" Options: nilfs2 +syn match fsOptionsKeywords contained /\<order=/ nextgroup=fsOptionsNilfs2Order +syn keyword fsOptionsNilfs2Order contained relaxed strict +syn match fsOptionsKeywords contained /\<\%([cp]p\)=/ nextgroup=fsOptionsNumber +syn keyword fsOptionsKeywords contained nogc " Options: ntfs +syn match fsOptionsKeywords contained /\<mft_zone_multiplier=/ nextgroup=fsOptionsNtfsMftZoneMultiplier +syn keyword fsOptionsNtfsMftZoneMultiplier contained 1 2 3 4 syn match fsOptionsKeywords contained /\<\%(posix=*\|uni_xlate=\)/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<\%(sloppy\|show_sys_files\|case_sensitive\|disable_sparse\)=/ nextgroup=fsOptionsTrueFalse syn keyword fsOptionsKeywords contained utf8 +" Options: ntfs3 +syn keyword fsOptionsKeywords contained noacsrules nohidden sparse showmeta prealloc + +" Options: ntfs-3g +syn match fsOptionsKeywords contained /\<\%(usermapping\|locale\|streams_interface\)=/ nextgroup=fsOptionsString +syn keyword fsOptionsKeywords contained permissions inherit recover norecover ignore_case remove_hiberfile hide_hid_files hide_dot_files windows_names silent no_def_opts efs_raw compression nocompression no_detach + +" Options: ocfs2 +syn match fsOptionsKeywords contained /\<\%(resv_level\|dir_resv_level\)=/ nextgroup=fsOptionsOcfs2ResvLevel +syn keyword fsOptionsOcfs2ResvLevel contained 0 1 2 3 4 5 6 7 8 +syn match fsOptionsKeywords contained /\<coherency=/ nextgroup=fsOptionsOcfs2Coherency +syn keyword fsOptionsOcfs2Coherency contained full buffered +syn match fsOptionsKeywords contained /\<\%(atime_quantum\|preferred_slot\|localalloc\)=/ nextgroup=fsOptionsNumber +syn keyword fsOptionsKeywords contained strictatime inode64 + +" Options: overlay +syn match fsOptionsKeywords contained /\<redirect_dir=/ nextgroup=fsOptionsOverlayRedirectDir +syn keyword fsOptionsOverlayRedirectDir contained on follow off nofollow + " Options: proc -" -- everything already defined +syn match fsOptionsKeywords contained /\<\%(hidepid\|subset\)=/ nextgroup=fsOptionsString + +" Options: qnx4 +syn match fsOptionsKeywords contained /\<bitmap=/ nextgroup=fsOptionsQnx4Bitmap +syn keyword fsOptionsQnx4Bitmap contained always lazy nonrmv +syn keyword fsOptionsKeywords contained grown noembed overalloc unbusy + +" Options: qnx6 +syn match fsOptionsKeywords contained /\<hold=/ nextgroup=fsOptionsQnx6Hold +syn keyword fsOptionsQnx6Hold contained allow root deny +syn match fsOptionsKeywords contained /\<sync=/ nextgroup=fsOptionsQnx6Sync +syn keyword fsOptionsQnx6Sync contained mandatory optional none +syn match fsOptionsKeywords contained /\<snapshot=/ nextgroup=fsOptionsNumber +syn keyword fsOptionsKeywords contained alignio " Options: reiserfs syn match fsOptionsKeywords contained /\<hash=/ nextgroup=fsOptionsReiserHash @@ -176,7 +314,7 @@ syn keyword fsOptionsReiserHash contained rupasov tea r5 detect syn keyword fsOptionsKeywords contained hashed_relocation noborder nolog notail no_unhashed_relocation replayonly " Options: sshfs -syn match fsOptionsKeywords contained /\<\%(BatchMode\|ChallengeResponseAuthentication\|CheckHostIP\|ClearAllForwardings\|Compression\|EnableSSHKeysign\|ForwardAgent\|ForwardX11\|ForwardX11Trusted\|GatewayPorts\|GSSAPIAuthentication\|GSSAPIDelegateCredentials\|HashKnownHosts\|HostbasedAuthentication\|IdentitiesOnly\|NoHostAuthenticationForLocalhost\|PasswordAuthentication\|PubkeyAuthentication\|RhostsRSAAuthentication\|RSAAuthentication\|TCPKeepAlive\|UsePrivilegedPort\|cache\)=/ nextgroup=fsOptionsYesNo +syn match fsOptionsKeywords contained /\<\%(BatchMode\|ChallengeResponseAuthentication\|CheckHostIP\|ClearAllForwardings\|Compression\|EnableSSHKeysign\|ForwardAgent\|ForwardX11\|ForwardX11Trusted\|GatewayPorts\|GSSAPIAuthentication\|GSSAPIDelegateCredentials\|HashKnownHosts\|HostbasedAuthentication\|IdentitiesOnly\|NoHostAuthenticationForLocalhost\|PasswordAuthentication\|PubkeyAuthentication\|RhostsRSAAuthentication\|RSAAuthentication\|TCPKeepAlive\|UsePrivilegedPort\)=/ nextgroup=fsOptionsYesNo syn match fsOptionsKeywords contained /\<\%(ControlMaster\|StrictHostKeyChecking\|VerifyHostKeyDNS\)=/ nextgroup=fsOptionsSshYesNoAsk syn match fsOptionsKeywords contained /\<\%(AddressFamily\|BindAddress\|Cipher\|Ciphers\|ControlPath\|DynamicForward\|EscapeChar\|GlobalKnownHostsFile\|HostKeyAlgorithms\|HostKeyAlias\|HostName\|IdentityFile\|KbdInteractiveDevices\|LocalForward\|LogLevel\|MACs\|PreferredAuthentications\|Protocol\|ProxyCommand\|RemoteForward\|RhostsAuthentication\|SendEnv\|SmartcardDevice\|User\|UserKnownHostsFile\|XAuthLocation\|comment\|workaround\|idmap\|ssh_command\|sftp_server\|fsname\)=/ nextgroup=fsOptionsString syn match fsOptionsKeywords contained /\<\%(CompressionLevel\|ConnectionAttempts\|ConnectTimeout\|NumberOfPasswordPrompts\|Port\|ServerAliveCountMax\|ServerAliveInterval\|cache_timeout\|cache_X_timeout\|ssh_protocol\|directport\|max_read\|umask\|uid\|gid\|entry_timeout\|negative_timeout\|attr_timeout\)=/ nextgroup=fsOptionsNumber @@ -190,12 +328,19 @@ syn keyword fsOptionsKeywords contained procuid " Options: swap syn match fsOptionsKeywords contained /\<pri=/ nextgroup=fsOptionsNumber +" Options: ubifs +syn match fsOptionsKeywords contained /\<\%(compr\|auth_key\|auth_hash_name\)=/ nextgroup=fsOptionsString +syn keyword fsOptionsKeywords contained bulk_read no_bulk_read chk_data_crc no_chk_data_crc + " Options: tmpfs +syn match fsOptionsKeywords contained /\<huge=/ nextgroup=fsOptionsTmpfsHuge +syn keyword fsOptionsTmpfsHuge contained never always within_size advise deny force +syn match fsOptionsKeywords contained /\<\%(size\|mpol\)=/ nextgroup=fsOptionsString syn match fsOptionsKeywords contained /\<nr_\%(blocks\|inodes\)=/ nextgroup=fsOptionsNumber " Options: udf syn match fsOptionsKeywords contained /\<\%(anchor\|partition\|lastblock\|fileset\|rootdir\)=/ nextgroup=fsOptionsString -syn keyword fsOptionsKeywords contained unhide undelete strict novrs +syn keyword fsOptionsKeywords contained unhide undelete strict nostrict novrs adinicb noadinicb shortad longad " Options: ufs syn match fsOptionsKeywords contained /\<ufstype=/ nextgroup=fsOptionsUfsType @@ -208,14 +353,32 @@ syn keyword fsOptionsUfsError contained panic lock umount repair syn match fsOptionsKeywords contained /\<\%(dev\|bus\|list\)\%(id\|gid\)=/ nextgroup=fsOptionsNumber syn match fsOptionsKeywords contained /\<\%(dev\|bus\|list\)mode=/ nextgroup=fsOptionsNumberOctal +" Options: v9fs +syn match fsOptionsKeywords contained /\<\%(trans\)=/ nextgroup=fsOptionsV9Trans +syn keyword fsOptionsV9Trans unix tcp fd virtio rdma +syn match fsOptionsKeywords contained /\<debug=/ nextgroup=fsOptionsV9Debug +syn keyword fsOptionsV9Debug 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80 0x100 0x200 0x400 0x800 +syn match fsOptionsKeywords contained /\<version=/ nextgroup=fsOptionsV9Version +syn keyword fsOptionsV9Version 9p2000 9p2000.u 9p2000.L +syn match fsOptionsKeywords contained /\<\%([ua]name\|[rw]fdno\|access\)=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<msize=/ nextgroup=fsOptionsNumber +syn keyword fsOptionsKeywords contained noextend dfltuid dfltgid afid nodevmap cachetag + " Options: vfat -syn keyword fsOptionsKeywords contained nonumtail posix utf8 -syn match fsOptionsKeywords contained /shortname=/ nextgroup=fsOptionsVfatShortname +syn match fsOptionsKeywords contained /\<shortname=/ nextgroup=fsOptionsVfatShortname syn keyword fsOptionsVfatShortname contained lower win95 winnt mixed +syn match fsOptionsKeywords contained /\<nfs=/ nextgroup=fsOptionsVfatNfs +syn keyword fsOptionsVfatNfs contained stale_rw nostale_ro +syn match fsOptionsKeywords contained /\<\%(tz\|dos1xfloppy\)=/ nextgroup=fsOptionsString +syn match fsOptionsKeywords contained /\<\%(allow_utime\|codepage\)=/ nextgroup=fsOptionsNumber +syn match fsOptionsKeywords contained /\<time_offset=/ nextgroup=fsOptionsNumberSigned +syn keyword fsOptionsKeywords contained nonumtail posix utf8 usefree flush rodir " Options: xfs -syn match fsOptionsKeywords contained /\%(biosize\|logbufs\|logbsize\|logdev\|rtdev\|sunit\|swidth\)=/ nextgroup=fsOptionsString -syn keyword fsOptionsKeywords contained dmapi xdsm noalign noatime noquota norecovery osyncisdsync quota usrquota uqnoenforce grpquota gqnoenforce +syn match fsOptionsKeywords contained /\<logbufs=/ nextgroup=fsOptionsXfsLogBufs +syn keyword fsOptionsXfsLogBufs contained 2 3 4 5 6 7 8 +syn match fsOptionsKeywords contained /\%(allocsize\|biosize\|logbsize\|logdev\|rtdev\|sunit\|swidth\)=/ nextgroup=fsOptionsString +syn keyword fsOptionsKeywords contained dmapi xdsm noalign noatime noquota norecovery osyncisdsync quota usrquota uqnoenforce grpquota gqnoenforce attr2 noattr2 filestreams ikeep noikeep inode32 inode64 largeio nolargeio nouuid uquota qnoenforce gquota pquota pqnoenforce swalloc wsync " Frequency / Pass No. syn cluster fsFreqPassCluster contains=fsFreqPassNumber,fsFreqPassError @@ -257,31 +420,71 @@ hi def link fsMountPointError Error hi def link fsMountPointKeyword Keyword hi def link fsFreqPassError Error -hi def link fsOptionsGeneral Type -hi def link fsOptionsKeywords Keyword -hi def link fsOptionsNumber Number -hi def link fsOptionsNumberOctal Number -hi def link fsOptionsString String -hi def link fsOptionsSize Number +hi def link fsOptionsBtrfsDiscard String +hi def link fsOptionsBtrfsFatalErrors String +hi def link fsOptionsBtrfsFragment String +hi def link fsOptionsCache String +hi def link fsOptionsCephRecoverSession String +hi def link fsOptionsConv String +hi def link fsOptionsDax String +hi def link fsOptionsEroCacheStrategy String +hi def link fsOptionsErrors String hi def link fsOptionsExt2Check String -hi def link fsOptionsExt2Errors String -hi def link fsOptionsExt3Journal String hi def link fsOptionsExt3Data String -hi def link fsOptionsExt4Journal String +hi def link fsOptionsExt3DataErr String +hi def link fsOptionsExt3Journal String +hi def link fsOptionsExt3Jqfmt String hi def link fsOptionsExt4Data String -hi def link fsOptionsExt4Barrier Number +hi def link fsOptionsExt4Journal String +hi def link fsOptionsExt4JournalIoprio Number +hi def link fsOptionsF2fsActiveLogs Number +hi def link fsOptionsF2fsAllocMode String +hi def link fsOptionsF2fsBackgroundGc String +hi def link fsOptionsF2fsCompressMode String +hi def link fsOptionsF2fsDiscardUnit String +hi def link fsOptionsF2fsFsyncMode String +hi def link fsOptionsF2fsMemory String hi def link fsOptionsFatCheck String -hi def link fsOptionsConv String hi def link fsOptionsFatType Number -hi def link fsOptionsYesNo String +hi def link fsOptionsGeneral Type +hi def link fsOptionsGfs2Quota String hi def link fsOptionsHpfsCase String +hi def link fsOptionsHpfsChkdsk String +hi def link fsOptionsHpfsEas String hi def link fsOptionsIsoMap String +hi def link fsOptionsKeywords Keyword +hi def link fsOptionsNfsLocalLock String +hi def link fsOptionsNfsLookupCache String +hi def link fsOptionsNilfs2Order String +hi def link fsOptionsNtfsMftZoneMultiplier Number +hi def link fsOptionsNumber Number +hi def link fsOptionsNumberOctal Number +hi def link fsOptionsNumberSigned Number +hi def link fsOptionsOcfs2Coherency String +hi def link fsOptionsOcfs2ResvLevel Number +hi def link fsOptionsOverlayRedirectDir String +hi def link fsOptionsQnx4Bitmap String +hi def link fsOptionsQnx6Hold String +hi def link fsOptionsQnx6Sync String hi def link fsOptionsReiserHash String +hi def link fsOptionsSecurityMode String +hi def link fsOptionsSize Number hi def link fsOptionsSshYesNoAsk String -hi def link fsOptionsUfsType String +hi def link fsOptionsString String +hi def link fsOptionsTmpfsHuge String hi def link fsOptionsUfsError String - +hi def link fsOptionsUfsType String +hi def link fsOptionsV9Debug String +hi def link fsOptionsV9Trans String +hi def link fsOptionsV9Version String +hi def link fsOptionsVfatNfs String hi def link fsOptionsVfatShortname String +hi def link fsOptionsXfsLogBufs Number + +hi def link fsOptionsTrueFalse Boolean +hi def link fsOptionsYesNo String +hi def link fsOptionsYN String +hi def link fsOptions01 Number let b:current_syntax = "fstab" 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/go.vim b/runtime/syntax/go.vim index 0c326254b8..904c8ad7f2 100644 --- a/runtime/syntax/go.vim +++ b/runtime/syntax/go.vim @@ -5,7 +5,7 @@ " go.vim: Vim syntax file for Go. " Language: Go " Maintainer: Billie Cleek <bhcleek@gmail.com> -" Latest Revision: 2021-09-18 +" Latest Revision: 2022-11-17 " License: BSD-style. See LICENSE file in source repository. " Repository: https://github.com/fatih/vim-go @@ -117,7 +117,7 @@ hi def link goLabel Label hi def link goRepeat Repeat " Predefined types -syn keyword goType chan map bool string error +syn keyword goType chan map bool string error any comparable syn keyword goSignedInts int int8 int16 int32 int64 rune syn keyword goUnsignedInts byte uint uint8 uint16 uint32 uint64 uintptr syn keyword goFloats float32 float64 @@ -187,6 +187,8 @@ else syn region goRawString start=+`+ end=+`+ endif +syn match goImportString /^\%(\s\+\|import \)\(\h\w* \)\?\zs"[^"]\+"$/ contained containedin=goImport + if s:HighlightFormatStrings() " [n] notation is valid for specifying explicit argument indexes " 1. Match a literal % not preceded by a %. @@ -204,6 +206,7 @@ if s:HighlightFormatStrings() hi def link goFormatSpecifier goSpecialString endif +hi def link goImportString String hi def link goString String hi def link goRawString String @@ -223,9 +226,9 @@ endif " import if s:FoldEnable('import') - syn region goImport start='import (' end=')' transparent fold contains=goImport,goString,goComment + syn region goImport start='import (' end=')' transparent fold contains=goImport,goImportString,goComment else - syn region goImport start='import (' end=')' transparent contains=goImport,goString,goComment + syn region goImport start='import (' end=')' transparent contains=goImport,goImportString,goComment endif " var, const @@ -245,14 +248,10 @@ endif syn match goSingleDecl /\%(import\|var\|const\) [^(]\@=/ contains=goImport,goVar,goConst " Integers -syn match goDecimalInt "\<-\=\(0\|[1-9]_\?\(\d\|\d\+_\?\d\+\)*\)\%([Ee][-+]\=\d\+\)\=\>" -syn match goDecimalError "\<-\=\(_\(\d\+_*\)\+\|\([1-9]\d*_*\)\+__\(\d\+_*\)\+\|\([1-9]\d*_*\)\+_\+\)\%([Ee][-+]\=\d\+\)\=\>" -syn match goHexadecimalInt "\<-\=0[xX]_\?\(\x\+_\?\)\+\>" -syn match goHexadecimalError "\<-\=0[xX]_\?\(\x\+_\?\)*\(\([^ \t0-9A-Fa-f_)]\|__\)\S*\|_\)\>" -syn match goOctalInt "\<-\=0[oO]\?_\?\(\o\+_\?\)\+\>" -syn match goOctalError "\<-\=0[0-7oO_]*\(\([^ \t0-7oOxX_/)\]\}\:;]\|[oO]\{2,\}\|__\)\S*\|_\|[oOxX]\)\>" -syn match goBinaryInt "\<-\=0[bB]_\?\([01]\+_\?\)\+\>" -syn match goBinaryError "\<-\=0[bB]_\?[01_]*\([^ \t01_)]\S*\|__\S*\|_\)\>" +syn match goDecimalInt "\<-\=\%(0\|\%(\d\|\d_\d\)\+\)\>" +syn match goHexadecimalInt "\<-\=0[xX]_\?\%(\x\|\x_\x\)\+\>" +syn match goOctalInt "\<-\=0[oO]\?_\?\%(\o\|\o_\o\)\+\>" +syn match goBinaryInt "\<-\=0[bB]_\?\%([01]\|[01]_[01]\)\+\>" hi def link goDecimalInt Integer hi def link goDecimalError Error @@ -265,19 +264,55 @@ hi def link goBinaryError Error hi def link Integer Number " Floating point -syn match goFloat "\<-\=\d\+\.\d*\%([Ee][-+]\=\d\+\)\=\>" -syn match goFloat "\<-\=\.\d\+\%([Ee][-+]\=\d\+\)\=\>" +"float_lit = decimal_float_lit | hex_float_lit . +" +"decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] | +" decimal_digits decimal_exponent | +" "." decimal_digits [ decimal_exponent ] . +"decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits . +" +"hex_float_lit = "0" ( "x" | "X" ) hex_mantissa hex_exponent . +"hex_mantissa = [ "_" ] hex_digits "." [ hex_digits ] | +" [ "_" ] hex_digits | +" "." hex_digits . +"hex_exponent = ( "p" | "P" ) [ "+" | "-" ] decimal_digits . +" decimal floats with a decimal point +syn match goFloat "\<-\=\%(0\|\%(\d\|\d_\d\)\+\)\.\%(\%(\%(\d\|\d_\d\)\+\)\=\%([Ee][-+]\=\%(\d\|\d_\d\)\+\)\=\>\)\=" +syn match goFloat "\s\zs-\=\.\%(\d\|\d_\d\)\+\%(\%([Ee][-+]\=\%(\d\|\d_\d\)\+\)\>\)\=" +" decimal floats without a decimal point +syn match goFloat "\<-\=\%(0\|\%(\d\|\d_\d\)\+\)[Ee][-+]\=\%(\d\|\d_\d\)\+\>" +" hexadecimal floats with a decimal point +syn match goHexadecimalFloat "\<-\=0[xX]\%(_\x\|\x\)\+\.\%(\%(\x\|\x_\x\)\+\)\=\%([Pp][-+]\=\%(\d\|\d_\d\)\+\)\=\>" +syn match goHexadecimalFloat "\<-\=0[xX]\.\%(\x\|\x_\x\)\+\%([Pp][-+]\=\%(\d\|\d_\d\)\+\)\=\>" +" hexadecimal floats without a decimal point +syn match goHexadecimalFloat "\<-\=0[xX]\%(_\x\|\x\)\+[Pp][-+]\=\%(\d\|\d_\d\)\+\>" hi def link goFloat Float +hi def link goHexadecimalFloat Float " Imaginary literals -syn match goImaginary "\<-\=\d\+i\>" -syn match goImaginary "\<-\=\d\+[Ee][-+]\=\d\+i\>" -syn match goImaginaryFloat "\<-\=\d\+\.\d*\%([Ee][-+]\=\d\+\)\=i\>" -syn match goImaginaryFloat "\<-\=\.\d\+\%([Ee][-+]\=\d\+\)\=i\>" - -hi def link goImaginary Number -hi def link goImaginaryFloat Float +syn match goImaginaryDecimal "\<-\=\%(0\|\%(\d\|\d_\d\)\+\)i\>" +syn match goImaginaryHexadecimal "\<-\=0[xX]_\?\%(\x\|\x_\x\)\+i\>" +syn match goImaginaryOctal "\<-\=0[oO]\?_\?\%(\o\|\o_\o\)\+i\>" +syn match goImaginaryBinary "\<-\=0[bB]_\?\%([01]\|[01]_[01]\)\+i\>" + +" imaginary decimal floats with a decimal point +syn match goImaginaryFloat "\<-\=\%(0\|\%(\d\|\d_\d\)\+\)\.\%(\%(\%(\d\|\d_\d\)\+\)\=\%([Ee][-+]\=\%(\d\|\d_\d\)\+\)\=\)\=i\>" +syn match goImaginaryFloat "\s\zs-\=\.\%(\d\|\d_\d\)\+\%([Ee][-+]\=\%(\d\|\d_\d\)\+\)\=i\>" +" imaginary decimal floats without a decimal point +syn match goImaginaryFloat "\<-\=\%(0\|\%(\d\|\d_\d\)\+\)[Ee][-+]\=\%(\d\|\d_\d\)\+i\>" +" imaginary hexadecimal floats with a decimal point +syn match goImaginaryHexadecimalFloat "\<-\=0[xX]\%(_\x\|\x\)\+\.\%(\%(\x\|\x_\x\)\+\)\=\%([Pp][-+]\=\%(\d\|\d_\d\)\+\)\=i\>" +syn match goImaginaryHexadecimalFloat "\<-\=0[xX]\.\%(\x\|\x_\x\)\+\%([Pp][-+]\=\%(\d\|\d_\d\)\+\)\=i\>" +" imaginary hexadecimal floats without a decimal point +syn match goImaginaryHexadecimalFloat "\<-\=0[xX]\%(_\x\|\x\)\+[Pp][-+]\=\%(\d\|\d_\d\)\+i\>" + +hi def link goImaginaryDecimal Number +hi def link goImaginaryHexadecimal Number +hi def link goImaginaryOctal Number +hi def link goImaginaryBinary Number +hi def link goImaginaryFloat Float +hi def link goImaginaryHexadecimalFloat Float " Spaces after "[]" if s:HighlightArrayWhitespaceError() @@ -346,6 +381,8 @@ if s:HighlightOperators() syn match goOperator /\%(<<\|>>\|&^\)=\?/ " match remaining two-char operators: := && || <- ++ -- syn match goOperator /:=\|||\|<-\|++\|--/ + " match ~ + syn match goOperator /\~/ " match ... hi def link goPointerOperator goOperator @@ -353,13 +390,37 @@ if s:HighlightOperators() endif hi def link goOperator Operator +" -> type constraint opening bracket +" |-> start non-counting group +" || -> any word character +" || | -> at least one, as many as possible +" || | | -> start non-counting group +" || | | | -> match ~ +" || | | | | -> at most once +" || | | | | | -> allow a slice type +" || | | | | | | -> any word character +" || | | | | | | | -> start a non-counting group +" || | | | | | | | | -> that matches word characters and | +" || | | | | | | | | | -> close the non-counting group +" || | | | | | | | | | | -> close the non-counting group +" || | | | | | | | | | | |-> any number of matches +" || | | | | | | | | | | || -> start a non-counting group +" || | | | | | | | | | | || | -> a comma and whitespace +" || | | | | | | | | | | || | | -> at most once +" || | | | | | | | | | | || | | | -> close the non-counting group +" || | | | | | | | | | | || | | | | -> at least one of those non-counting groups, as many as possible +" || | | | | | -------- | | | | || | | | | | -> type constraint closing bracket +" || | | | | || | | | | | || | | | | | | +syn match goTypeParams /\[\%(\w\+\s\+\%(\~\?\%(\[]\)\?\w\%(\w\||\)\)*\%(,\s*\)\?\)\+\]/ nextgroup=goSimpleParams,goDeclType contained + " Functions; if s:HighlightFunctions() || s:HighlightFunctionParameters() syn match goDeclaration /\<func\>/ nextgroup=goReceiver,goFunction,goSimpleParams skipwhite skipnl + syn match goReceiverDecl /(\s*\zs\%(\%(\w\+\s\+\)\?\*\?\w\+\%(\[\%(\%(\[\]\)\?\w\+\%(,\s*\)\?\)\+\]\)\?\)\ze\s*)/ contained contains=goReceiverVar,goReceiverType,goPointerOperator syn match goReceiverVar /\w\+\ze\s\+\%(\w\|\*\)/ nextgroup=goPointerOperator,goReceiverType skipwhite skipnl contained syn match goPointerOperator /\*/ nextgroup=goReceiverType contained skipwhite skipnl - syn match goFunction /\w\+/ nextgroup=goSimpleParams contained skipwhite skipnl - syn match goReceiverType /\w\+/ contained + syn match goFunction /\w\+/ nextgroup=goSimpleParams,goTypeParams contained skipwhite skipnl + syn match goReceiverType /\w\+\%(\[\%(\%(\[\]\)\?\w\+\%(,\s*\)\?\)\+\]\)\?\ze\s*)/ contained if s:HighlightFunctionParameters() syn match goSimpleParams /(\%(\w\|\_s\|[*\.\[\],\{\}<>-]\)*)/ contained contains=goParamName,goType nextgroup=goFunctionReturn skipwhite skipnl syn match goFunctionReturn /(\%(\w\|\_s\|[*\.\[\],\{\}<>-]\)*)/ contained contains=goParamName,goType skipwhite skipnl @@ -369,7 +430,7 @@ if s:HighlightFunctions() || s:HighlightFunctionParameters() hi def link goReceiverVar goParamName hi def link goParamName Identifier endif - syn match goReceiver /(\s*\w\+\%(\s\+\*\?\s*\w\+\)\?\s*)\ze\s*\w/ contained nextgroup=goFunction contains=goReceiverVar skipwhite skipnl + syn match goReceiver /(\s*\%(\w\+\s\+\)\?\*\?\s*\w\+\%(\[\%(\%(\[\]\)\?\w\+\%(,\s*\)\?\)\+\]\)\?\s*)\ze\s*\w/ contained nextgroup=goFunction contains=goReceiverDecl skipwhite skipnl else syn keyword goDeclaration func endif @@ -377,7 +438,7 @@ hi def link goFunction Function " Function calls; if s:HighlightFunctionCalls() - syn match goFunctionCall /\w\+\ze(/ contains=goBuiltins,goDeclaration + syn match goFunctionCall /\w\+\ze\%(\[\%(\%(\[]\)\?\w\+\(,\s*\)\?\)\+\]\)\?(/ contains=goBuiltins,goDeclaration endif hi def link goFunctionCall Type @@ -404,7 +465,7 @@ hi def link goField Identifier if s:HighlightTypes() syn match goTypeConstructor /\<\w\+{\@=/ syn match goTypeDecl /\<type\>/ nextgroup=goTypeName skipwhite skipnl - syn match goTypeName /\w\+/ contained nextgroup=goDeclType skipwhite skipnl + syn match goTypeName /\w\+/ contained nextgroup=goDeclType,goTypeParams skipwhite skipnl syn match goDeclType /\<\%(interface\|struct\)\>/ skipwhite skipnl hi def link goReceiverType Type else @@ -444,7 +505,7 @@ if s:HighlightBuildConstraints() " The rs=s+2 option lets the \s*+build portion be part of the inner region " instead of the matchgroup so it will be highlighted as a goBuildKeyword. syn region goBuildComment matchgroup=goBuildCommentStart - \ start="//\s*+build\s"rs=s+2 end="$" + \ start="//\(\s*+build\s\|go:build\)"rs=s+2 end="$" \ contains=goBuildKeyword,goBuildDirectives hi def link goBuildCommentStart Comment hi def link goBuildDirectives Type 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..8b469d7242 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 Nov 13 " Quit when a (custom) syntax file was already loaded if exists("b:current_syntax") @@ -11,13 +11,14 @@ endif let s:cpo_save = &cpo set cpo&vim -syn match helpHeadline "^[-A-Z .][-A-Z0-9 .()_]*\ze\(\s\+\*\|$\)" +syn match helpHeadline "^[A-Z.][-A-Z0-9 .,()_']*?\=\ze\(\s\+\*\|$\)" syn match helpSectionDelim "^===.*===$" syn match helpSectionDelim "^---.*--$" +" Neovim: support language annotation in codeblocks if has("conceal") - syn region helpExample matchgroup=helpIgnore start=" >$" start="^>$" end="^[^ \t]"me=e-1 end="^<" concealends + syn region helpExample matchgroup=helpIgnore start=" >[a-z0-9]*$" start="^>[a-z0-9]*$" end="^[^ \t]"me=e-1 end="^<" concealends else - syn region helpExample matchgroup=helpIgnore start=" >$" start="^>$" end="^[^ \t]"me=e-1 end="^<" + syn region helpExample matchgroup=helpIgnore start=" >[a-z0-9]*$" start="^>[a-z0-9]*$" end="^[^ \t]"me=e-1 end="^<" endif syn match helpHyperTextJump "\\\@<!|[#-)!+-~]\+|" contains=helpBar syn match helpHyperTextEntry "\*[#-)!+-~]\+\*\s"he=e-1 contains=helpStar @@ -39,6 +40,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/hgcommit.vim b/runtime/syntax/hgcommit.vim index 37fe9db8bf..e9f31bef61 100644 --- a/runtime/syntax/hgcommit.vim +++ b/runtime/syntax/hgcommit.vim @@ -1,8 +1,8 @@ " Vim syntax file -" Language: hg (Mercurial) commit file +" Language: hg/sl (Mercurial / Sapling) commit file " Maintainer: Ken Takata <kentkt at csc dot jp> -" Last Change: 2012 Aug 23 -" Filenames: hg-editor-*.txt +" Max Coplan <mchcopl@gmail.com> +" Last Change: 2022-12-08 " License: VIM License " URL: https://github.com/k-takata/hg-vim @@ -10,12 +10,15 @@ if exists("b:current_syntax") finish endif -syn match hgcommitComment "^HG:.*$" contains=@NoSpell -syn match hgcommitUser "^HG: user: \zs.*$" contains=@NoSpell contained containedin=hgcommitComment -syn match hgcommitBranch "^HG: branch \zs.*$" contains=@NoSpell contained containedin=hgcommitComment -syn match hgcommitAdded "^HG: \zsadded .*$" contains=@NoSpell contained containedin=hgcommitComment -syn match hgcommitChanged "^HG: \zschanged .*$" contains=@NoSpell contained containedin=hgcommitComment -syn match hgcommitRemoved "^HG: \zsremoved .*$" contains=@NoSpell contained containedin=hgcommitComment +syn match hgcommitComment "^\%(SL\|HG\): .*$" contains=@NoSpell +syn match hgcommitUser "^\%(SL\|HG\): user: \zs.*$" contains=@NoSpell contained containedin=hgcommitComment +syn match hgcommitBranch "^\%(SL\|HG\): branch \zs.*$" contains=@NoSpell contained containedin=hgcommitComment +syn match hgcommitAdded "^\%(SL\|HG\): \zsadded .*$" contains=@NoSpell contained containedin=hgcommitComment +syn match hgcommitChanged "^\%(SL\|HG\): \zschanged .*$" contains=@NoSpell contained containedin=hgcommitComment +syn match hgcommitRemoved "^\%(SL\|HG\): \zsremoved .*$" contains=@NoSpell contained containedin=hgcommitComment + +syn region hgcommitDiff start=/\%(^\(SL\|HG\): diff --\%(git\|cc\|combined\) \)\@=/ end=/^\%(diff --\|$\|@@\@!\|[^[:alnum:]\ +-]\S\@!\)\@=/ fold contains=@hgcommitDiff +syn include @hgcommitDiff syntax/shared/hgcommitDiff.vim hi def link hgcommitComment Comment hi def link hgcommitUser String 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/hollywood.vim b/runtime/syntax/hollywood.vim index ce5ba29553..fcd03a68f0 100644 --- a/runtime/syntax/hollywood.vim +++ b/runtime/syntax/hollywood.vim @@ -1,14 +1,14 @@ " Vim syntax file -" Language: Hollywood 9.0 -" Maintainer: Tom Crecelius <holly@net-eclipse.net> -" First Author: Tom Crecelius <holly@net-eclipse.net> -" Last Change: 2021 April 13 -" Highlighting Issues: +" Language: Hollywood 9.1 +" Maintainer: Ola Söder <rolfkopman@gmail.com> +" First Author: Tom Crecelius <holly@net-eclipse.net> +" Last Change: 2022 Nov 09 +" Highlighting Issues: " Depending on your colour schema, Strings or Comments might be highlighted in " a way, you don't like. If so, try one of the following settings after " opening a hollywood script: " -" :hi link hwString MoreMsg +" :hi link hwString MoreMsg " :hi link hwString NonText " :hi link hwString String " @@ -60,10 +60,10 @@ syn region hwThenElse transparent matchgroup=hwCond start="\<Then\>" end="$" end " If .. EndIf syn region hwIfEndIf transparent matchgroup=hwCond start="\<If\>\(\(.\{-}Then.\{-}\)\@!\)" end="\<EndIf\>" contains=ALLBUT,hwTodo,hwSpecial,hwIn,hwStep,hwLineStatement skipwhite skipempty -" Else ... EndIf +" Else ... EndIf syn region hwElseEndIf contained transparent matchgroup=hwCond start="\<Else\>" end="\<EndIf\>"me=e-5 contains=ALLBUT,hwTodo,hwSpecial,hwElseIf,hwElseEndIf,hwIn,hwStep,hwFallThrough,hwLineStatement -" Then +" Then "syn keyword hwLineStatement Then contained " Forever syn keyword hwLineStatement Forever contained @@ -92,7 +92,7 @@ syn region hwLoopBlock transparent matchgroup=hwRepeat start="\<Repeat\>" end="\ " While ... Wend/Do syn region hwLoopBlock transparent matchgroup=hwRepeat start="\<While\>" end="\<Do\>" end="\<Wend\>" contains=ALLBUT,hwTodo,hwSpecial,hwElseIf,hwElse,hwIn,hwStep,hwLineStatement skipwhite skipempty -" For .. To +" For .. To syn region hwForTo transparent matchgroup=hwRepeat start="\<For\>" end="\<To\>"me=e-2 skipwhite skipempty nextgroup=hwToNext " To .. Next @@ -113,7 +113,7 @@ syn match hwPreProcessor "@\<\%(ANIM\|APPAUTHOR\|APPCOPYRIGHT\|APPDESCRIPTION\|A " predefined constants syn match hwConstant "#\<\%(ACTIVEWINDOW\|ADF_ANIM\|ADF_FX\|ADF_MOVEOBJECT\|ALL\|ALPHABETICAL\|ALPHACHANNEL\|ALPHANUMERICAL\|AMIGAICON_DEVICE\|AMIGAICON_DISK\|AMIGAICON_DRAWER\|AMIGAICON_GARBAGE\|AMIGAICON_HIDE\|AMIGAICON_KICKSTART\|AMIGAICON_NONE\|AMIGAICON_PROJECT\|AMIGAICON_SETPOSITION\|AMIGAICON_SETTITLE\|AMIGAICON_SHOW\|AMIGAICON_TOOL\|ANIM\|ANIMSTREAM\|ANIMTYPE_RASTER\|ANIMTYPE_VECTOR\|ANMFMT_GIF\|ANMFMT_IFF\|ANMFMT_MJPEG\|ANTIALIAS\|AQUA\|ARC\|ASYNCDRAW\|ASYNCOBJ\|ATTRACTIVE\|ATTRADAPTER\|ATTRALPHAINTENSITY\|ATTRBGPIC\|ATTRBITRATE\|ATTRBORDERBOTTOM\|ATTRBORDERLEFT\|ATTRBORDERLESS\|ATTRBORDERPEN\|ATTRBORDERRIGHT\|ATTRBORDERTOP\|ATTRBULLETPEN\|ATTRCANSEEK\|ATTRCLIPREGION\|ATTRCOUNT\|ATTRCURFRAME\|ATTRCURSORX\|ATTRCURSORY\|ATTRCURSUBSONG\|ATTRCYCLE\|ATTRDENSITY\|ATTRDEPTH\|ATTRDISPLAY\|ATTRDITHERMODE\|ATTRDOUBLEBUFFER\|ATTRDRIVER\|ATTRDURATION\|ATTRELAPSE\|ATTRENCODING\|ATTRFIXED\|ATTRFONTAA\|ATTRFONTASCENDER\|ATTRFONTCHARMAP\|ATTRFONTDEPTH\|ATTRFONTDESCENDER\|ATTRFONTENGINE\|ATTRFONTNAME\|ATTRFONTPALETTE\|ATTRFONTSCALABLE\|ATTRFONTSIZE\|ATTRFONTTRANSPARENTPEN\|ATTRFONTTYPE\|ATTRFORMAT\|ATTRFRAMEDELAY\|ATTRFUNCTION\|ATTRGROUP\|ATTRHARDWARE\|ATTRHASALPHA\|ATTRHASMASK\|ATTRHEIGHT\|ATTRHOSTDEPTH\|ATTRHOSTHEIGHT\|ATTRHOSTMONITORS\|ATTRHOSTSCALE\|ATTRHOSTSCALEX\|ATTRHOSTSCALEY\|ATTRHOSTTASKBAR\|ATTRHOSTTITLEBARHEIGHT\|ATTRHOSTWIDTH\|ATTRID\|ATTRIMMERSIVEMODE\|ATTRINTERPOLATE\|ATTRKEYBOARD\|ATTRLAYERID\|ATTRLAYERS\|ATTRLAYERSON\|ATTRLOADER\|ATTRMARGINLEFT\|ATTRMARGINRIGHT\|ATTRMASKMODE\|ATTRMAXHEIGHT\|ATTRMAXIMIZED\|ATTRMAXWIDTH\|ATTRMENU\|ATTRMODE\|ATTRMONITOR\|ATTRNOCLOSE\|ATTRNOHIDE\|ATTRNOMODESWITCH\|ATTRNUMENTRIES\|ATTRNUMFRAMES\|ATTRNUMSUBSONGS\|ATTRONSCREEN\|ATTRORIENTATION\|ATTROUTPUTDEVICE\|ATTRPALETTE\|ATTRPALETTEMODE\|ATTRPAUSED\|ATTRPEN\|ATTRPITCH\|ATTRPLAYING\|ATTRPOINTER\|ATTRPOSITION\|ATTRPUBSCREEN\|ATTRRAWHEIGHT\|ATTRRAWWIDTH\|ATTRRAWXPOS\|ATTRRAWYPOS\|ATTRSCALEHEIGHT\|ATTRSCALEMODE\|ATTRSCALESWITCH\|ATTRSCALEWIDTH\|ATTRSHADOWPEN\|ATTRSIZE\|ATTRSIZEABLE\|ATTRSPRITES\|ATTRSTANDARD\|ATTRSTATE\|ATTRSYSTEMBARS\|ATTRTEXT\|ATTRTITLE\|ATTRTRANSPARENTCOLOR\|ATTRTRANSPARENTPEN\|ATTRTYPE\|ATTRUSERDATA\|ATTRVISIBLE\|ATTRWIDTH\|ATTRXDPI\|ATTRXPOS\|ATTRXSERVER\|ATTRYDPI\|ATTRYPOS\|ATTRZPOS\|BARS\|BAUD_115200\|BAUD_1200\|BAUD_19200\|BAUD_2400\|BAUD_300\|BAUD_38400\|BAUD_460800\|BAUD_4800\|BAUD_57600\|BAUD_600\|BAUD_9600\|BEEPERROR\|BEEPINFORMATION\|BEEPQUESTION\|BEEPSYSTEM\|BEEPWARNING\|BGPIC\|BGPICPART\|BIGENDIAN\|BIGSINE\|BITMAP_DEFAULT\|BLACK\|BLEND\|BLUE\|BOLD\|BOOLEAN\|BORDER\|BOTTOM\|BOTTOMOUT\|BOUNCE\|BOX\|BRUSH\|BRUSH_VS_BOX\|BRUSHPART\|BULLET_ARROW\|BULLET_BOX\|BULLET_CHECKMARK\|BULLET_CIRCLE\|BULLET_CROSS\|BULLET_DASH\|BULLET_DIAMOND\|BULLET_LALPHA\|BULLET_LALPHADOUBLE\|BULLET_LALPHASINGLE\|BULLET_LROMAN\|BULLET_LROMANDOUBLE\|BULLET_LROMANSINGLE\|BULLET_NONE\|BULLET_NUMERIC\|BULLET_NUMERICDOUBLE\|BULLET_NUMERICSINGLE\|BULLET_UALPHA\|BULLET_UALPHADOUBLE\|BULLET_UALPHASINGLE\|BULLET_UROMAN\|BULLET_UROMANDOUBLE\|BULLET_UROMANSINGLE\|BYTE\|CAPBUTT\|CAPROUND\|CAPSQUARE\|CARDBOTTOM\|CARDTOP\|CENTER\|CHARMAP_ADOBECUSTOM\|CHARMAP_ADOBEEXPERT\|CHARMAP_ADOBELATIN1\|CHARMAP_ADOBESTANDARD\|CHARMAP_APPLEROMAN\|CHARMAP_BIG5\|CHARMAP_DEFAULT\|CHARMAP_JOHAB\|CHARMAP_MSSYMBOL\|CHARMAP_OLDLATIN2\|CHARMAP_SJIS\|CHARMAP_UNICODE\|CHARMAP_WANSUNG\|CHIPMEMORY\|CIRCLE\|CLIENT\|CLIPBOARD_EMPTY\|CLIPBOARD_IMAGE\|CLIPBOARD_SOUND\|CLIPBOARD_TEXT\|CLIPBOARD_UNKNOWN\|CLIPREGION\|CLOCKWIPE\|CLOSEWINDOW\|CONICAL\|COPYFILE_FAILED\|COPYFILE_OVERWRITE\|COPYFILE_STATUS\|COPYFILE_UNPROTECT\|COUNTBOTH\|COUNTDIRECTORIES\|COUNTFILES\|COUNTRY_AFGHANISTAN\|COUNTRY_ALANDISLANDS\|COUNTRY_ALBANIA\|COUNTRY_ALGERIA\|COUNTRY_AMERICANSAMOA\|COUNTRY_ANDORRA\|COUNTRY_ANGOLA\|COUNTRY_ANGUILLA\|COUNTRY_ANTARCTICA\|COUNTRY_ANTIGUAANDBARBUDA\|COUNTRY_ARGENTINA\|COUNTRY_ARMENIA\|COUNTRY_ARUBA\|COUNTRY_AUSTRALIA\|COUNTRY_AUSTRIA\|COUNTRY_AZERBAIJAN\|COUNTRY_BAHAMAS\|COUNTRY_BAHRAIN\|COUNTRY_BANGLADESH\|COUNTRY_BARBADOS\|COUNTRY_BELARUS\|COUNTRY_BELGIUM\|COUNTRY_BELIZE\|COUNTRY_BENIN\|COUNTRY_BERMUDA\|COUNTRY_BESISLANDS\|COUNTRY_BHUTAN\|COUNTRY_BOLIVIA\|COUNTRY_BOSNIAANDHERZEGOVINA\|COUNTRY_BOTSWANA\|COUNTRY_BOUVETISLAND\|COUNTRY_BRAZIL\|COUNTRY_BRUNEI\|COUNTRY_BULGARIA\|COUNTRY_BURKINAFASO\|COUNTRY_BURUNDI\|COUNTRY_CAMBODIA\|COUNTRY_CAMEROON\|COUNTRY_CANADA\|COUNTRY_CAPEVERDE\|COUNTRY_CAYMANISLANDS\|COUNTRY_CENTRALAFRICANREPUBLIC\|COUNTRY_CHAD\|COUNTRY_CHILE\|COUNTRY_CHINA\|COUNTRY_CHRISTMASISLAND\|COUNTRY_COCOSISLANDS\|COUNTRY_COLOMBIA\|COUNTRY_COMOROS\|COUNTRY_CONGO\|COUNTRY_COOKISLANDS\|COUNTRY_COSTARICA\|COUNTRY_CROATIA\|COUNTRY_CUBA\|COUNTRY_CURACAO\|COUNTRY_CYPRUS\|COUNTRY_CZECHREPUBLIC\|COUNTRY_DENMARK\|COUNTRY_DJIBOUTI\|COUNTRY_DOMINICA\|COUNTRY_DOMINICANREPUBLIC\|COUNTRY_DRCONGO\|COUNTRY_ECUADOR\|COUNTRY_EGYPT\|COUNTRY_ELSALVADOR\|COUNTRY_EQUATORIALGUINEA\|COUNTRY_ERITREA\|COUNTRY_ESTONIA\|COUNTRY_ETHIOPIA\|COUNTRY_FALKLANDISLANDS\|COUNTRY_FAROEISLANDS\|COUNTRY_FIJI\|COUNTRY_FINLAND\|COUNTRY_FRANCE\|COUNTRY_FRENCHGUIANA\|COUNTRY_FRENCHPOLYNESIA\|COUNTRY_GABON\|COUNTRY_GAMBIA\|COUNTRY_GEORGIA\|COUNTRY_GERMANY\|COUNTRY_GHANA\|COUNTRY_GIBRALTAR\|COUNTRY_GREECE\|COUNTRY_GREENLAND\|COUNTRY_GRENADA\|COUNTRY_GUADELOUPE\|COUNTRY_GUAM\|COUNTRY_GUATEMALA\|COUNTRY_GUERNSEY\|COUNTRY_GUINEA\|COUNTRY_GUINEABISSAU\|COUNTRY_GUYANA\|COUNTRY_HAITI\|COUNTRY_HOLYSEE\|COUNTRY_HONDURAS\|COUNTRY_HONGKONG\|COUNTRY_HUNGARY\|COUNTRY_ICELAND\|COUNTRY_INDIA\|COUNTRY_INDONESIA\|COUNTRY_IRAN\|COUNTRY_IRAQ\|COUNTRY_IRELAND\|COUNTRY_ISLEOFMAN\|COUNTRY_ISRAEL\|COUNTRY_ITALY\|COUNTRY_IVORYCOAST\|COUNTRY_JAMAICA\|COUNTRY_JAPAN\|COUNTRY_JERSEY\|COUNTRY_JORDAN\|COUNTRY_KAZAKHSTAN\|COUNTRY_KENYA\|COUNTRY_KIRIBATI\|COUNTRY_KUWAIT\|COUNTRY_KYRGYZSTAN\|COUNTRY_LAOS\|COUNTRY_LATVIA\|COUNTRY_LEBANON\|COUNTRY_LESOTHO\|COUNTRY_LIBERIA\|COUNTRY_LIBYA\|COUNTRY_LIECHTENSTEIN\|COUNTRY_LITHUANIA\|COUNTRY_LUXEMBOURG\|COUNTRY_MACAO\|COUNTRY_MACEDONIA\|COUNTRY_MADAGASCAR\|COUNTRY_MALAWI\|COUNTRY_MALAYSIA\|COUNTRY_MALDIVES\|COUNTRY_MALI\|COUNTRY_MALTA\|COUNTRY_MARSHALLISLANDS\|COUNTRY_MARTINIQUE\|COUNTRY_MAURITANIA\|COUNTRY_MAURITIUS\|COUNTRY_MAYOTTE\|COUNTRY_MEXICO\|COUNTRY_MICRONESIA\|COUNTRY_MOLDOVA\|COUNTRY_MONACO\|COUNTRY_MONGOLIA\|COUNTRY_MONTENEGRO\|COUNTRY_MONTSERRAT\|COUNTRY_MOROCCO\|COUNTRY_MOZAMBIQUE\|COUNTRY_MYANMAR\|COUNTRY_NAMIBIA\|COUNTRY_NAURU\|COUNTRY_NEPAL\|COUNTRY_NETHERLANDS\|COUNTRY_NEWCALEDONIA\|COUNTRY_NEWZEALAND\|COUNTRY_NICARAGUA\|COUNTRY_NIGER\|COUNTRY_NIGERIA\|COUNTRY_NIUE\|COUNTRY_NORFOLKISLAND\|COUNTRY_NORTHKOREA\|COUNTRY_NORWAY\|COUNTRY_OMAN\|COUNTRY_PAKISTAN\|COUNTRY_PALAU\|COUNTRY_PALESTINE\|COUNTRY_PANAMA\|COUNTRY_PAPUANEWGUINEA\|COUNTRY_PARAGUAY\|COUNTRY_PERU\|COUNTRY_PHILIPPINES\|COUNTRY_PITCAIRN\|COUNTRY_POLAND\|COUNTRY_PORTUGAL\|COUNTRY_PUERTORICO\|COUNTRY_QATAR\|COUNTRY_REUNION\|COUNTRY_ROMANIA\|COUNTRY_RUSSIA\|COUNTRY_RWANDA\|COUNTRY_SAINTBARTHELEMY\|COUNTRY_SAINTHELENA\|COUNTRY_SAINTKITTSANDNEVIS\|COUNTRY_SAINTLUCIA\|COUNTRY_SAINTVINCENT\|COUNTRY_SAMOA\|COUNTRY_SANMARINO\|COUNTRY_SAOTOMEANDPRINCIPE\|COUNTRY_SAUDIARABIA\|COUNTRY_SENEGAL\|COUNTRY_SERBIA\|COUNTRY_SEYCHELLES\|COUNTRY_SIERRALEONE\|COUNTRY_SINGAPORE\|COUNTRY_SLOVAKIA\|COUNTRY_SLOVENIA\|COUNTRY_SOLOMONISLANDS\|COUNTRY_SOMALIA\|COUNTRY_SOUTHAFRICA\|COUNTRY_SOUTHKOREA\|COUNTRY_SOUTHSUDAN\|COUNTRY_SPAIN\|COUNTRY_SRILANKA\|COUNTRY_SUDAN\|COUNTRY_SURINAME\|COUNTRY_SWAZILAND\|COUNTRY_SWEDEN\|COUNTRY_SWITZERLAND\|COUNTRY_SYRIA\|COUNTRY_TAIWAN\|COUNTRY_TAJIKISTAN\|COUNTRY_TANZANIA\|COUNTRY_THAILAND\|COUNTRY_TIMOR\|COUNTRY_TOGO\|COUNTRY_TONGA\|COUNTRY_TRINIDADANDTOBAGO\|COUNTRY_TUNISIA\|COUNTRY_TURKEY\|COUNTRY_TURKMENISTAN\|COUNTRY_TUVALU\|COUNTRY_UAE\|COUNTRY_UGANDA\|COUNTRY_UK\|COUNTRY_UKRAINE\|COUNTRY_UNKNOWN\|COUNTRY_URUGUAY\|COUNTRY_USA\|COUNTRY_UZBEKISTAN\|COUNTRY_VANUATU\|COUNTRY_VENEZUELA\|COUNTRY_VIETNAM\|COUNTRY_YEMEN\|COUNTRY_ZAMBIA\|COUNTSEPARATE\|CR_DEAD\|CR_RUNNING\|CR_SUSPENDED\|CROSSFADE\|CRUSHBOTTOM\|CRUSHLEFT\|CRUSHRIGHT\|CRUSHTOP\|DAMPED\|DATA_5\|DATA_6\|DATA_7\|DATA_8\|DATEDAY\|DATELOCAL\|DATELOCALNATIVE\|DATEMONTH\|DATETIME\|DATEUTC\|DATEYEAR\|DEFAULTICON\|DEFAULTSPEED\|DEINTERLACE_DEFAULT\|DEINTERLACE_DOUBLE\|DELETEFILE_FAILED\|DELETEFILE_STATUS\|DELETEFILE_UNPROTECT\|DENSITY_HIGH\|DENSITY_LOW\|DENSITY_MEDIUM\|DENSITY_NONE\|DIAGONAL\|DIRECTORY\|DIRMONITOR_ADD\|DIRMONITOR_CHANGE\|DIRMONITOR_REMOVE\|DISPLAY\|DISPMODE_ASK\|DISPMODE_FAKEFULLSCREEN\|DISPMODE_FULLSCREEN\|DISPMODE_FULLSCREENSCALE\|DISPMODE_MODEREQUESTER\|DISPMODE_MODESWITCH\|DISPMODE_SYSTEMSCALE\|DISPMODE_WINDOWED\|DISPSTATE_CLOSED\|DISPSTATE_MINIMIZED\|DISPSTATE_OPEN\|DISSOLVE\|DITHERMODE_FLOYDSTEINBERG\|DITHERMODE_NONE\|DOSTYPE_DIRECTORY\|DOSTYPE_FILE\|DOUBLE\|DOUBLEBUFFER\|DOWNLOADFILE_STATUS\|DTR_OFF\|DTR_ON\|DURATION_LONG\|DURATION_SHORT\|EDGE\|ELLIPSE\|ENCODING_AMIGA\|ENCODING_ISO8859_1\|ENCODING_RAW\|ENCODING_UTF8\|EOF\|ERR_8OR16BITONLY\|ERR_ACCELERATOR\|ERR_ADDAPPICON\|ERR_ADDAPPWIN\|ERR_ADDSYSEVENT\|ERR_ADDTASK\|ERR_ADFFREEDISP\|ERR_ADFWRONGDISP\|ERR_AFILEPROP\|ERR_AHI\|ERR_ALLOCALPHA\|ERR_ALLOCCHANNEL\|ERR_ALLOCCHUNKY\|ERR_ALLOCMASK\|ERR_ALRDYDECLRD\|ERR_ALREADYASYNC\|ERR_ALSAPCM\|ERR_AMIGAGUIDE\|ERR_ANIMDISK\|ERR_ANIMFRAME\|ERR_ANTIALIAS\|ERR_APPLET\|ERR_APPLETVERSION\|ERR_APPLICATION\|ERR_ARGS\|ERR_ARRAYDECLA\|ERR_ASSERTFAILED\|ERR_ATSUI\|ERR_AUDIOCONVERTER\|ERR_BACKFILL\|ERR_BAD8SVX\|ERR_BADBASE64\|ERR_BADBYTECODE\|ERR_BADCALLBACKRET\|ERR_BADCONSTANT\|ERR_BADDIMENSIONS\|ERR_BADENCODING\|ERR_BADINTEGER\|ERR_BADIP\|ERR_BADLAYERTYPE\|ERR_BADPLATFORM\|ERR_BADSIGNATURE\|ERR_BADUPVALUES\|ERR_BADURL\|ERR_BADWAVE\|ERR_BADYIELD\|ERR_BEGINREFRESH\|ERR_BGPICBUTTON\|ERR_BGPICPALETTE\|ERR_BGPICTYPE\|ERR_BITMAP\|ERR_BLKWOENDBLK\|ERR_BRACECLOSE\|ERR_BRACEOPEN\|ERR_BRACKETCLOSE\|ERR_BRACKETOPEN\|ERR_BRUSHLINK\|ERR_BRUSHSIZE\|ERR_BRUSHTYPE\|ERR_CACHEERROR\|ERR_CASECST\|ERR_CHANGEDIR\|ERR_CHANNELRANGE\|ERR_CHRCSTEMPTY\|ERR_CHRCSTLEN\|ERR_CLIPFORMAT\|ERR_CLIPOPEN\|ERR_CLIPREAD\|ERR_CLIPWRITE\|ERR_CLOSEDDISPLAY\|ERR_CLOSEFILE\|ERR_CMDASVAR\|ERR_CMPUNSUPPORTED\|ERR_COLORSPACE\|ERR_COMMENTSTRUCT\|ERR_COMMODITY\|ERR_COMPLEXEXPR\|ERR_COMPLEXPATTERN\|ERR_COMPLEXWHILE\|ERR_CONCAT\|ERR_CONFIG\|ERR_CONFIG2\|ERR_CONITEMS\|ERR_CONSOLEARG\|ERR_CONTEXTMENU\|ERR_COORDSRANGE\|ERR_COREFOUNDATION\|ERR_CORETEXT\|ERR_CREATEDIR\|ERR_CREATEDOCKY\|ERR_CREATEEVENT\|ERR_CREATEGC\|ERR_CREATEICON\|ERR_CREATEMENU\|ERR_CREATEPORT\|ERR_CREATESHORTCUT\|ERR_CSTDOUBLEDEF\|ERR_CTRLSTRUCT\|ERR_CYIELD\|ERR_DATATYPEALPHA\|ERR_DATATYPESAVE\|ERR_DATATYPESAVE2\|ERR_DBLENCODING\|ERR_DBPALETTE\|ERR_DBTRANSWIN\|ERR_DBVIDEOLAYER\|ERR_DDAUTOSCALE\|ERR_DDMOBILE\|ERR_DDRECVIDEO\|ERR_DEADRESUME\|ERR_DEFFONT\|ERR_DELETEFILE\|ERR_DEMO\|ERR_DEMO2\|ERR_DEMO3\|ERR_DEPTHMISMATCH\|ERR_DEPTHRANGE\|ERR_DESERIALIZE\|ERR_DIFFDEPTH\|ERR_DIFFENCODING\|ERR_DINPUT\|ERR_DIRECTSHOW\|ERR_DIRLOCK\|ERR_DISPLAYADAPTERSUPPORT\|ERR_DISPLAYDESKTOP\|ERR_DISPLAYDESKTOPPAL\|ERR_DISPLAYSIZE\|ERR_DISPMINIMIZED\|ERR_DLOPEN\|ERR_DOUBLEDECLA\|ERR_DOUBLEMENU\|ERR_DRAWPATH\|ERR_DSOUNDNOTIFY\|ERR_DSOUNDNOTIPOS\|ERR_DSOUNDPLAY\|ERR_ELSEIFAFTERELSE\|ERR_ELSETWICE\|ERR_ELSEWOIF\|ERR_EMPTYMENUTREE\|ERR_EMPTYOBJ\|ERR_EMPTYPATH\|ERR_EMPTYSCRIPT\|ERR_EMPTYTABLE\|ERR_ENDBLKWOBLK\|ERR_ENDDOUBLEBUFFER\|ERR_ENDFUNCWOFUNC\|ERR_ENDIFWOIF\|ERR_ENDSWCHWOSWCH\|ERR_ENDWITHWOWITH\|ERR_EQUALEXPECTED\|ERR_ERRORCALLED\|ERR_ESCREPLACE\|ERR_EVNTEXPCTED\|ERR_EXAMINE\|ERR_EXECUTE\|ERR_EXETYPE\|ERR_FGRABVIDSTATE\|ERR_FIELDINIT\|ERR_FILEEXIST\|ERR_FILEFORMAT\|ERR_FILENOTFOUND\|ERR_FILESIZE\|ERR_FINDACTIVITY\|ERR_FINDANIM\|ERR_FINDANIMSTREAM\|ERR_FINDAPPLICATION\|ERR_FINDARRAY\|ERR_FINDASYNCDRAW\|ERR_FINDASYNCOBJ\|ERR_FINDBGPIC\|ERR_FINDBRUSH\|ERR_FINDBUTTON\|ERR_FINDCLIENT\|ERR_FINDCLIPREGION\|ERR_FINDCST\|ERR_FINDDIR\|ERR_FINDDISPLAY\|ERR_FINDFILE\|ERR_FINDFONT\|ERR_FINDFONT2\|ERR_FINDICON\|ERR_FINDINTERVAL\|ERR_FINDLAYER\|ERR_FINDLAYERDATA\|ERR_FINDMEMBLK\|ERR_FINDMENU\|ERR_FINDMENUITEM\|ERR_FINDMONITOR\|ERR_FINDMOVE\|ERR_FINDMUSIC\|ERR_FINDOBJECTDATA\|ERR_FINDPALETTE\|ERR_FINDPATH\|ERR_FINDPLUGIN\|ERR_FINDPOINTER\|ERR_FINDPORT\|ERR_FINDSAMPLE\|ERR_FINDSELECTOR\|ERR_FINDSERIAL\|ERR_FINDSERVER\|ERR_FINDSPRITE\|ERR_FINDTEXTOBJECT\|ERR_FINDTIMEOUT\|ERR_FINDTIMER\|ERR_FINDUDPOBJECT\|ERR_FINDVIDEO\|ERR_FIRSTPREPROC\|ERR_FONTFORMAT\|ERR_FONTPATH\|ERR_FONTPATH2\|ERR_FORBIDMODAL\|ERR_FOREVERWOREPEAT\|ERR_FORWONEXT\|ERR_FRAMEGRABBER\|ERR_FREEABGPIC\|ERR_FREEADISPLAY\|ERR_FREECURPOINTER\|ERR_FT2\|ERR_FTPAUTH\|ERR_FTPERROR\|ERR_FULLSCREEN\|ERR_FUNCARGS\|ERR_FUNCDECLA\|ERR_FUNCEXPECTED\|ERR_FUNCJMP\|ERR_FUNCREMOVED\|ERR_FUNCTABLEARG\|ERR_FUNCWOENDFUNC\|ERR_GETDISKOBJ\|ERR_GETIFADDRS\|ERR_GETMONITORINFO\|ERR_GETSHORTCUT\|ERR_GRABSCREEN\|ERR_GROUPNAMEUSED\|ERR_GTK\|ERR_GUIGFX\|ERR_HEXPOINT\|ERR_HOSTNAME\|ERR_HTTPERROR\|ERR_HTTPTE\|ERR_HWBMCLOSEDISP\|ERR_HWBRUSH\|ERR_HWBRUSHFUNC\|ERR_HWDBFREEDISP\|ERR_ICONDIMS\|ERR_ICONENTRY\|ERR_ICONPARMS\|ERR_ICONSIZE\|ERR_ICONSTANDARD\|ERR_ICONVECTOR\|ERR_IFWOENDIF\|ERR_IMAGEERROR\|ERR_INCOMPATBRUSH\|ERR_INISYNTAX\|ERR_INITSERIAL\|ERR_INTERNAL\|ERR_INTERNAL1\|ERR_INTEXPECTED\|ERR_INVALIDDATE\|ERR_INVALIDUTF8\|ERR_INVALIDUTF8ARG\|ERR_INVCAPIDX\|ERR_INVINSERT\|ERR_INVNEXTKEY\|ERR_INVPATCAP\|ERR_INVREPLACE\|ERR_JAVA\|ERR_JAVAMETHOD\|ERR_JOYSTICK\|ERR_KEYFILE\|ERR_KEYNOTFOUND\|ERR_KEYWORD\|ERR_KICKSTART\|ERR_LABELDECLA\|ERR_LABELDOUBLE\|ERR_LABINFOR\|ERR_LABINFUNC\|ERR_LABINIF\|ERR_LABINWHILE\|ERR_LABMAINBLK\|ERR_LAYERRANGE\|ERR_LAYERSOFF\|ERR_LAYERSON\|ERR_LAYERSUPPORT\|ERR_LAYERSUPPORT2\|ERR_LAYERSWITCH\|ERR_LEGACYPTMOD\|ERR_LFSYNTAX\|ERR_LINKFONT\|ERR_LINKPLUGIN\|ERR_LOADFRAME\|ERR_LOADICON\|ERR_LOADPICTURE\|ERR_LOADPICTURE2\|ERR_LOADPLUGIN\|ERR_LOADSOUND\|ERR_LOADVIDEO\|ERR_LOCK\|ERR_LOCK2\|ERR_LOCKBMAP\|ERR_LOCKEDOBJ\|ERR_LOOPRANGE\|ERR_LOWFREQ\|ERR_MAGICKEY\|ERR_MALFORMPAT1\|ERR_MALFORMPAT2\|ERR_MASKNALPHA\|ERR_MAXLINES\|ERR_MAXLOCALS\|ERR_MAXPARAMS\|ERR_MAXUPVALS\|ERR_MEDIAFOUNDATION\|ERR_MEM\|ERR_MEMCODE\|ERR_MEMCST\|ERR_MEMRANGE\|ERR_MENUATTACHED\|ERR_MENUCOMPLEXITY\|ERR_MISSINGBRACKET\|ERR_MISSINGFIELD\|ERR_MISSINGOPBRACK\|ERR_MISSINGPARAMTR\|ERR_MISSINGSEPARTR\|ERR_MIXMUSMOD\|ERR_MOBILE\|ERR_MODIFYAANIM\|ERR_MODIFYABG\|ERR_MODIFYABGPIC\|ERR_MODIFYABR\|ERR_MODIFYPSMP\|ERR_MODIFYSPRITE\|ERR_MODIFYSPRITE2\|ERR_MONITORDIR\|ERR_MONITORFULLSCREEN\|ERR_MONITORRANGE\|ERR_MOVEFILE\|ERR_MSGPORT\|ERR_MULDISMOBILE\|ERR_MULTIBGPIC\|ERR_MULTIDISPLAYS\|ERR_MUSFMTSUPPORT\|ERR_MUSNOTPAUSED\|ERR_MUSNOTPLYNG\|ERR_MUSNOTPLYNG2\|ERR_MUSPAUSED\|ERR_MUSPLAYING\|ERR_NAMETOOLONG\|ERR_NAMEUSED\|ERR_NEEDAPPLICATION\|ERR_NEEDCOMPOSITE\|ERR_NEEDMORPHOS2\|ERR_NEEDOS41\|ERR_NEEDPALETTEIMAGE\|ERR_NEGCOORDS\|ERR_NEWHWPLUGIN\|ERR_NEXTWOFOR\|ERR_NOABSPATH\|ERR_NOACCESS\|ERR_NOALPHA\|ERR_NOANMLAYER\|ERR_NOAPPLET\|ERR_NOARGBVISUAL\|ERR_NOBLOCKBREAK\|ERR_NOCALLBACK\|ERR_NOCHANNEL\|ERR_NOCHAR\|ERR_NOCLIPREG\|ERR_NOCOLON\|ERR_NOCOMMA\|ERR_NOCOMPRESS\|ERR_NOCONSTANTS\|ERR_NOCONTEXTMENU\|ERR_NOCOORDCST\|ERR_NODIRPATTERN\|ERR_NODISLAYERS\|ERR_NODISPMODES\|ERR_NODOUBLEBUFFER\|ERR_NOFALLTHROUGH\|ERR_NOFILTERNAME\|ERR_NOFMBHANDLER\|ERR_NOFUNCTION\|ERR_NOHWFUNC\|ERR_NOJOYATPORT\|ERR_NOKEYWORDS\|ERR_NOLAYERS\|ERR_NOLOOP\|ERR_NOLOOPCONT\|ERR_NOMASKBRUSH\|ERR_NOMENU\|ERR_NOMIMEVIEWER\|ERR_NOMUSICCB\|ERR_NONE\|ERR_NONSUSPENDEDRESUME\|ERR_NOPALETTE\|ERR_NOPALETTEIMAGE\|ERR_NOPALETTEMODE\|ERR_NORETVAL\|ERR_NOREXX\|ERR_NOSPRITES\|ERR_NOTADIR\|ERR_NOTENOUGHPIXELS\|ERR_NOTIGER\|ERR_NOTPROTRACKER\|ERR_NOTRANSPARENCY\|ERR_NOTXTLAYER\|ERR_NUMBEREXPECTED\|ERR_NUMCALLBACK\|ERR_NUMCONCAT\|ERR_NUMEXPECTED\|ERR_NUMSTRCMP\|ERR_NUMTABLEARG\|ERR_OLDAPPLET\|ERR_OPENANIM\|ERR_OPENANIM2\|ERR_OPENAUDIO\|ERR_OPENFONT\|ERR_OPENLIB\|ERR_OPENSERIAL\|ERR_OPENSOCKET\|ERR_OPENSOUND\|ERR_OPENSOUND2\|ERR_OUTOFRANGE\|ERR_PAKFORMAT\|ERR_PALETTEFILL\|ERR_PALETTEMODE\|ERR_PALSCREEN\|ERR_PEERNAME\|ERR_PENRANGE\|ERR_PERCENTFORMAT\|ERR_PERCENTFORMATSTR\|ERR_PIPE\|ERR_PIXELFORMAT\|ERR_PIXELRANGE\|ERR_PLAYERCOMP\|ERR_PLAYVIDEO\|ERR_PLUGINARCH\|ERR_PLUGINDOUBLET\|ERR_PLUGINSUPPORT\|ERR_PLUGINSYMBOL\|ERR_PLUGINTYPE\|ERR_PLUGINVER\|ERR_POINTERFORMAT\|ERR_POINTERIMG\|ERR_PORTNOTAVAIL\|ERR_PREPROCSYM\|ERR_PROTMETATABLE\|ERR_PUBSCREEN\|ERR_QUICKTIME\|ERR_RADIOTOGGLEMENU\|ERR_RANDOMIZE\|ERR_READ\|ERR_READFILE\|ERR_READFUNC\|ERR_READONLY\|ERR_READRANGE\|ERR_READTABLE\|ERR_READVIDEOPIXELS\|ERR_RECVCLOSED\|ERR_RECVTIMEOUT\|ERR_RECVUNKNOWN\|ERR_REGCLASS\|ERR_REGISTRYREAD\|ERR_REGISTRYWRITE\|ERR_REMADLAYER\|ERR_RENAME\|ERR_RENDER\|ERR_RENDERADLAYER\|ERR_RENDERCALLBACK\|ERR_RENDERER\|ERR_REPEATWOUNTIL\|ERR_REQAUTH\|ERR_REQUIREFIELD\|ERR_REQUIREPLUGIN\|ERR_REQUIRETAGFMT\|ERR_RETWOGOSUB\|ERR_REVDWORD\|ERR_REWINDDIR\|ERR_REXXERR\|ERR_SATELLITE\|ERR_SATFREEDISP\|ERR_SAVEANIM\|ERR_SAVEICON\|ERR_SAVEIMAGE\|ERR_SAVEPNG\|ERR_SAVERALPHA\|ERR_SAVESAMPLE\|ERR_SCALEBGPIC\|ERR_SCREEN\|ERR_SCREENMODE\|ERR_SCREENSIZE\|ERR_SCRPIXFMT\|ERR_SEEK\|ERR_SEEKFILE\|ERR_SEEKFORMAT\|ERR_SEEKRANGE\|ERR_SELECTALPHACHANNEL\|ERR_SELECTANIM\|ERR_SELECTBG\|ERR_SELECTBGPIC\|ERR_SELECTBGPIC2\|ERR_SELECTBRUSH\|ERR_SELECTMASK\|ERR_SEMAPHORE\|ERR_SENDDATA\|ERR_SENDMESSAGE\|ERR_SENDTIMEOUT\|ERR_SENDUNKNOWN\|ERR_SERIALIO\|ERR_SERIALIZE\|ERR_SERIALIZETYPE\|ERR_SETADAPTER\|ERR_SETENV\|ERR_SETFILEATTR\|ERR_SETFILECOMMENT\|ERR_SETFILEDATE\|ERR_SETMENU\|ERR_SHORTIF\|ERR_SIGNAL\|ERR_SMODEALPHA\|ERR_SMPRANGE\|ERR_SOCKET\|ERR_SOCKNAME\|ERR_SOCKOPT\|ERR_SORTFUNC\|ERR_SPRITELINK\|ERR_SPRITEONSCREEN\|ERR_SPRITEONSCREEN2\|ERR_SQBRACKETCLOSE\|ERR_SQBRACKETOPEN\|ERR_STACK\|ERR_STAT\|ERR_STRCALLBACK\|ERR_STREAMASSAMPLE\|ERR_STREXPECTED\|ERR_STRINGCST\|ERR_STRINGEXPECTED\|ERR_STRORNUM\|ERR_STRTABLEARG\|ERR_STRTOOSHORT\|ERR_SURFACE\|ERR_SWCHWOENDSWCH\|ERR_SYNTAXERROR\|ERR_SYNTAXLEVELS\|ERR_SYSBUTTON\|ERR_SYSIMAGE\|ERR_SYSTOOOLD\|ERR_TABCALLBACK\|ERR_TABEXPECTED\|ERR_TABEXPECTED2\|ERR_TABEXPECTED3\|ERR_TABLEDECLA\|ERR_TABLEINDEX\|ERR_TABLEORNIL\|ERR_TABLEOVERFLOW\|ERR_TAGEXPECTED\|ERR_TASKSETUP\|ERR_TEXTARG\|ERR_TEXTCONVERT\|ERR_TEXTCONVERT2\|ERR_TEXTSYNTAX\|ERR_TEXTURE\|ERR_TFIMAGE\|ERR_TFVANIM\|ERR_TFVBGPICBRUSH\|ERR_TFVBRUSH\|ERR_TFVBRUSHBGPIC\|ERR_THREAD\|ERR_THREADEXPECTED\|ERR_TIMER\|ERR_TOKENEXPECTED\|ERR_TOOMANYARGS\|ERR_TOOMANYCAPTURES\|ERR_TOOSMALL2\|ERR_TRANSBGMOBILE\|ERR_TRANSBRUSH\|ERR_TRAYICON\|ERR_TRIALCOMPILE\|ERR_TRIALINCLUDE\|ERR_TRIALLIMIT\|ERR_TRIALSAVEVID\|ERR_UDEXPECTED\|ERR_UNBALANCEDPAT\|ERR_UNEXPECTEDEOF\|ERR_UNEXPECTEDSYM\|ERR_UNFINISHEDCAPTURE\|ERR_UNIMPLCMD\|ERR_UNKNOWN\|ERR_UNKNOWNANMOUT\|ERR_UNKNOWNATTR\|ERR_UNKNOWNCMD\|ERR_UNKNOWNCOND\|ERR_UNKNOWNFILTER\|ERR_UNKNOWNICNOUT\|ERR_UNKNOWNIMGOUT\|ERR_UNKNOWNMIMETYPE\|ERR_UNKNOWNMUSFMT\|ERR_UNKNOWNPALETTE\|ERR_UNKNOWNSEC\|ERR_UNKNOWNSEQ\|ERR_UNKNOWNSMPOUT\|ERR_UNKNOWNTAG\|ERR_UNKNUMFMT\|ERR_UNKPROTOCOL\|ERR_UNKTEXTFMT\|ERR_UNMPARENTHESES\|ERR_UNSETENV\|ERR_UNSUPPORTEDFEAT\|ERR_UNTERMINTDSTR\|ERR_UNTILWOREPEAT\|ERR_UPDATEICON\|ERR_UPLOADFORBIDDEN\|ERR_USERABORT\|ERR_VALUEEXPECTED\|ERR_VAREXPECTED\|ERR_VARLENGTH\|ERR_VARSYNTAX\|ERR_VECGFXPLUGIN\|ERR_VECTORANIM\|ERR_VECTORBRUSH\|ERR_VERSION\|ERR_VFONT\|ERR_VFONTTYPE\|ERR_VIDATTACHED\|ERR_VIDEOFRAME\|ERR_VIDEOINIT\|ERR_VIDEOLAYER\|ERR_VIDEOLAYERDRV\|ERR_VIDEOSTRATEGY\|ERR_VIDEOTRANS\|ERR_VIDLAYERFUNC\|ERR_VIDNOTPAUSED\|ERR_VIDNOTPLAYING\|ERR_VIDPAUSED\|ERR_VIDPLAYING\|ERR_VIDRECMULTI\|ERR_VIDRECTRANS\|ERR_VIDSTOPPED\|ERR_VISUALINFO\|ERR_VMMISMATCH\|ERR_WARPOS\|ERR_WENDWOWHILE\|ERR_WHILEWOWEND\|ERR_WINDOW\|ERR_WITHWOENDWITH\|ERR_WRITE\|ERR_WRITEFILE\|ERR_WRITEJPEG\|ERR_WRITEONLY\|ERR_WRONGCLIPREG\|ERR_WRONGCMDRECVIDEO\|ERR_WRONGDTYPE\|ERR_WRONGFLOAT\|ERR_WRONGHEX\|ERR_WRONGID\|ERR_WRONGOP\|ERR_WRONGOPCST\|ERR_WRONGSPRITESIZE\|ERR_WRONGUSAGE\|ERR_WRONGVSTRATEGY\|ERR_XCURSOR\|ERR_XDISPLAY\|ERR_XF86VIDMODEEXT\|ERR_XFIXES\|ERR_YIELD\|ERR_ZERODIVISION\|ERR_ZLIBDATA\|ERR_ZLIBIO\|ERR_ZLIBSTREAM\|ERR_ZLIBVERSION\|EVENTHANDLER\|FADE\|FASTMEMORY\|FASTSPEED\|FILE\|FILEATTR_ARCHIVE\|FILEATTR_DELETE_USR\|FILEATTR_EXECUTE_GRP\|FILEATTR_EXECUTE_OTH\|FILEATTR_EXECUTE_USR\|FILEATTR_HIDDEN\|FILEATTR_NORMAL\|FILEATTR_PURE\|FILEATTR_READ_GRP\|FILEATTR_READ_OTH\|FILEATTR_READ_USR\|FILEATTR_READONLY\|FILEATTR_SCRIPT\|FILEATTR_SYSTEM\|FILEATTR_WRITE_GRP\|FILEATTR_WRITE_OTH\|FILEATTR_WRITE_USR\|FILETYPE_ANIM\|FILETYPE_ICON\|FILETYPE_IMAGE\|FILETYPE_SOUND\|FILETYPE_VIDEO\|FILETYPEFLAGS_ALPHA\|FILETYPEFLAGS_FPS\|FILETYPEFLAGS_QUALITY\|FILETYPEFLAGS_SAVE\|FILLCOLOR\|FILLGRADIENT\|FILLNONE\|FILLRULEEVENODD\|FILLRULEWINDING\|FILLTEXTURE\|FLOAT\|FLOW_HARDWARE\|FLOW_OFF\|FLOW_XON_XOFF\|FONT\|FONTENGINE_INBUILT\|FONTENGINE_NATIVE\|FONTSLANT_ITALIC\|FONTSLANT_OBLIQUE\|FONTSLANT_ROMAN\|FONTTYPE_BITMAP\|FONTTYPE_COLOR\|FONTTYPE_VECTOR\|FONTWEIGHT_BLACK\|FONTWEIGHT_BOLD\|FONTWEIGHT_BOOK\|FONTWEIGHT_DEMIBOLD\|FONTWEIGHT_EXTRABLACK\|FONTWEIGHT_EXTRABOLD\|FONTWEIGHT_EXTRALIGHT\|FONTWEIGHT_HEAVY\|FONTWEIGHT_LIGHT\|FONTWEIGHT_MEDIUM\|FONTWEIGHT_NORMAL\|FONTWEIGHT_REGULAR\|FONTWEIGHT_SEMIBOLD\|FONTWEIGHT_THIN\|FONTWEIGHT_ULTRABLACK\|FONTWEIGHT_ULTRABOLD\|FONTWEIGHT_ULTRALIGHT\|FRAMEMODE_FULL\|FRAMEMODE_SINGLE\|FREESPACE\|FTPASCII\|FTPBINARY\|FUCHSIA\|FUNCTION\|GRAY\|GREEN\|HBLINDS128\|HBLINDS16\|HBLINDS32\|HBLINDS64\|HBLINDS8\|HCLOSECURTAIN\|HCLOSEGATE\|HEXNUMERICAL\|HFLIPCOIN\|HFLOWBOTTOM\|HFLOWTOP\|HIDEBRUSH\|HIDELAYER\|HKEY_CLASSES_ROOT\|HKEY_CURRENT_CONFIG\|HKEY_CURRENT_USER\|HKEY_LOCAL_MACHINE\|HKEY_USERS\|HLINES\|HLINES2\|HLOWFLIPCOIN\|HOLLYWOOD\|HOPENCURTAIN\|HOPENGATE\|HSPLIT\|HSTRANGEPUSH\|HSTRETCHCENTER\|HSTRIPES\|HSTRIPES16\|HSTRIPES2\|HSTRIPES32\|HSTRIPES4\|HSTRIPES64\|HSTRIPES8\|HW_64BIT\|HW_AMIGA\|HW_AMIGAOS3\|HW_AMIGAOS4\|HW_ANDROID\|HW_AROS\|HW_IOS\|HW_LINUX\|HW_LITTLE_ENDIAN\|HW_MACOS\|HW_MORPHOS\|HW_REVISION\|HW_VERSION\|HW_WARPOS\|HW_WINDOWS\|ICNFMT_HOLLYWOOD\|ICON\|IMAGETYPE_RASTER\|IMAGETYPE_VECTOR\|IMGFMT_BMP\|IMGFMT_GIF\|IMGFMT_ILBM\|IMGFMT_JPEG\|IMGFMT_NATIVE\|IMGFMT_PLUGIN\|IMGFMT_PNG\|IMGFMT_TIFF\|IMGFMT_UNKNOWN\|IMMERSIVE_LEANBACK\|IMMERSIVE_NONE\|IMMERSIVE_NORMAL\|IMMERSIVE_STICKY\|INACTIVEWINDOW\|INF\|INSERTBRUSH\|INTEGER\|INTERVAL\|IO_BUFFERED\|IO_FAKE64\|IO_LITTLEENDIAN\|IO_SIGNED\|IO_UNBUFFERED\|IO_UNSIGNED\|IPAUTO\|IPUNKNOWN\|IPV4\|IPV6\|ITALIC\|JOINBEVEL\|JOINMITER\|JOINROUND\|JOYDOWN\|JOYDOWNLEFT\|JOYDOWNRIGHT\|JOYLEFT\|JOYNODIR\|JOYRIGHT\|JOYUP\|JOYUPLEFT\|JOYUPRIGHT\|JUSTIFIED\|KEEPASPRAT\|KEEPPOSITION\|LANGUAGE_ABKHAZIAN\|LANGUAGE_AFAR\|LANGUAGE_AFRIKAANS\|LANGUAGE_AKAN\|LANGUAGE_ALBANIAN\|LANGUAGE_AMHARIC\|LANGUAGE_ARABIC\|LANGUAGE_ARAGONESE\|LANGUAGE_ARMENIAN\|LANGUAGE_ASSAMESE\|LANGUAGE_AVARIC\|LANGUAGE_AVESTAN\|LANGUAGE_AYMARA\|LANGUAGE_AZERBAIJANI\|LANGUAGE_BAMBARA\|LANGUAGE_BASHKIR\|LANGUAGE_BASQUE\|LANGUAGE_BELARUSIAN\|LANGUAGE_BENGALI\|LANGUAGE_BIHARI\|LANGUAGE_BISLAMA\|LANGUAGE_BOSNIAN\|LANGUAGE_BRETON\|LANGUAGE_BULGARIAN\|LANGUAGE_BURMESE\|LANGUAGE_CATALAN\|LANGUAGE_CENTRALKHMER\|LANGUAGE_CHAMORRO\|LANGUAGE_CHECHEN\|LANGUAGE_CHICHEWA\|LANGUAGE_CHINESE\|LANGUAGE_CHURCHSLAVIC\|LANGUAGE_CHUVASH\|LANGUAGE_CORNISH\|LANGUAGE_CORSICAN\|LANGUAGE_CREE\|LANGUAGE_CROATIAN\|LANGUAGE_CZECH\|LANGUAGE_DANISH\|LANGUAGE_DIVEHI\|LANGUAGE_DUTCH\|LANGUAGE_DZONGKHA\|LANGUAGE_ENGLISH\|LANGUAGE_ESPERANTO\|LANGUAGE_ESTONIAN\|LANGUAGE_EWE\|LANGUAGE_FAROESE\|LANGUAGE_FIJIAN\|LANGUAGE_FINNISH\|LANGUAGE_FRENCH\|LANGUAGE_FULAH\|LANGUAGE_GAELIC\|LANGUAGE_GALICIAN\|LANGUAGE_GANDA\|LANGUAGE_GEORGIAN\|LANGUAGE_GERMAN\|LANGUAGE_GREEK\|LANGUAGE_GREENLANDIC\|LANGUAGE_GUARANI\|LANGUAGE_GUJARATI\|LANGUAGE_HAITIAN\|LANGUAGE_HAUSA\|LANGUAGE_HEBREW\|LANGUAGE_HERERO\|LANGUAGE_HINDI\|LANGUAGE_HIRIMOTU\|LANGUAGE_HUNGARIAN\|LANGUAGE_ICELANDIC\|LANGUAGE_IDO\|LANGUAGE_IGBO\|LANGUAGE_INDONESIAN\|LANGUAGE_INTERLINGUA\|LANGUAGE_INTERLINGUE\|LANGUAGE_INUKTITUT\|LANGUAGE_INUPIAQ\|LANGUAGE_IRISH\|LANGUAGE_ITALIAN\|LANGUAGE_JAPANESE\|LANGUAGE_JAVANESE\|LANGUAGE_KANNADA\|LANGUAGE_KANURI\|LANGUAGE_KASHMIRI\|LANGUAGE_KAZAKH\|LANGUAGE_KIKUYU\|LANGUAGE_KINYARWANDA\|LANGUAGE_KIRGHIZ\|LANGUAGE_KOMI\|LANGUAGE_KONGO\|LANGUAGE_KOREAN\|LANGUAGE_KUANYAMA\|LANGUAGE_KURDISH\|LANGUAGE_LAO\|LANGUAGE_LATIN\|LANGUAGE_LATVIAN\|LANGUAGE_LIMBURGAN\|LANGUAGE_LINGALA\|LANGUAGE_LITHUANIAN\|LANGUAGE_LUBAKATANGA\|LANGUAGE_LUXEMBOURGISH\|LANGUAGE_MACEDONIAN\|LANGUAGE_MALAGASY\|LANGUAGE_MALAY\|LANGUAGE_MALAYALAM\|LANGUAGE_MALTESE\|LANGUAGE_MANX\|LANGUAGE_MAORI\|LANGUAGE_MARATHI\|LANGUAGE_MARSHALLESE\|LANGUAGE_MONGOLIAN\|LANGUAGE_NAURU\|LANGUAGE_NAVAJO\|LANGUAGE_NDONGA\|LANGUAGE_NEPALI\|LANGUAGE_NORTHERNSAMI\|LANGUAGE_NORTHNDEBELE\|LANGUAGE_NORWEGIAN\|LANGUAGE_NORWEGIANBOKMAL\|LANGUAGE_NORWEGIANNYNORSK\|LANGUAGE_OCCITAN\|LANGUAGE_OJIBWA\|LANGUAGE_ORIYA\|LANGUAGE_OROMO\|LANGUAGE_OSSETIAN\|LANGUAGE_PALI\|LANGUAGE_PANJABI\|LANGUAGE_PASHTO\|LANGUAGE_PERSIAN\|LANGUAGE_POLISH\|LANGUAGE_PORTUGUESE\|LANGUAGE_QUECHUA\|LANGUAGE_ROMANIAN\|LANGUAGE_ROMANSH\|LANGUAGE_RUNDI\|LANGUAGE_RUSSIAN\|LANGUAGE_SAMOAN\|LANGUAGE_SANGO\|LANGUAGE_SANSKRIT\|LANGUAGE_SARDINIAN\|LANGUAGE_SERBIAN\|LANGUAGE_SHONA\|LANGUAGE_SICHUANYI\|LANGUAGE_SINDHI\|LANGUAGE_SINHALA\|LANGUAGE_SLOVAK\|LANGUAGE_SLOVENIAN\|LANGUAGE_SOMALI\|LANGUAGE_SOUTHERNSOTHO\|LANGUAGE_SOUTHNDEBELE\|LANGUAGE_SPANISH\|LANGUAGE_SUNDANESE\|LANGUAGE_SWAHILI\|LANGUAGE_SWATI\|LANGUAGE_SWEDISH\|LANGUAGE_TAGALOG\|LANGUAGE_TAHITIAN\|LANGUAGE_TAJIK\|LANGUAGE_TAMIL\|LANGUAGE_TATAR\|LANGUAGE_TELUGU\|LANGUAGE_THAI\|LANGUAGE_TIBETAN\|LANGUAGE_TIGRINYA\|LANGUAGE_TONGA\|LANGUAGE_TSONGA\|LANGUAGE_TSWANA\|LANGUAGE_TURKISH\|LANGUAGE_TURKMEN\|LANGUAGE_TWI\|LANGUAGE_UIGHUR\|LANGUAGE_UKRAINIAN\|LANGUAGE_UNKNOWN\|LANGUAGE_URDU\|LANGUAGE_UZBEK\|LANGUAGE_VENDA\|LANGUAGE_VIETNAMESE\|LANGUAGE_WALLOON\|LANGUAGE_WELSH\|LANGUAGE_WESTERNFRISIAN\|LANGUAGE_WOLOF\|LANGUAGE_XHOSA\|LANGUAGE_YIDDISH\|LANGUAGE_YORUBA\|LANGUAGE_ZHUANG\|LANGUAGE_ZULU\|LAYER\|LAYER_VS_BOX\|LAYERBUTTON\|LEFT\|LEFTOUT\|LIGHTUSERDATA\|LIME\|LINE\|LINEAR\|LITTLEENDIAN\|LONG\|LOWERCURVE\|MAROON\|MASK\|MASKAND\|MASKINVISIBLE\|MASKOR\|MASKVANILLACOPY\|MASKVISIBLE\|MASKXOR\|MEMORY\|MENU\|MENUITEM_DISABLED\|MENUITEM_RADIO\|MENUITEM_SELECTED\|MENUITEM_TOGGLE\|MILLISECONDS\|MODE_READ\|MODE_READWRITE\|MODE_WRITE\|MODLALT\|MODLCOMMAND\|MODLCONTROL\|MODLSHIFT\|MODRALT\|MODRCOMMAND\|MODRCONTROL\|MODRSHIFT\|MONO16\|MONO8\|MONOSPACE\|MOVEFILE_COPY\|MOVEFILE_COPYFAILED\|MOVEFILE_DELETE\|MOVEFILE_DELETEFAILED\|MOVEFILE_UNPROTECT\|MOVELIST\|MOVEWINDOW\|MUSIC\|NAN\|NATIVE\|NATIVEENDIAN\|NAVY\|NETWORKCONNECTION\|NETWORKSERVER\|NETWORKUDP\|NEXTFRAME\|NEXTFRAME2\|NIL\|NOCOLOR\|NONE\|NOPEN\|NORMAL\|NORMALSPEED\|NOTRANSPARENCY\|NUMBER\|NUMERICAL\|OLIVE\|ONBUTTONCLICK\|ONBUTTONCLICKALL\|ONBUTTONOVER\|ONBUTTONOVERALL\|ONBUTTONRIGHTCLICK\|ONBUTTONRIGHTCLICKALL\|ONKEYDOWN\|ONKEYDOWNALL\|ORIENTATION_LANDSCAPE\|ORIENTATION_LANDSCAPEREV\|ORIENTATION_NONE\|ORIENTATION_PORTRAIT\|ORIENTATION_PORTRAITREV\|PALETTE\|PALETTE_AGA\|PALETTE_CGA\|PALETTE_DEFAULT\|PALETTE_EGA\|PALETTE_GRAY128\|PALETTE_GRAY16\|PALETTE_GRAY256\|PALETTE_GRAY32\|PALETTE_GRAY4\|PALETTE_GRAY64\|PALETTE_GRAY8\|PALETTE_MACINTOSH\|PALETTE_MONOCHROME\|PALETTE_OCS\|PALETTE_WINDOWS\|PALETTE_WORKBENCH\|PALETTEMODE_PEN\|PALETTEMODE_REMAP\|PARITY_EVEN\|PARITY_NONE\|PARITY_ODD\|PERMREQ_READEXTERNAL\|PERMREQ_WRITEEXTERNAL\|PI\|PIXELZOOM1\|PIXELZOOM2\|PLOT\|PLUGINCAPS_ANIM\|PLUGINCAPS_AUDIOADAPTER\|PLUGINCAPS_CONVERT\|PLUGINCAPS_DIRADAPTER\|PLUGINCAPS_DISPLAYADAPTER\|PLUGINCAPS_EXTENSION\|PLUGINCAPS_FILEADAPTER\|PLUGINCAPS_ICON\|PLUGINCAPS_IMAGE\|PLUGINCAPS_IPCADAPTER\|PLUGINCAPS_LIBRARY\|PLUGINCAPS_NETWORKADAPTER\|PLUGINCAPS_REQUESTERADAPTER\|PLUGINCAPS_REQUIRE\|PLUGINCAPS_SAVEANIM\|PLUGINCAPS_SAVEICON\|PLUGINCAPS_SAVEIMAGE\|PLUGINCAPS_SAVESAMPLE\|PLUGINCAPS_SERIALIZE\|PLUGINCAPS_SOUND\|PLUGINCAPS_TIMERADAPTER\|PLUGINCAPS_VECTOR\|PLUGINCAPS_VIDEO\|POINTER\|POLYGON\|PRGTYPE_APPLET\|PRGTYPE_PROGRAM\|PRGTYPE_SCRIPT\|PRINT\|PURPLE\|PUSHBOTTOM\|PUSHLEFT\|PUSHRIGHT\|PUSHTOP\|PUZZLE\|QUADRECT\|QUARTERS\|RADIAL\|RANDOMEFFECT\|RANDOMPARAMETER\|RECEIVEALL\|RECEIVEBYTES\|RECEIVEDATA_PACKET\|RECEIVELINE\|RECTBACKCENTER\|RECTBACKEAST\|RECTBACKNORTH\|RECTBACKNORTHEAST\|RECTBACKNORTHWEST\|RECTBACKSOUTH\|RECTBACKSOUTHEAST\|RECTBACKSOUTHWEST\|RECTBACKWEST\|RECTCENTER\|RECTEAST\|RECTNORTH\|RECTNORTHEAST\|RECTNORTHWEST\|RECTSOUTH\|RECTSOUTHEAST\|RECTSOUTHWEST\|RECTWEST\|RED\|REMOVELAYER\|REQ_CAMERA\|REQ_GALLERY\|REQ_HIDEICONS\|REQ_MULTISELECT\|REQ_NORMAL\|REQ_SAVEMODE\|REQICON_ERROR\|REQICON_INFORMATION\|REQICON_NONE\|REQICON_QUESTION\|REQICON_WARNING\|REVEALBOTTOM\|REVEALLEFT\|REVEALRIGHT\|REVEALTOP\|RIGHT\|RIGHTOUT\|ROLLLEFT\|ROLLTOP\|RTS_OFF\|RTS_ON\|SAMPLE\|SANS\|SCALEMODE_AUTO\|SCALEMODE_LAYER\|SCALEMODE_NONE\|SCROLLBOTTOM\|SCROLLEAST\|SCROLLLEFT\|SCROLLNORTH\|SCROLLNORTHEAST\|SCROLLNORTHWEST\|SCROLLRIGHT\|SCROLLSOUTH\|SCROLLSOUTHEAST\|SCROLLSOUTHWEST\|SCROLLTOP\|SCROLLWEST\|SECONDS\|SEEK_BEGINNING\|SEEK_CURRENT\|SEEK_END\|SELMODE_COMBO\|SELMODE_LAYERS\|SELMODE_NORMAL\|SERIAL\|SERIF\|SERVER\|SHADOW\|SHAPE\|SHDWEAST\|SHDWNORTH\|SHDWNORTHEAST\|SHDWNORTHWEST\|SHDWSOUTH\|SHDWSOUTHEAST\|SHDWSOUTHWEST\|SHDWWEST\|SHORT\|SILVER\|SIMPLEBUTTON\|SINE\|SIZEWINDOW\|SLIDEBOTTOM\|SLIDELEFT\|SLIDERIGHT\|SLIDETOP\|SLOWSPEED\|SMOOTHOUT\|SMPFMT_WAVE\|SNAPDESKTOP\|SNAPDISPLAY\|SNAPWINDOW\|SPIRAL\|SPRITE\|SPRITE_VS_BOX\|SPRITE_VS_BRUSH\|STAR\|STDERR\|STDIN\|STDOUT\|STDPTR_BUSY\|STDPTR_CUSTOM\|STDPTR_SYSTEM\|STEREO16\|STEREO8\|STOP_1\|STOP_2\|STRETCHBOTTOM\|STRETCHLEFT\|STRETCHRIGHT\|STRETCHTOP\|STRING\|STRUDEL\|SUN\|SWISS\|TABLE\|TEAL\|TEXTOBJECT\|TEXTOUT\|THREAD\|TICKS\|TIMEOUT\|TIMER\|TOP\|TOPOUT\|TRUETYPE_DEFAULT\|TURNDOWNBOTTOM\|TURNDOWNLEFT\|TURNDOWNRIGHT\|TURNDOWNTOP\|UDPCLIENT\|UDPNONE\|UDPOBJECT\|UDPSERVER\|UNDERLINED\|UNDO\|UPLOADFILE_RESPONSE\|UPLOADFILE_STATUS\|UPNDOWN\|UPPERCURVE\|USEDSPACE\|USELAYERPOSITION\|USERDATA\|VANILLACOPY\|VBLINDS128\|VBLINDS16\|VBLINDS32\|VBLINDS64\|VBLINDS8\|VCLOSECURTAIN\|VCLOSEGATE\|VECTORPATH\|VFLIPCOIN\|VFLOWLEFT\|VFLOWRIGHT\|VIDDRV_HOLLYWOOD\|VIDDRV_OS\|VIDEO\|VIEWMODE_DATE\|VIEWMODE_ICONS\|VIEWMODE_NAME\|VIEWMODE_NONE\|VIEWMODE_SIZE\|VIEWMODE_TYPE\|VLINES\|VLINES2\|VLOWFLIPCOIN\|VOID\|VOPENCURTAIN\|VOPENGATE\|VSPLIT\|VSTRANGEPUSH\|VSTRETCHCENTER\|VSTRIPES\|VSTRIPES16\|VSTRIPES2\|VSTRIPES32\|VSTRIPES4\|VSTRIPES64\|VSTRIPES8\|WALLPAPERLEFT\|WALLPAPERTOP\|WATER1\|WATER2\|WATER3\|WATER4\|WHITE\|WORD\|YELLOW\|ZOOMCENTER\|ZOOMEAST\|ZOOMIN\|ZOOMNORTH\|ZOOMNORTHEAST\|ZOOMNORTHWEST\|ZOOMOUT\|ZOOMSOUTH\|ZOOMSOUTHEAST\|ZOOMSOUTHWEST\|ZOOMWEST\)\>" " Hollywood Functions -syn keyword hwFunction ACos ARGB ASin ATan ATan2 Abs ActivateDisplay Add AddArcToPath AddBoxToPath AddCircleToPath AddEllipseToPath AddFontPath AddIconImage AddMove AddStr AddTab AddTextToPath AllocMem AllocMemFromPointer AllocMemFromVirtualFile AppendPath ApplyPatch Arc ArcDistortBrush ArrayToStr Asc Assert AsyncDrawFrame BGPicToBrush BarrelDistortBrush Base64Str Beep BeginAnimStream BeginDoubleBuffer BeginRefresh BinStr BitClear BitComplement BitSet BitTest BitXor Blue BlurBrush Box BreakEventHandler BreakWhileMouseOn BrushToBGPic BrushToGray BrushToMonochrome BrushToPenArray BrushToRGBArray ByteAsc ByteChr ByteLen ByteOffset ByteStrStr ByteVal CRC32 CRC32Str CallJavaMethod CancelAsyncDraw CancelAsyncOperation CanonizePath Cast Ceil ChangeApplicationIcon ChangeBrushTransparency ChangeDirectory ChangeDisplayMode ChangeDisplaySize ChangeInterval CharOffset CharWidth CharcoalBrush CheckEvent CheckEvents Chr Circle ClearClipboard ClearEvents ClearInterval ClearMove ClearObjectData ClearPath ClearScreen ClearSerialQueue ClearTimeout CloseAmigaGuide CloseAnim CloseAudio CloseCatalog CloseConnection CloseDirectory CloseDisplay CloseFile CloseFont CloseMusic ClosePath CloseResourceMonitor CloseSerialPort CloseServer CloseUDPObject CloseVideo Cls CollectGarbage Collision ColorRequest CompareDates CompareStr CompressFile Concat ConsolePrint ConsolePrintNR ConsolePrompt ContinueAsyncOperation ContrastBrush ContrastPalette ConvertStr ConvertToBrush CopyAnim CopyBGPic CopyBrush CopyFile CopyMem CopyObjectData CopyPalette CopyPath CopyPens CopySample CopySprite CopyTable CopyTextObject Cos CountDirectoryEntries CountJoysticks CountStr CreateAnim CreateBGPic CreateBorderBrush CreateBrush CreateButton CreateClipRegion CreateCoroutine CreateDisplay CreateGradientBGPic CreateGradientBrush CreateIcon CreateKeyDown CreateLayer CreateList CreateMenu CreateMusic CreatePalette CreatePointer CreatePort CreateRainbowBGPic CreateRexxPort CreateSample CreateServer CreateShadowBrush CreateShortcut CreateSprite CreateTextObject CreateTexturedBGPic CreateTexturedBrush CreateUDPObject CropBrush CtrlCQuit CurveTo CyclePalette DateToTimestamp DateToUTC DebugOutput DebugPrint DebugPrintNR DebugPrompt DebugStr DebugVal DecompressFile DecreasePointer DefineVirtualFile DefineVirtualFileFromString Deg DeleteAlphaChannel DeleteButton DeleteFile DeleteMask DeletePrefs DeselectMenuItem DeserializeTable DirectoryItems DisableButton DisableEvent DisableLayers DisableLineHook DisableMenuItem DisablePlugin DisableVWait DisplayAnimFrame DisplayBGPic DisplayBGPicPart DisplayBGPicPartFX DisplayBrush DisplayBrushFX DisplayBrushPart DisplaySprite DisplayTextObject DisplayTextObjectFX DisplayTransitionFX DisplayVideoFrame Div DoMove DownloadFile DrawPath DumpButtons DumpLayers DumpMem DumpVideo DumpVideoTime EdgeBrush Ellipse EmbossBrush EmptyStr EnableButton EnableEvent EnableLayers EnableLineHook EnableMenuItem EnablePlugin EnableVWait End EndDoubleBuffer EndRefresh EndSelect EndianSwap EndsWith Eof Error EscapeQuit Eval Execute Exists ExitOnError Exp ExtractPalette FileAttributes FileLength FileLines FilePart FilePos FileRequest FileSize FileToString FillMem FillMusicBuffer FindStr FinishAnimStream FinishAsyncDraw Flip FlipBrush FlipSprite FloodFill Floor FlushFile FlushMusicBuffer FlushSerialPort FontRequest ForEach ForEachI ForcePathUse ForceSound ForceVideoDriver ForceVideoMode FormatStr FrExp Frac FreeAnim FreeBGPic FreeBrush FreeClipRegion FreeDisplay FreeEventCache FreeGlyphCache FreeIcon FreeLayers FreeMem FreeMenu FreeModule FreePalette FreePath FreePointer FreeSample FreeSprite FreeTextObject FullPath GCInfo GammaBrush GammaPalette GetAnimFrame GetApplicationInfo GetApplicationList GetAsset GetAttribute GetAvailableFonts GetBaudRate GetBestPen GetBrushLink GetBrushPen GetBulletColor GetCatalogString GetChannels GetCharMaps GetClipboard GetCommandLine GetConnectionIP GetConnectionPort GetConnectionProtocol GetConstant GetCoroutineStatus GetCountryInfo GetCurrentDirectory GetCurrentPoint GetDTR GetDash GetDataBits GetDate GetDateNum GetDefaultEncoding GetDirectoryEntry GetDisplayModes GetEnv GetErrorName GetEventCode GetFPSLimit GetFileArgument GetFileAttributes GetFillRule GetFillStyle GetFlowControl GetFontColor GetFontStyle GetFormStyle GetFrontScreen GetHostName GetIconProperties GetItem GetKerningPair GetLanguageInfo GetLastError GetLayerAtPos GetLayerPen GetLayerStyle GetLineCap GetLineJoin GetLineWidth GetLocalIP GetLocalInterfaces GetLocalPort GetLocalProtocol GetMACAddress GetMemPointer GetMemString GetMemoryInfo GetMetaTable GetMiterLimit GetMonitors GetObjectData GetObjectType GetObjects GetPalettePen GetParity GetPathExtents GetPatternPosition GetPen GetPlugins GetProgramDirectory GetProgramInfo GetPubScreens GetRTS GetRandomColor GetRandomFX GetRealColor GetSampleData GetShortcutPath GetSongPosition GetStartDirectory GetStopBits GetSystemCountry GetSystemInfo GetSystemLanguage GetTempFileName GetTime GetTimeZone GetTimer GetTimestamp GetType GetVersion GetVideoFrame GetVolumeInfo GetVolumeName GetWeekday GrabDesktop Green HaveFreeChannel HaveItem HaveObject HaveObjectData HavePlugin HaveVolume HexStr HideDisplay HideKeyboard HideLayer HideLayerFX HidePointer HideScreen Hypot IIf IPairs IgnoreCase ImageRequest InKeyStr IncreasePointer InsertItem InsertLayer InsertSample InsertStr InstallEventHandler Int Intersection InvertAlphaChannel InvertBrush InvertMask InvertPalette IsAbsolutePath IsAlNum IsAlpha IsAnim IsBrushEmpty IsChannelPlaying IsCntrl IsDigit IsDirectory IsFinite IsGraph IsInf IsKeyDown IsLeftMouse IsLower IsMenuItemDisabled IsMenuItemSelected IsMidMouse IsModule IsMusic IsMusicPlaying IsNan IsNil IsOnline IsPathEmpty IsPicture IsPrint IsPunct IsRightMouse IsSample IsSamplePlaying IsSound IsSpace IsTableEmpty IsUnicode IsUpper IsVideo IsVideoPlaying IsXDigit JoyDir JoyFire LayerExists LayerToBack LayerToFront Ld LdExp LeftMouseQuit LeftStr LegacyControl Limit Line LineTo ListItems ListRequest Ln LoadAnim LoadAnimFrame LoadBGPic LoadBrush LoadIcon LoadModule LoadPalette LoadPlugin LoadPrefs LoadSample LoadSprite Locate Log LowerStr MD5 MD5Str MakeButton MakeDate MakeDirectory MakeHostPath MatchPattern Max MemToTable MidStr Min MixBrush MixRGB MixSample Mod ModifyAnimFrames ModifyButton ModifyKeyDown ModifyLayerFrames ModulateBrush ModulatePalette MonitorDirectory MouseX MouseY MoveAnim MoveBrush MoveDisplay MoveFile MoveLayer MovePointer MoveSprite MoveTextObject MoveTo Mul NPrint NextDirectoryEntry NextFrame NextItem NormalizePath OilPaintBrush OpenAmigaGuide OpenAnim OpenAudio OpenCatalog OpenConnection OpenDirectory OpenDisplay OpenFile OpenFont OpenMusic OpenResourceMonitor OpenSerialPort OpenURL OpenVideo Pack PadNum Pairs PaletteToGray ParseDate PathItems PathPart PathRequest PathToBrush PatternFindStr PatternFindStrDirect PatternFindStrShort PatternReplaceStr PauseLayer PauseModule PauseMusic PauseTimer PauseVideo Peek PeekClipboard PenArrayToBrush PerformSelector PermissionRequest PerspectiveDistortBrush Pi PixelateBrush PlayAnim PlayAnimDisk PlayLayer PlayModule PlayMusic PlaySample PlaySubsong PlayVideo Plot Poke PolarDistortBrush PollSerialQueue Polygon Pow Print QuantizeBrush RGB RGBArrayToBrush Rad RaiseOnError RasterizeBrush RawDiv RawEqual RawGet RawSet ReadBrushPixel ReadByte ReadBytes ReadChr ReadDirectory ReadFloat ReadFunction ReadInt ReadLine ReadMem ReadPen ReadPixel ReadRegistryKey ReadSerialData ReadShort ReadString ReadTable ReceiveData ReceiveUDPData Red ReduceAlphaChannel RefreshDisplay RelCurveTo RelLineTo RelMoveTo RemapBrush RemoveBrushPalette RemoveButton RemoveIconImage RemoveItem RemoveKeyDown RemoveLayer RemoveLayerFX RemoveLayers RemoveSprite RemoveSprites Rename RepeatStr ReplaceColors ReplaceStr ResetKeyStates ResetTabs ResetTimer ResolveHostName ResumeCoroutine ResumeLayer ResumeModule ResumeMusic ResumeTimer ResumeVideo ReverseFindStr ReverseStr RewindDirectory RightStr Rnd RndF RndStrong Rol Ror RotateBrush RotateLayer RotateTextObject Round Rt Run RunCallback RunRexxScript Sar SaveAnim SaveBrush SaveIcon SavePalette SavePrefs SaveSample SaveSnapshot ScaleAnim ScaleBGPic ScaleBrush ScaleLayer ScaleSprite ScaleTextObject Seek SeekLayer SeekMusic SeekVideo SelectAlphaChannel SelectAnim SelectBGPic SelectBrush SelectDisplay SelectLayer SelectMask SelectMenuItem SelectPalette SendApplicationMessage SendData SendMessage SendRexxCommand SendUDPData SepiaToneBrush SerializeTable SetAlphaIntensity SetAnimFrameDelay SetBaudRate SetBorderPen SetBrushDepth SetBrushPalette SetBrushPen SetBrushTransparency SetBrushTransparentPen SetBulletColor SetBulletPen SetChannelVolume SetClipRegion SetClipboard SetCycleTable SetDTR SetDash SetDataBits SetDefaultEncoding SetDepth SetDisplayAttributes SetDitherMode SetDrawPen SetDrawTagsDefault SetEnv SetEventTimeout SetFPSLimit SetFileAttributes SetFileEncoding SetFillRule SetFillStyle SetFlowControl SetFont SetFontColor SetFontStyle SetFormStyle SetGradientPalette SetIOMode SetIconProperties SetInterval SetLayerAnchor SetLayerBorder SetLayerDepth SetLayerFilter SetLayerLight SetLayerName SetLayerPalette SetLayerPen SetLayerShadow SetLayerStyle SetLayerTint SetLayerTransparency SetLayerTransparentPen SetLayerVolume SetLayerZPos SetLineCap SetLineJoin SetLineWidth SetListItems SetMargins SetMaskMode SetMasterVolume SetMetaTable SetMiterLimit SetMusicVolume SetNetworkProtocol SetNetworkTimeout SetObjectData SetPalette SetPaletteDepth SetPaletteMode SetPalettePen SetPaletteTransparentPen SetPanning SetParity SetPen SetPitch SetPointer SetRTS SetScreenTitle SetShadowPen SetSpriteZPos SetStandardIconImage SetStandardPalette SetStopBits SetSubtitle SetTimeout SetTimerElapse SetTitle SetTransparentPen SetTransparentThreshold SetTrayIcon SetVectorEngine SetVideoPosition SetVideoSize SetVideoVolume SetVolume SetWBIcon Sgn SharpenBrush Shl ShowDisplay ShowKeyboard ShowLayer ShowLayerFX ShowNotification ShowPointer ShowRinghioMessage ShowScreen ShowToast Shr Sin SolarizeBrush SolarizePalette Sort SplitStr Sqrt StartPath StartSubPath StartTimer StartsWith StopChannel StopLayer StopModule StopMusic StopSample StopTimer StopVideo StrLen StrStr StrToArray StringRequest StringToFile StripStr Sub SwapLayers SwirlBrush SystemRequest TableItems TableToMem Tan TextExtent TextHeight TextOut TextWidth TimerElapsed TimestampToDate TintBrush TintPalette ToHostName ToIP ToNumber ToString ToUserData TransformBrush TransformLayer TranslateLayer TranslatePath TrimBrush TrimStr UTCToDate UndefineVirtualStringFile Undo UndoFX UnleftStr UnmidStr Unpack UnrightStr UnsetEnv UploadFile UpperStr UseCarriageReturn UseFont VWait Val ValidateDate ValidateStr Vibrate Wait WaitEvent WaitKeyDown WaitLeftMouse WaitMidMouse WaitPatternPosition WaitRightMouse WaitSampleEnd WaitSongPosition WaitTimer WaterRippleBrush WhileKeyDown WhileMouseDown WhileMouseOn WhileRightMouseDown Wrap WriteAnimFrame WriteBrushPixel WriteByte WriteBytes WriteChr WriteFloat WriteFunction WriteInt WriteLine WriteMem WritePen WriteRegistryKey WriteSerialData WriteShort WriteString WriteTable YieldCoroutine +syn keyword hwFunction Abs ACos ARGB ActivateDisplay Add AddArcToPath AddBoxToPath AddCircleToPath AddEllipseToPath AddFontPath AddIconImage AddMove AddStr AddTab AddTextToPath AllocMem AllocMemFromPointer AllocMemFromVirtualFile AppendPath ApplyPatch Arc ArcDistortBrush ArrayToStr Asc ASin Assert AsyncDrawFrame ATan ATan2 BarrelDistortBrush Base64Str Beep BeginAnimStream BeginDoubleBuffer BeginRefresh BGPicToBrush BinStr BitClear BitComplement BitSet BitTest BitXor Blue BlurBrush Box BreakEventHandler BreakWhileMouseOn BrushToBGPic BrushToGray BrushToMonochrome BrushToPenArray BrushToRGBArray ByteAsc ByteChr ByteLen ByteOffset ByteStrStr ByteVal CRC32 CRC32Str CallJavaMethod CancelAsyncDraw CancelAsyncOperation CanonizePath Cast Ceil ChangeApplicationIcon ChangeBrushTransparency ChangeDirectory ChangeDisplayMode ChangeDisplaySize ChangeInterval CharcoalBrush CharOffset CharWidth CheckEvent CheckEvents Chr Circle ClearClipboard ClearEvents ClearInterval ClearMove ClearObjectData ClearPath ClearScreen ClearSerialQueue ClearTimeout CloseAmigaGuide CloseAnim CloseAudio CloseCatalog CloseConnection CloseDirectory CloseDisplay CloseFile CloseFont CloseMusic ClosePath CloseResourceMonitor CloseSerialPort CloseServer CloseUDPObject CloseVideo Cls CollectGarbage Collision ColorRequest CompareDates CompareStr CompressFile Concat ConsolePrint ConsolePrintNR ConsolePrompt ContinueAsyncOperation ContrastBrush ContrastPalette ConvertStr ConvertToBrush CopyAnim CopyBGPic CopyBrush CopyFile CopyLayer CopyMem CopyObjectData CopyPalette CopyPath CopyPens CopySample CopySprite CopyTable CopyTextObject Cos CountDirectoryEntries CountJoysticks CountStr CreateAnim CreateBGPic CreateBorderBrush CreateBrush CreateButton CreateClipRegion CreateCoroutine CreateDisplay CreateGradientBGPic CreateGradientBrush CreateIcon CreateKeyDown CreateLayer CreateList CreateMenu CreateMusic CreatePalette CreatePointer CreatePort CreateRainbowBGPic CreateRexxPort CreateSample CreateServer CreateShadowBrush CreateShortcut CreateSprite CreateTextObject CreateTexturedBGPic CreateTexturedBrush CreateUDPObject CropBrush CtrlCQuit CurveTo CyclePalette DateToTimestamp DateToUTC DebugOutput DebugPrint DebugPrintNR DebugPrompt DebugStr DebugVal DecompressFile DecreasePointer DefineVirtualFile DefineVirtualFileFromString Deg DeleteAlphaChannel DeleteButton DeleteFile DeleteMask DeletePrefs DeselectMenuItem DeserializeTable DirectoryItems DisableButton DisableEvent DisableEventHandler DisableLayers DisableLineHook DisableMenuItem DisablePlugin DisablePrecalculation DisableVWait DisplayAnimFrame DisplayBGPic DisplayBGPicPart DisplayBGPicPartFX DisplayBrush DisplayBrushFX DisplayBrushPart DisplaySprite DisplayTextObject DisplayTextObjectFX DisplayTransitionFX DisplayVideoFrame Div DoMove DownloadFile DrawPath DumpButtons DumpLayers DumpMem DumpVideo DumpVideoTime EdgeBrush Ellipse EmbossBrush EmptyStr EnableButton EnableEventHandler EnableEvent EnableLayers EnableLineHook EnableMenuItem EnablePlugin EnablePrecalculation EnableVWait End EndDoubleBuffer EndianSwap EndRefresh EndSelect EndsWith Eof Error EscapeQuit Eval Execute Exists ExitOnError Exp ExtractPalette FileAttributes FileLength FileLines FilePart FilePos FileRequest FileSize FileToString FillMem FillMusicBuffer FindStr FinishAnimStream FinishAsyncDraw Flip FlipBrush FlipSprite FloodFill Floor FlushFile FlushMusicBuffer FlushSerialPort FontRequest ForcePathUse ForceSound ForceVideoDriver ForceVideoMode ForEach ForEachI FormatStr Frac FreeAnim FreeBGPic FreeBrush FreeClipRegion FreeDisplay FreeEventCache FreeGlyphCache FreeIcon FreeLayers FreeMem FreeMenu FreeModule FreePalette FreePath FreePointer FreeSample FreeSprite FreeTextObject FrExp FullPath GammaBrush GammaPalette GCInfo GetAnimFrame GetApplicationInfo GetApplicationList GetAsset GetAttribute GetAvailableFonts GetBaudRate GetBestPen GetBrushLink GetBrushPen GetBulletColor GetCatalogString GetChannels GetCharMaps GetClipboard GetCommandLine GetConnectionIP GetConnectionPort GetConnectionProtocol GetConstant GetCoroutineStatus GetCountryInfo GetCurrentDirectory GetCurrentPoint GetDash GetDataBits GetDate GetDateNum GetDefaultEncoding GetDirectoryEntry GetDisplayModes GetDTR GetEnv GetErrorName GetEventCode GetFileArgument GetFileAttributes GetFillRule GetFillStyle GetFlowControl GetFontColor GetFontStyle GetFormStyle GetFPSLimit GetFrontScreen GetHostName GetIconProperties GetItem GetKerningPair GetLanguageInfo GetLastError GetLayerAtPos GetLayerPen GetLayerStyle GetLineCap GetLineJoin GetLineWidth GetLocalInterfaces GetLocalIP GetLocalPort GetLocalProtocol GetMACAddress GetMemoryInfo GetMemPointer GetMemString GetMetaTable GetMiterLimit GetMonitors GetObjectData GetObjects GetObjectType GetPalettePen GetParity GetPathExtents GetPatternPosition GetPen GetPlugins GetProgramDirectory GetProgramInfo GetPubScreens GetRandomColor GetRandomFX GetRealColor GetRTS GetSampleData GetShortcutPath GetSongPosition GetStartDirectory GetStopBits GetSystemCountry GetSystemInfo GetSystemLanguage GetTempFileName GetTime GetTimer GetTimestamp GetTimeZone GetType GetVersion GetVideoFrame GetVolumeInfo GetVolumeName GetWeekday Gosub Goto GrabDesktop Green HaveFreeChannel HaveItem HaveObject HaveObjectData HavePlugin HaveVolume HexStr HideDisplay HideKeyboard HideLayer HideLayerFX HidePointer HideScreen Hypot IgnoreCase IIf ImageRequest IncreasePointer InKeyStr InsertItem InsertLayer InsertSample InsertStr InstallEventHandler Intersection Int InvertAlphaChannel InvertBrush InvertMask InvertPalette IPairs IsAbsolutePath IsAlNum IsAlpha IsAnim IsAnimPlaying IsBrushEmpty IsChannelPlaying IsCntrl IsDigit IsDirectory IsFinite IsGraph IsInf IsKeyDown IsLeftMouse IsLower IsMenuItemDisabled IsMenuItemSelected IsMidMouse IsModule IsMusicPlaying IsMusic IsNan IsNil IsOnline IsPathEmpty IsPicture IsPrint IsPunct IsRightMouse IsSamplePlaying IsSample IsSound IsSpace IsTableEmpty IsUnicode IsUpper IsVideo IsVideoPlaying IsXDigit JoyDir JoyFire Label LayerExists LayerToBack LayerToFront Ld LdExp LeftMouseQuit LeftStr LegacyControl Limit Line LineTo ListItems ListRequest Ln LoadAnim LoadAnimFrame LoadBGPic LoadBrush LoadIcon LoadModule LoadPalette LoadPlugin LoadPrefs LoadSample LoadSprite Locate Log LowerStr MakeButton MakeDate MakeDirectory MakeHostPath MatchPattern Max MD5 MD5Str MemToTable MidStr Min MixBrush MixRGB MixSample ModifyAnimFrames ModifyButton ModifyKeyDown ModifyLayerFrames ModulateBrush Mod ModulatePalette MonitorDirectory MouseX MouseY MoveAnim MoveBrush MoveDisplay MoveFile MoveLayer MovePointer MoveSprite MoveTextObject MoveTo Mul NextDirectoryEntry NextFrame NextItem NormalizePath NPrint OilPaintBrush OpenAmigaGuide OpenAnim OpenAudio OpenCatalog OpenConnection OpenDirectory OpenDisplay OpenFile OpenFont OpenMusic OpenResourceMonitor OpenSerialPort OpenURL OpenVideo Pack PadNum Pairs PaletteToGray ParseDate PathItems PathPart PathRequest PathToBrush PatternFindStr PatternFindStrDirect PatternFindStrShort PatternReplaceStr PauseLayer PauseModule PauseMusic PauseTimer PauseVideo PeekClipboard Peek PenArrayToBrush PerformSelector PermissionRequest PerspectiveDistortBrush Pi PixelateBrush PlayAnim PlayAnimDisk PlayLayer PlayModule PlayMusic PlaySample PlaySubsong PlayVideo Plot Poke PolarDistortBrush PollSerialQueue Polygon Pow Print QuantizeBrush Rad RaiseOnError RasterizeBrush RawDiv RawEqual RawGet RawSet ReadBrushPixel ReadByte ReadBytes ReadChr ReadDirectory ReadFloat ReadFunction ReadInt ReadLine ReadMem ReadPen ReadPixel ReadRegistryKey ReadSerialData ReadShort ReadString ReadTable ReceiveData ReceiveUDPData Red ReduceAlphaChannel RefreshDisplay RelCurveTo RelLineTo RelMoveTo RemapBrush RemoveBrushPalette RemoveButton RemoveIconImage RemoveItem RemoveKeyDown RemoveLayer RemoveLayerFX RemoveLayers RemoveSprite RemoveSprites Rename RepeatStr ReplaceColors ReplaceStr ResetKeyStates ResetTabs ResetTimer ResolveHostName ResumeCoroutine ResumeLayer ResumeModule ResumeMusic ResumeTimer ResumeVideo ReverseFindStr ReverseStr RewindDirectory RGB RGBArrayToBrush RightStr Rnd RndF RndStrong Rol Ror RotateBrush RotateLayer RotateTextObject Round Rt Run RunCallback RunRexxScript Sar SaveAnim SaveBrush SaveIcon SavePalette SavePrefs SaveSample SaveSnapshot ScaleAnim ScaleBGPic ScaleBrush ScaleLayer ScaleSprite ScaleTextObject Seek SeekLayer SeekMusic SeekVideo SelectAlphaChannel SelectAnim SelectBGPic SelectBrush SelectDisplay SelectLayer SelectMask SelectMenuItem SelectPalette SendApplicationMessage SendData SendMessage SendRexxCommand SendUDPData SepiaToneBrush SerializeTable SetAlphaIntensity SetAnimFrameDelay SetBaudRate SetBorderPen SetBrushDepth SetBrushPalette SetBrushPen SetBrushTransparency SetBrushTransparentPen SetBulletColor SetBulletPen SetChannelVolume SetClipboard SetClipRegion SetCycleTable SetDash SetDataBits SetDefaultEncoding SetDepth SetDisplayAttributes SetDitherMode SetDrawPen SetDrawTagsDefault SetDTR SetEnv SetEventTimeout SetFileAttributes SetFileEncoding SetFillRule SetFillStyle SetFlowControl SetFont SetFontColor SetFontStyle SetFormStyle SetFPSLimit SetGradientPalette SetIconProperties SetInterval SetIOMode SetLayerAnchor SetLayerBorder SetLayerDepth SetLayerFilter SetLayerLight SetLayerName SetLayerPalette SetLayerPen SetLayerShadow SetLayerStyle SetLayerTint SetLayerTransparency SetLayerTransparentPen SetLayerVolume SetLayerZPos SetLineCap SetLineJoin SetLineWidth SetListItems SetMargins SetMaskMode SetMasterVolume SetMetaTable SetMiterLimit SetMusicVolume SetNetworkProtocol SetNetworkTimeout SetObjectData SetPalette SetPaletteDepth SetPaletteMode SetPalettePen SetPaletteTransparentPen SetPanning SetParity SetPen SetPitch SetPointer SetRTS SetScreenTitle SetShadowPen SetSpriteZPos SetStandardIconImage SetStandardPalette SetStopBits SetSubtitle SetTimeout SetTimerElapse SetTitle SetTransparentPen SetTransparentThreshold SetTrayIcon SetVarType SetVectorEngine SetVideoPosition SetVideoSize SetVideoVolume SetVolume SetWBIcon Sgn SharpenBrush Shl ShowDisplay ShowKeyboard ShowLayer ShowLayerFX ShowNotification ShowPointer ShowRinghioMessage ShowScreen ShowToast Shr Sin SolarizeBrush SolarizePalette Sort SplitStr Sqrt StartPath StartSubPath StartTimer StartsWith StopAnim StopChannel StopLayer StopModule StopMusic StopSample StopTimer StopVideo StringRequest StringToFile StripStr StrLen StrStr StrToArray Sub SwapLayers SwirlBrush SystemRequest TableItems TableToMem Tan TextExtent TextHeight TextOut TextWidth TimerElapsed TimestampToDate TintBrush TintPalette ToHostName ToIP ToNumber ToString ToUserData TransformBrush TransformLayer TranslateLayer TranslatePath TrimBrush TrimStr UndefineVirtualStringFile Undo UndoFX UnleftStr UnmidStr Unpack UnrightStr UnsetEnv UploadFile UpperStr Usage UseCarriageReturn UseFont UTCToDate Val ValidateDate ValidateStr Vibrate VWait Wait WaitAnimEnd WaitEvent WaitKeyDown WaitLeftMouse WaitMidMouse WaitPatternPosition WaitRightMouse WaitSampleEnd WaitSongPosition WaitTimer WaterRippleBrush WhileKeyDown WhileMouseDown WhileMouseOn WhileRightMouseDown Wrap WriteAnimFrame WriteBrushPixel WriteByte WriteBytes WriteChr WriteFloat WriteFunction WriteInt WriteLine WriteMem WritePen WriteRegistryKey WriteSerialData WriteShort WriteString WriteTable YieldCoroutine " user-defined constants syn match hwUserConstant "#\<\u\+\>" diff --git a/runtime/syntax/html.vim b/runtime/syntax/html.vim index 9061bdee90..605db3ae1c 100644 --- a/runtime/syntax/html.vim +++ b/runtime/syntax/html.vim @@ -3,7 +3,7 @@ " Maintainer: Doug Kearns <dougkearns@gmail.com> " Previous Maintainers: Jorge Maldonado Ventura <jorgesumle@freakspot.net> " Claudio Fleiner <claudio@fleiner.com> -" Last Change: 2022 Jul 20 +" Last Change: 2022 Nov 18 " Please check :help html.vim for some comments and a description of the options @@ -272,6 +272,16 @@ if main_syntax == "html" syn sync minlines=10 endif +" Folding +" Originally by Ingo Karkat and Marcus Zanona +if get(g:, "html_syntax_folding", 0) + syn region htmlFold start="<\z(\<\%(area\|base\|br\|col\|command\|embed\|hr\|img\|input\|keygen\|link\|meta\|param\|source\|track\|wbr\>\)\@![a-z-]\+\>\)\%(\_s*\_[^/]\?>\|\_s\_[^>]*\_[^>/]>\)" end="</\z1\_s*>" fold transparent keepend extend containedin=htmlHead,htmlH\d + " fold comments (the real ones and the old Netscape ones) + if exists("html_wrong_comments") + syn region htmlComment start=+<!--+ end=+--\s*>\%(\n\s*<!--\)\@!+ contains=@Spell fold + endif +endif + " The default highlighting. hi def link htmlTag Function hi def link htmlEndTag Identifier 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/make.vim b/runtime/syntax/make.vim index 68f7ee21ea..b4573044ca 100644 --- a/runtime/syntax/make.vim +++ b/runtime/syntax/make.vim @@ -3,7 +3,7 @@ " Maintainer: Roland Hieber <rohieb+vim-iR0jGdkV@rohieb.name>, <https://github.com/rohieb> " Previous Maintainer: Claudio Fleiner <claudio@fleiner.com> " URL: https://github.com/vim/vim/blob/master/runtime/syntax/make.vim -" Last Change: 2020 Oct 16 +" Last Change: 2022 Nov 06 " quit when a syntax file was already loaded if exists("b:current_syntax") @@ -45,11 +45,11 @@ syn match makeImplicit "^\.[A-Za-z0-9_./\t -]\+\s*:$"me=e-1 syn match makeImplicit "^\.[A-Za-z0-9_./\t -]\+\s*:[^=]"me=e-2 syn region makeTarget transparent matchgroup=makeTarget - \ start="^[~A-Za-z0-9_./$()%-][A-Za-z0-9_./\t $()%-]*&\?:\?:\{1,2}[^:=]"rs=e-1 + \ start="^[~A-Za-z0-9_./$(){}%-][A-Za-z0-9_./\t ${}()%-]*&\?:\?:\{1,2}[^:=]"rs=e-1 \ end="[^\\]$" \ keepend contains=makeIdent,makeSpecTarget,makeNextLine,makeComment,makeDString \ skipnl nextGroup=makeCommands -syn match makeTarget "^[~A-Za-z0-9_./$()%*@-][A-Za-z0-9_./\t $()%*@-]*&\?::\=\s*$" +syn match makeTarget "^[~A-Za-z0-9_./$(){}%*@-][A-Za-z0-9_./\t $(){}%*@-]*&\?::\=\s*$" \ contains=makeIdent,makeSpecTarget,makeComment \ skipnl nextgroup=makeCommands,makeCommandError diff --git a/runtime/syntax/markdown.vim b/runtime/syntax/markdown.vim index 17b61c2fa4..44187ff18c 100644 --- a/runtime/syntax/markdown.vim +++ b/runtime/syntax/markdown.vim @@ -1,8 +1,8 @@ " Vim syntax file " Language: Markdown -" Maintainer: Tim Pope <vimNOSPAM@tpope.org> +" Maintainer: Tim Pope <https://github.com/tpope/vim-markdown> " Filenames: *.markdown -" Last Change: 2020 Jan 14 +" Last Change: 2022 Oct 13 if exists("b:current_syntax") finish @@ -12,6 +12,12 @@ if !exists('main_syntax') let main_syntax = 'markdown' endif +if has('folding') + let s:foldmethod = &l:foldmethod + let s:foldtext = &l:foldtext +endif +let s:iskeyword = &l:iskeyword + runtime! syntax/html.vim unlet! b:current_syntax @@ -26,17 +32,33 @@ for s:type in map(copy(g:markdown_fenced_languages),'matchstr(v:val,"[^=]*$")') if s:type =~ '\.' let b:{matchstr(s:type,'[^.]*')}_subtype = matchstr(s:type,'\.\zs.*') endif - exe 'syn include @markdownHighlight'.substitute(s:type,'\.','','g').' syntax/'.matchstr(s:type,'[^.]*').'.vim' + syn case match + exe 'syn include @markdownHighlight_'.tr(s:type,'.','_').' syntax/'.matchstr(s:type,'[^.]*').'.vim' unlet! b:current_syntax let s:done_include[matchstr(s:type,'[^.]*')] = 1 endfor unlet! s:type unlet! s:done_include +syn spell toplevel +if exists('s:foldmethod') && s:foldmethod !=# &l:foldmethod + let &l:foldmethod = s:foldmethod + unlet s:foldmethod +endif +if exists('s:foldtext') && s:foldtext !=# &l:foldtext + let &l:foldtext = s:foldtext + unlet s:foldtext +endif +if s:iskeyword !=# &l:iskeyword + let &l:iskeyword = s:iskeyword +endif +unlet s:iskeyword + if !exists('g:markdown_minlines') let g:markdown_minlines = 50 endif execute 'syn sync minlines=' . g:markdown_minlines +syn sync linebreaks=1 syn case ignore syn match markdownValid '[<>]\c[a-z/$!]\@!' transparent contains=NONE @@ -52,16 +74,16 @@ syn match markdownH2 "^.\+\n-\+$" contained contains=@markdownInline,markdownHea syn match markdownHeadingRule "^[=-]\+$" contained -syn region markdownH1 matchgroup=markdownH1Delimiter start="##\@!" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained -syn region markdownH2 matchgroup=markdownH2Delimiter start="###\@!" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained -syn region markdownH3 matchgroup=markdownH3Delimiter start="####\@!" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained -syn region markdownH4 matchgroup=markdownH4Delimiter start="#####\@!" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained -syn region markdownH5 matchgroup=markdownH5Delimiter start="######\@!" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained -syn region markdownH6 matchgroup=markdownH6Delimiter start="#######\@!" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained +syn region markdownH1 matchgroup=markdownH1Delimiter start=" \{,3}#\s" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained +syn region markdownH2 matchgroup=markdownH2Delimiter start=" \{,3}##\s" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained +syn region markdownH3 matchgroup=markdownH3Delimiter start=" \{,3}###\s" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained +syn region markdownH4 matchgroup=markdownH4Delimiter start=" \{,3}####\s" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained +syn region markdownH5 matchgroup=markdownH5Delimiter start=" \{,3}#####\s" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained +syn region markdownH6 matchgroup=markdownH6Delimiter start=" \{,3}######\s" end="#*\s*$" keepend oneline contains=@markdownInline,markdownAutomaticLink contained syn match markdownBlockquote ">\%(\s\|$\)" contained nextgroup=@markdownBlock -syn region markdownCodeBlock start=" \|\t" end="$" contained +syn region markdownCodeBlock start="^\n\( \{4,}\|\t\)" end="^\ze \{,3}\S.*$" keepend " TODO: real nesting syn match markdownListMarker "\%(\t\| \{0,4\}\)[-*+]\%(\s\+\S\)\@=" contained @@ -79,7 +101,7 @@ syn region markdownUrlTitle matchgroup=markdownUrlTitleDelimiter start=+"+ end=+ syn region markdownUrlTitle matchgroup=markdownUrlTitleDelimiter start=+'+ end=+'+ keepend contained syn region markdownUrlTitle matchgroup=markdownUrlTitleDelimiter start=+(+ end=+)+ keepend contained -syn region markdownLinkText matchgroup=markdownLinkTextDelimiter start="!\=\[\%(\%(\_[^][]\|\[\_[^][]*\]\)*]\%( \=[[(]\)\)\@=" end="\]\%( \=[[(]\)\@=" nextgroup=markdownLink,markdownId skipwhite contains=@markdownInline,markdownLineStart +syn region markdownLinkText matchgroup=markdownLinkTextDelimiter start="!\=\[\%(\_[^][]*\%(\[\_[^][]*\]\_[^][]*\)*]\%( \=[[(]\)\)\@=" end="\]\%( \=[[(]\)\@=" nextgroup=markdownLink,markdownId skipwhite contains=@markdownInline,markdownLineStart syn region markdownLink matchgroup=markdownLinkDelimiter start="(" end=")" contains=markdownUrl keepend contained syn region markdownId matchgroup=markdownIdDelimiter start="\[" end="\]" keepend contained syn region markdownAutomaticLink matchgroup=markdownUrlDelimiter start="<\%(\w\+:\|[[:alnum:]_+-]\+@\)\@=" end=">" keepend oneline @@ -88,31 +110,38 @@ let s:concealends = '' if has('conceal') && get(g:, 'markdown_syntax_conceal', 1) == 1 let s:concealends = ' concealends' endif -exe 'syn region markdownItalic matchgroup=markdownItalicDelimiter start="\S\@<=\*\|\*\S\@=" end="\S\@<=\*\|\*\S\@=" skip="\\\*" contains=markdownLineStart,@Spell' . s:concealends -exe 'syn region markdownItalic matchgroup=markdownItalicDelimiter start="\w\@<!_\S\@=" end="\S\@<=_\w\@!" skip="\\_" contains=markdownLineStart,@Spell' . s:concealends -exe 'syn region markdownBold matchgroup=markdownBoldDelimiter start="\S\@<=\*\*\|\*\*\S\@=" end="\S\@<=\*\*\|\*\*\S\@=" skip="\\\*" contains=markdownLineStart,markdownItalic,@Spell' . s:concealends -exe 'syn region markdownBold matchgroup=markdownBoldDelimiter start="\w\@<!__\S\@=" end="\S\@<=__\w\@!" skip="\\_" contains=markdownLineStart,markdownItalic,@Spell' . s:concealends -exe 'syn region markdownBoldItalic matchgroup=markdownBoldItalicDelimiter start="\S\@<=\*\*\*\|\*\*\*\S\@=" end="\S\@<=\*\*\*\|\*\*\*\S\@=" skip="\\\*" contains=markdownLineStart,@Spell' . s:concealends -exe 'syn region markdownBoldItalic matchgroup=markdownBoldItalicDelimiter start="\w\@<!___\S\@=" end="\S\@<=___\w\@!" skip="\\_" contains=markdownLineStart,@Spell' . s:concealends +exe 'syn region markdownItalic matchgroup=markdownItalicDelimiter start="\*\S\@=" end="\S\@<=\*\|^$" skip="\\\*" contains=markdownLineStart,@Spell' . s:concealends +exe 'syn region markdownItalic matchgroup=markdownItalicDelimiter start="\w\@<!_\S\@=" end="\S\@<=_\w\@!\|^$" skip="\\_" contains=markdownLineStart,@Spell' . s:concealends +exe 'syn region markdownBold matchgroup=markdownBoldDelimiter start="\*\*\S\@=" end="\S\@<=\*\*\|^$" skip="\\\*" contains=markdownLineStart,markdownItalic,@Spell' . s:concealends +exe 'syn region markdownBold matchgroup=markdownBoldDelimiter start="\w\@<!__\S\@=" end="\S\@<=__\w\@!\|^$" skip="\\_" contains=markdownLineStart,markdownItalic,@Spell' . s:concealends +exe 'syn region markdownBoldItalic matchgroup=markdownBoldItalicDelimiter start="\*\*\*\S\@=" end="\S\@<=\*\*\*\|^$" skip="\\\*" contains=markdownLineStart,@Spell' . s:concealends +exe 'syn region markdownBoldItalic matchgroup=markdownBoldItalicDelimiter start="\w\@<!___\S\@=" end="\S\@<=___\w\@!\|^$" skip="\\_" contains=markdownLineStart,@Spell' . s:concealends +exe 'syn region markdownStrike matchgroup=markdownStrikeDelimiter start="\~\~\S\@=" end="\S\@<=\~\~\|^$" contains=markdownLineStart,@Spell' . s:concealends syn region markdownCode matchgroup=markdownCodeDelimiter start="`" end="`" keepend contains=markdownLineStart syn region markdownCode matchgroup=markdownCodeDelimiter start="`` \=" end=" \=``" keepend contains=markdownLineStart -syn region markdownCode matchgroup=markdownCodeDelimiter start="^\s*````*.*$" end="^\s*````*\ze\s*$" keepend +syn region markdownCodeBlock matchgroup=markdownCodeDelimiter start="^\s*\z(`\{3,\}\).*$" end="^\s*\z1\ze\s*$" keepend +syn region markdownCodeBlock matchgroup=markdownCodeDelimiter start="^\s*\z(\~\{3,\}\).*$" end="^\s*\z1\ze\s*$" keepend syn match markdownFootnote "\[^[^\]]\+\]" syn match markdownFootnoteDefinition "^\[^[^\]]\+\]:" -if main_syntax ==# 'markdown' - let s:done_include = {} - for s:type in g:markdown_fenced_languages - if has_key(s:done_include, matchstr(s:type,'[^.]*')) - continue - endif - exe 'syn region markdownHighlight'.substitute(matchstr(s:type,'[^=]*$'),'\..*','','').' matchgroup=markdownCodeDelimiter start="^\s*````*\s*\%({.\{-}\.\)\='.matchstr(s:type,'[^=]*').'}\=\S\@!.*$" end="^\s*````*\ze\s*$" keepend contains=@markdownHighlight'.substitute(matchstr(s:type,'[^=]*$'),'\.','','g') . s:concealends - let s:done_include[matchstr(s:type,'[^.]*')] = 1 - endfor - unlet! s:type - unlet! s:done_include +let s:done_include = {} +for s:type in g:markdown_fenced_languages + if has_key(s:done_include, matchstr(s:type,'[^.]*')) + continue + endif + exe 'syn region markdownHighlight_'.substitute(matchstr(s:type,'[^=]*$'),'\..*','','').' matchgroup=markdownCodeDelimiter start="^\s*\z(`\{3,\}\)\s*\%({.\{-}\.\)\='.matchstr(s:type,'[^=]*').'}\=\S\@!.*$" end="^\s*\z1\ze\s*$" keepend contains=@markdownHighlight_'.tr(matchstr(s:type,'[^=]*$'),'.','_') . s:concealends + exe 'syn region markdownHighlight_'.substitute(matchstr(s:type,'[^=]*$'),'\..*','','').' matchgroup=markdownCodeDelimiter start="^\s*\z(\~\{3,\}\)\s*\%({.\{-}\.\)\='.matchstr(s:type,'[^=]*').'}\=\S\@!.*$" end="^\s*\z1\ze\s*$" keepend contains=@markdownHighlight_'.tr(matchstr(s:type,'[^=]*$'),'.','_') . s:concealends + let s:done_include[matchstr(s:type,'[^.]*')] = 1 +endfor +unlet! s:type +unlet! s:done_include + +if get(b:, 'markdown_yaml_head', get(g:, 'markdown_yaml_head', main_syntax ==# 'markdown')) + syn include @markdownYamlTop syntax/yaml.vim + unlet! b:current_syntax + syn region markdownYamlHead start="\%^---$" end="^\%(---\|\.\.\.\)\s*$" keepend contains=@markdownYamlTop,@Spell endif syn match markdownEscape "\\[][\\`*_{}()<>#+.!-]" @@ -156,6 +185,8 @@ hi def link markdownBold htmlBold hi def link markdownBoldDelimiter markdownBold hi def link markdownBoldItalic htmlBoldItalic hi def link markdownBoldItalicDelimiter markdownBoldItalic +hi def link markdownStrike htmlStrike +hi def link markdownStrikeDelimiter markdownStrike hi def link markdownCodeDelimiter Delimiter hi def link markdownEscape Special diff --git a/runtime/syntax/mermaid.vim b/runtime/syntax/mermaid.vim new file mode 100644 index 0000000000..afdbcc3d62 --- /dev/null +++ b/runtime/syntax/mermaid.vim @@ -0,0 +1,155 @@ +" Vim syntax file +" Language: Mermaid +" Maintainer: Craig MacEahern <https://github.com/craigmac/vim-mermaid> +" Filenames: *.mmd +" Last Change: 2022 Nov 22 + +if exists("b:current_syntax") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +syntax iskeyword @,48-57,192-255,$,_,-,: +syntax keyword mermaidKeyword + \ _blank + \ _self + \ _parent + \ _top + \ ::icon + \ accDescr + \ accTitle + \ actor + \ activate + \ alt + \ and + \ as + \ autonumber + \ branch + \ break + \ callback + \ checkout + \ class + \ classDef + \ classDiagram + \ click + \ commit + \ commitgitGraph + \ critical + \ dataFormat + \ dateFormat + \ deactivate + \ direction + \ element + \ else + \ end + \ erDiagram + \ flowchart + \ gantt + \ gitGraph + \ graph + \ journey + \ link + \ LR + \ TD + \ TB + \ RL + \ loop + \ merge + \ mindmap root + \ Note + \ Note right of + \ Note left of + \ Note over + \ note + \ note right of + \ note left of + \ note over + \ opt + \ option + \ par + \ participant + \ pie + \ rect + \ requirement + \ rgb + \ section + \ sequenceDiagram + \ state + \ stateDiagram + \ stateDiagram-v2 + \ style + \ subgraph + \ title +highlight link mermaidKeyword Keyword + +syntax match mermaidStatement "|" +syntax match mermaidStatement "--\?[>x)]>\?+\?-\?" +syntax match mermaidStatement "\~\~\~" +syntax match mermaidStatement "--" +syntax match mermaidStatement "---" +syntax match mermaidStatement "-->" +syntax match mermaidStatement "-\." +syntax match mermaidStatement "\.->" +syntax match mermaidStatement "-\.-" +syntax match mermaidStatement "-\.\.-" +syntax match mermaidStatement "-\.\.\.-" +syntax match mermaidStatement "==" +syntax match mermaidStatement "==>" +syntax match mermaidStatement "===>" +syntax match mermaidStatement "====>" +syntax match mermaidStatement "&" +syntax match mermaidStatement "--o" +syntax match mermaidStatement "--x" +syntax match mermaidStatement "x--x" +syntax match mermaidStatement "-----" +syntax match mermaidStatement "---->" +syntax match mermaidStatement "===" +syntax match mermaidStatement "====" +syntax match mermaidStatement "=====" +syntax match mermaidStatement ":::" +syntax match mermaidStatement "<|--" +syntax match mermaidStatement "\*--" +syntax match mermaidStatement "o--" +syntax match mermaidStatement "o--o" +syntax match mermaidStatement "<--" +syntax match mermaidStatement "<-->" +syntax match mermaidStatement "\.\." +syntax match mermaidStatement "<\.\." +syntax match mermaidStatement "<|\.\." +syntax match mermaidStatement "--|>" +syntax match mermaidStatement "--\*" +syntax match mermaidStatement "--o" +syntax match mermaidStatement "\.\.>" +syntax match mermaidStatement "\.\.|>" +syntax match mermaidStatement "<|--|>" +syntax match mermaidStatement "||--o{" +highlight link mermaidStatement Statement + +syntax match mermaidIdentifier "[\+-]\?\w\+(.*)[\$\*]\?" +highlight link mermaidIdentifier Identifier + +syntax match mermaidType "[\+-\#\~]\?\cint\>" +syntax match mermaidType "[\+-\#\~]\?\cString\>" +syntax match mermaidType "[\+-\#\~]\?\cbool\>" +syntax match mermaidType "[\+-\#\~]\?\cBigDecimal\>" +syntax match mermaidType "[\+-\#\~]\?\cList\~.\+\~" +syntax match mermaidType "<<\w\+>>" +highlight link mermaidType Type + +syntax match mermaidComment "%%.*$" +highlight link mermaidComment Comment + +syntax region mermaidDirective start="%%{" end="\}%%" +highlight link mermaidDirective PreProc + +syntax region mermaidString start=/"/ skip=/\\"/ end=/"/ +highlight link mermaidString String + +let b:current_syntax = "mermaid" + +let &cpo = s:cpo_save +unlet s:cpo_save + +" vim:set sw=2: diff --git a/runtime/syntax/modula3.vim b/runtime/syntax/modula3.vim index b179303799..390a1a90ff 100644 --- a/runtime/syntax/modula3.vim +++ b/runtime/syntax/modula3.vim @@ -2,18 +2,29 @@ " Language: Modula-3 " Maintainer: Doug Kearns <dougkearns@gmail.com> " Previous Maintainer: Timo Pedersen <dat97tpe@ludat.lth.se> -" Last Change: 2021 Apr 08 +" Last Change: 2022 Oct 31 if exists("b:current_syntax") finish endif -" Modula-3 keywords -syn keyword modula3Keyword ANY ARRAY AS BITS BRANDED BY CASE CONST DEFINITION -syn keyword modula3Keyword EVAL EXIT EXCEPT EXCEPTION EXIT EXPORTS FINALLY -syn keyword modula3Keyword FROM GENERIC IMPORT LOCK METHOD OF RAISE RAISES -syn keyword modula3Keyword READONLY RECORD REF RETURN SET TRY TYPE TYPECASE -syn keyword modula3Keyword UNSAFE VALUE VAR WITH +" Whitespace errors {{{1 +if exists("modula3_space_errors") + if !exists("modula3_no_trail_space_error") + syn match modula3SpaceError display excludenl "\s\+$" + endif + if !exists("modula3_no_tab_space_error") + syn match modula3SpaceError display " \+\t"me=e-1 + endif +endif + +" Keywords {{{1 +syn keyword modula3Keyword ANY ARRAY AS BITS BRANDED BY CASE CONST +syn keyword modula3Keyword DEFINITION EVAL EXIT EXCEPT EXCEPTION EXIT +syn keyword modula3Keyword EXPORTS FINALLY FROM GENERIC IMPORT LOCK METHOD +syn keyword modula3Keyword OF RAISE RAISES READONLY RECORD REF +syn keyword modula3Keyword RETURN SET TRY TYPE TYPECASE UNSAFE +syn keyword modula3Keyword VALUE VAR WITH syn match modula3keyword "\<UNTRACED\>" @@ -22,44 +33,73 @@ syn keyword modula3Block PROCEDURE FUNCTION MODULE INTERFACE REPEAT THEN syn keyword modula3Block BEGIN END OBJECT METHODS OVERRIDES RECORD REVEAL syn keyword modula3Block WHILE UNTIL DO TO IF FOR ELSIF ELSE LOOP -" Reserved identifiers +" Reserved identifiers {{{1 syn keyword modula3Identifier ABS ADR ADRSIZE BITSIZE BYTESIZE CEILING DEC syn keyword modula3Identifier DISPOSE FIRST FLOAT FLOOR INC ISTYPE LAST syn keyword modula3Identifier LOOPHOLE MAX MIN NARROW NEW NUMBER ORD ROUND syn keyword modula3Identifier SUBARRAY TRUNC TYPECODE VAL -" Predefined types +" Predefined types {{{1 syn keyword modula3Type ADDRESS BOOLEAN CARDINAL CHAR EXTENDED INTEGER syn keyword modula3Type LONGCARD LONGINT LONGREAL MUTEX NULL REAL REFANY TEXT syn keyword modula3Type WIDECHAR syn match modula3Type "\<\%(UNTRACED\s\+\)\=ROOT\>" -" Operators -syn keyword modulaOperator DIV MOD IN AND OR NOT +" Operators {{{1 +syn keyword modula3Operator DIV MOD +syn keyword modula3Operator IN +syn keyword modula3Operator NOT AND OR +" TODO: exclude = from declarations if exists("modula3_operators") syn match modula3Operator "\^" - syn match modula3Operator "+\|-\|\*\|/\|&" - " TODO: need to exclude = in procedure definitions - syn match modula3Operator "<=\|<\|>=\|>\|:\@<!=\|#" + syn match modula3Operator "[-+/*]" + syn match modula3Operator "&" + syn match modula3Operator "<=\|<:\@!\|>=\|>" + syn match modula3Operator ":\@<!=\|#" endif +" Literals {{{1 + " Booleans syn keyword modula3Boolean TRUE FALSE " Nil syn keyword modula3Nil NIL -" Integers -syn match modula3Integer "\<\d\+L\=\>" -syn match modula3Integer "\<\d\d\=_\x\+L\=\>" +" Numbers {{{2 + +" NOTE: Negated numbers are constant expressions not literals + +syn case ignore + + " Integers + + syn match modula3Integer "\<\d\+L\=\>" -" Reals -syn match modula3Real "\c\<\d\+\.\d\+\%([EDX][+-]\=\d\+\)\=\>" + if exists("modula3_number_errors") + syn match modula3IntegerError "\<\d\d\=_\x\+L\=\>" + endif + + let s:digits = "0123456789ABCDEF" + for s:radix in range(2, 16) + " Nvim does not support interpolated strings yet. + " exe $'syn match modula3Integer "\<{s:radix}_[{s:digits[:s:radix - 1]}]\+L\=\>"' + exe 'syn match modula3Integer "\<' .. s:radix .. '_[' .. s:digits[:s:radix - 1] .. ']\+L\=\>"' + endfor + unlet s:digits s:radix + + " Reals + syn match modula3Real "\<\d\+\.\d\+\%([EDX][+-]\=\d\+\)\=\>" + +syn case match + +" Strings and characters {{{2 " String escape sequences syn match modula3Escape "\\['"ntrf]" contained display +" TODO: limit to <= 377 (255) syn match modula3Escape "\\\o\{3}" contained display syn match modula3Escape "\\\\" contained display @@ -69,13 +109,23 @@ syn match modula3Character "'\%([^']\|\\.\|\\\o\{3}\)'" contains=modula3Escape " Strings syn region modula3String start=+"+ end=+"+ contains=modula3Escape -" Pragmas +" Pragmas {{{1 +" EXTERNAL INLINE ASSERT TRACE FATAL UNUSED OBSOLETE CALLBACK EXPORTED PRAGMA NOWARN LINE LL LL.sup SPEC +" Documented: INLINE ASSERT TRACE FATAL UNUSED OBSOLETE NOWARN syn region modula3Pragma start="<\*" end="\*>" -" Comments -syn region modula3Comment start="(\*" end="\*)" contains=modula3Comment,@Spell +" Comments {{{1 +if !exists("modula3_no_comment_fold") + syn region modula3Comment start="(\*" end="\*)" contains=modula3Comment,@Spell fold + syn region modula3LineCommentBlock start="^\s*(\*.*\*)\s*\n\%(^\s*(\*.*\*)\s*$\)\@=" end="^\s*(\*.*\*)\s*\n\%(^\s*(\*.*\*)\s*$\)\@!" contains=modula3Comment transparent fold keepend +else + syn region modula3Comment start="(\*" end="\*)" contains=modula3Comment,@Spell +endif + +" Syncing "{{{1 +syn sync minlines=100 -" Default highlighting +" Default highlighting {{{1 hi def link modula3Block Statement hi def link modula3Boolean Boolean hi def link modula3Character Character @@ -85,12 +135,13 @@ hi def link modula3Identifier Keyword hi def link modula3Integer Number hi def link modula3Keyword Statement hi def link modula3Nil Constant +hi def link modula3IntegerError Error hi def link modula3Operator Operator hi def link modula3Pragma PreProc hi def link modula3Real Float hi def link modula3String String -hi def link modula3Type Type +hi def link modula3Type Type "}}} let b:current_syntax = "modula3" -" vim: nowrap sw=2 sts=2 ts=8 noet: +" vim: nowrap sw=2 sts=2 ts=8 noet fdm=marker: diff --git a/runtime/syntax/nix.vim b/runtime/syntax/nix.vim new file mode 100644 index 0000000000..c07676a4a8 --- /dev/null +++ b/runtime/syntax/nix.vim @@ -0,0 +1,210 @@ +" Vim syntax file +" Language: Nix +" Maintainer: James Fleming <james@electronic-quill.net> +" Original Author: Daiderd Jordan <daiderd@gmail.com> +" Acknowledgement: Based on vim-nix maintained by Daiderd Jordan <daiderd@gmail.com> +" https://github.com/LnL7/vim-nix +" License: MIT +" Last Change: 2022 Dec 06 + +if exists("b:current_syntax") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +syn keyword nixBoolean true false +syn keyword nixNull null +syn keyword nixRecKeyword rec + +syn keyword nixOperator or +syn match nixOperator '!=\|!' +syn match nixOperator '<=\?' +syn match nixOperator '>=\?' +syn match nixOperator '&&' +syn match nixOperator '//\=' +syn match nixOperator '==' +syn match nixOperator '?' +syn match nixOperator '||' +syn match nixOperator '++\=' +syn match nixOperator '-' +syn match nixOperator '\*' +syn match nixOperator '->' + +syn match nixParen '[()]' +syn match nixInteger '\d\+' + +syn keyword nixTodo FIXME NOTE TODO OPTIMIZE XXX HACK contained +syn match nixComment '#.*' contains=nixTodo,@Spell +syn region nixComment start=+/\*+ end=+\*/+ contains=nixTodo,@Spell + +syn region nixInterpolation matchgroup=nixInterpolationDelimiter start="\${" end="}" contained contains=@nixExpr,nixInterpolationParam + +syn match nixSimpleStringSpecial /\\\%([nrt"\\$]\|$\)/ contained +syn match nixStringSpecial /''['$]/ contained +syn match nixStringSpecial /\$\$/ contained +syn match nixStringSpecial /''\\[nrt]/ contained + +syn match nixSimpleStringSpecial /\$\$/ contained + +syn match nixInvalidSimpleStringEscape /\\[^nrt"\\$]/ contained +syn match nixInvalidStringEscape /''\\[^nrt]/ contained + +syn region nixSimpleString matchgroup=nixStringDelimiter start=+"+ skip=+\\"+ end=+"+ contains=nixInterpolation,nixSimpleStringSpecial,nixInvalidSimpleStringEscape +syn region nixString matchgroup=nixStringDelimiter start=+''+ skip=+''['$\\]+ end=+''+ contains=nixInterpolation,nixStringSpecial,nixInvalidStringEscape + +syn match nixFunctionCall "[a-zA-Z_][a-zA-Z0-9_'-]*" + +syn match nixPath "[a-zA-Z0-9._+-]*\%(/[a-zA-Z0-9._+-]\+\)\+" +syn match nixHomePath "\~\%(/[a-zA-Z0-9._+-]\+\)\+" +syn match nixSearchPath "[a-zA-Z0-9._+-]\+\%(\/[a-zA-Z0-9._+-]\+\)*" contained +syn match nixPathDelimiter "[<>]" contained +syn match nixSearchPathRef "<[a-zA-Z0-9._+-]\+\%(\/[a-zA-Z0-9._+-]\+\)*>" contains=nixSearchPath,nixPathDelimiter +syn match nixURI "[a-zA-Z][a-zA-Z0-9.+-]*:[a-zA-Z0-9%/?:@&=$,_.!~*'+-]\+" + +syn match nixAttributeDot "\." contained +syn match nixAttribute "[a-zA-Z_][a-zA-Z0-9_'-]*\ze\%([^a-zA-Z0-9_'.-]\|$\)" contained +syn region nixAttributeAssignment start="=" end="\ze;" contained contains=@nixExpr +syn region nixAttributeDefinition start=/\ze[a-zA-Z_"$]/ end=";" contained contains=nixComment,nixAttribute,nixInterpolation,nixSimpleString,nixAttributeDot,nixAttributeAssignment + +syn region nixInheritAttributeScope start="(" end="\ze)" contained contains=@nixExpr +syn region nixAttributeDefinition matchgroup=nixInherit start="\<inherit\>" end=";" contained contains=nixComment,nixInheritAttributeScope,nixAttribute + +syn region nixAttributeSet start="{" end="}" contains=nixComment,nixAttributeDefinition + +" vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv +syn region nixArgumentDefinitionWithDefault matchgroup=nixArgumentDefinition start="[a-zA-Z_][a-zA-Z0-9_'-]*\ze\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*?\@=" matchgroup=NONE end="[,}]\@=" transparent contained contains=@nixExpr +" vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv +syn match nixArgumentDefinition "[a-zA-Z_][a-zA-Z0-9_'-]*\ze\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*[,}]\@=" contained +syn match nixArgumentEllipsis "\.\.\." contained +syn match nixArgumentSeparator "," contained + +" vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv +syn match nixArgOperator '@\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*[a-zA-Z_][a-zA-Z0-9_'-]*\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*:'he=s+1 contained contains=nixAttribute + +" vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv +syn match nixArgOperator '[a-zA-Z_][a-zA-Z0-9_'-]*\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*@'hs=e-1 contains=nixAttribute nextgroup=nixFunctionArgument + +" This is a bit more complicated, because function arguments can be passed in a +" very similar form on how attribute sets are defined and two regions with the +" same start patterns will shadow each other. Instead of a region we could use a +" match on {\_.\{-\}}, which unfortunately doesn't take nesting into account. +" +" So what we do instead is that we look forward until we are sure that it's a +" function argument. Unfortunately, we need to catch comments and both vertical +" and horizontal white space, which the following regex should hopefully do: +" +" "\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*" +" +" It is also used throught the whole file and is marked with 'v's as well. +" +" Fortunately the matching rules for function arguments are much simpler than +" for real attribute sets, because we can stop when we hit the first ellipsis or +" default value operator, but we also need to paste the "whitespace & comments +" eating" regex all over the place (marked with 'v's): +" +" Region match 1: { foo ? ... } or { foo, ... } or { ... } (ellipsis) +" vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv {----- identifier -----}vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv +syn region nixFunctionArgument start="{\ze\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*\%([a-zA-Z_][a-zA-Z0-9_'-]*\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*[,?}]\|\.\.\.\)" end="}" contains=nixComment,nixArgumentDefinitionWithDefault,nixArgumentDefinition,nixArgumentEllipsis,nixArgumentSeparator nextgroup=nixArgOperator + +" Now it gets more tricky, because we need to look forward for the colon, but +" there could be something like "{}@foo:", even though it's highly unlikely. +" +" Region match 2: {} +" vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv@vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv{----- identifier -----} vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv +syn region nixFunctionArgument start="{\ze\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*}\%(\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*@\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*[a-zA-Z_][a-zA-Z0-9_'-]*\)\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*:" end="}" contains=nixComment nextgroup=nixArgOperator + +" vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv +syn match nixSimpleFunctionArgument "[a-zA-Z_][a-zA-Z0-9_'-]*\ze\%(\s\|#.\{-\}\n\|\n\|/\*\_.\{-\}\*/\)*:\([\n ]\)\@=" + +syn region nixList matchgroup=nixListBracket start="\[" end="\]" contains=@nixExpr + +syn region nixLetExpr matchgroup=nixLetExprKeyword start="\<let\>" end="\<in\>" contains=nixComment,nixAttributeDefinition + +syn keyword nixIfExprKeyword then contained +syn region nixIfExpr matchgroup=nixIfExprKeyword start="\<if\>" end="\<else\>" contains=@nixExpr,nixIfExprKeyword + +syn region nixWithExpr matchgroup=nixWithExprKeyword start="\<with\>" matchgroup=NONE end=";" contains=@nixExpr + +syn region nixAssertExpr matchgroup=nixAssertKeyword start="\<assert\>" matchgroup=NONE end=";" contains=@nixExpr + +syn cluster nixExpr contains=nixBoolean,nixNull,nixOperator,nixParen,nixInteger,nixRecKeyword,nixConditional,nixBuiltin,nixSimpleBuiltin,nixComment,nixFunctionCall,nixFunctionArgument,nixArgOperator,nixSimpleFunctionArgument,nixPath,nixHomePath,nixSearchPathRef,nixURI,nixAttributeSet,nixList,nixSimpleString,nixString,nixLetExpr,nixIfExpr,nixWithExpr,nixAssertExpr,nixInterpolation + +" These definitions override @nixExpr and have to come afterwards: + +syn match nixInterpolationParam "[a-zA-Z_][a-zA-Z0-9_'-]*\%(\.[a-zA-Z_][a-zA-Z0-9_'-]*\)*" contained + +" Non-namespaced Nix builtins as of version 2.0: +syn keyword nixSimpleBuiltin + \ abort baseNameOf derivation derivationStrict dirOf fetchGit + \ fetchMercurial fetchTarball import isNull map mapAttrs placeholder removeAttrs + \ scopedImport throw toString + + +" Namespaced and non-namespaced Nix builtins as of version 2.0: +syn keyword nixNamespacedBuiltin contained + \ abort add addErrorContext all any attrNames attrValues baseNameOf + \ catAttrs compareVersions concatLists concatStringsSep currentSystem + \ currentTime deepSeq derivation derivationStrict dirOf div elem elemAt + \ fetchGit fetchMercurial fetchTarball fetchurl filter \ filterSource + \ findFile foldl' fromJSON functionArgs genList \ genericClosure getAttr + \ getEnv hasAttr hasContext hashString head import intersectAttrs isAttrs + \ isBool isFloat isFunction isInt isList isNull isString langVersion + \ length lessThan listToAttrs map mapAttrs match mul nixPath nixVersion + \ parseDrvName partition path pathExists placeholder readDir readFile + \ removeAttrs replaceStrings scopedImport seq sort split splitVersion + \ storeDir storePath stringLength sub substring tail throw toFile toJSON + \ toPath toString toXML trace tryEval typeOf unsafeDiscardOutputDependency + \ unsafeDiscardStringContext unsafeGetAttrPos valueSize fromTOML bitAnd + \ bitOr bitXor floor ceil + +syn match nixBuiltin "builtins\.[a-zA-Z']\+"he=s+9 contains=nixComment,nixNamespacedBuiltin + +hi def link nixArgOperator Operator +hi def link nixArgumentDefinition Identifier +hi def link nixArgumentEllipsis Operator +hi def link nixAssertKeyword Keyword +hi def link nixAttribute Identifier +hi def link nixAttributeDot Operator +hi def link nixBoolean Boolean +hi def link nixBuiltin Special +hi def link nixComment Comment +hi def link nixConditional Conditional +hi def link nixHomePath Include +hi def link nixIfExprKeyword Keyword +hi def link nixInherit Keyword +hi def link nixInteger Integer +hi def link nixInterpolation Macro +hi def link nixInterpolationDelimiter Delimiter +hi def link nixInterpolationParam Macro +hi def link nixInvalidSimpleStringEscape Error +hi def link nixInvalidStringEscape Error +hi def link nixLetExprKeyword Keyword +hi def link nixNamespacedBuiltin Special +hi def link nixNull Constant +hi def link nixOperator Operator +hi def link nixPath Include +hi def link nixPathDelimiter Delimiter +hi def link nixRecKeyword Keyword +hi def link nixSearchPath Include +hi def link nixSimpleBuiltin Keyword +hi def link nixSimpleFunctionArgument Identifier +hi def link nixSimpleString String +hi def link nixSimpleStringSpecial SpecialChar +hi def link nixString String +hi def link nixStringDelimiter Delimiter +hi def link nixStringSpecial Special +hi def link nixTodo Todo +hi def link nixURI Include +hi def link nixWithExprKeyword Keyword + +" This could lead up to slow syntax highlighting for large files, but usually +" large files such as all-packages.nix are one large attribute set, so if we'd +" use sync patterns we'd have to go back to the start of the file anyway +syn sync fromstart + +let b:current_syntax = "nix" + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/nsis.vim b/runtime/syntax/nsis.vim index 3a73fe0989..49fa17abf1 100644 --- a/runtime/syntax/nsis.vim +++ b/runtime/syntax/nsis.vim @@ -3,7 +3,7 @@ " Maintainer: Ken Takata " URL: https://github.com/k-takata/vim-nsis " Previous Maintainer: Alex Jakushev <Alex.Jakushev@kemek.lt> -" Last Change: 2020-10-18 +" Last Change: 2022-11-05 " quit when a syntax file was already loaded if exists("b:current_syntax") @@ -394,9 +394,13 @@ syn keyword nsisInstruction contained CreateShortcut nextgroup=nsisCreateShortcu syn region nsisCreateShortcutOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisCreateShortcutKwd syn match nsisCreateShortcutKwd contained "/NoWorkingDir\>" +syn keyword nsisInstruction contained GetWinVer nextgroup=nsisGetWinVerOpt skipwhite +syn region nsisGetWinVerOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisGetWinVerKwd +syn keyword nsisGetWinVerKwd contained Major Minor Build ServicePack + syn keyword nsisInstruction contained GetDLLVersion GetDLLVersionLocal nextgroup=nsisGetDLLVersionOpt skipwhite -syn region nsisGetDLLVersionOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisGetDLLVersionKwd -syn match nsisGetDLLVersionKwd contained "/ProductVersion\>" +syn region nsisGetDLLVersionOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisGetDLLVersionKwd +syn match nsisGetDLLVersionKwd contained "/ProductVersion\>" syn keyword nsisInstruction contained GetFullPathName nextgroup=nsisGetFullPathNameOpt skipwhite syn region nsisGetFullPathNameOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisGetFullPathNameKwd @@ -562,10 +566,19 @@ syn match nsisSystem contained "!execute\>" syn match nsisSystem contained "!makensis\>" syn match nsisSystem contained "!packhdr\>" syn match nsisSystem contained "!finalize\>" +syn match nsisSystem contained "!uninstfinalize\>" syn match nsisSystem contained "!system\>" syn match nsisSystem contained "!tempfile\>" -syn match nsisSystem contained "!getdllversion\>" -syn match nsisSystem contained "!gettlbversion\>" + +" Add 'P' to avoid conflicts with nsisGetDLLVersionOpt. ('P' for preprocessor.) +syn match nsisSystem contained "!getdllversion\>" nextgroup=nsisPGetdllversionOpt skipwhite +syn region nsisPGetdllversionOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisPGetdllversionKwd +syn match nsisPGetdllversionKwd contained "/\%(noerrors\|packed\|productversion\)\>" + +syn match nsisSystem contained "!gettlbversion\>" nextgroup=nsisPGettlbversionOpt skipwhite +syn region nsisPGettlbversionOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisPGettlbversionKwd +syn match nsisPGettlbversionKwd contained "/\%(noerrors\|packed\)\>" + syn match nsisSystem contained "!warning\>" syn match nsisSystem contained "!pragma\>" nextgroup=nsisPragmaOpt skipwhite @@ -581,7 +594,10 @@ syn match nsisDefine contained "!define\>" nextgroup=nsisDefineOpt skipwhite syn region nsisDefineOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisDefineKwd syn match nsisDefineKwd contained "/\%(ifndef\|redef\|date\|utcdate\|file\|intfmt\|math\)\>" -syn match nsisDefine contained "!undef\>" +syn match nsisDefine contained "!undef\>" nextgroup=nsisUndefineOpt skipwhite +syn region nsisUndefineOpt contained start="" end="$" transparent keepend contains=@nsisAnyOpt,nsisUndefineKwd +syn match nsisUndefineKwd contained "/noerrors\>" + syn match nsisPreCondit contained "!ifdef\>" syn match nsisPreCondit contained "!ifndef\>" @@ -659,6 +675,7 @@ hi def link nsisWriteRegMultiStrKwd Constant hi def link nsisSetRegViewKwd Constant hi def link nsisCopyFilesKwd Constant hi def link nsisCreateShortcutKwd Constant +hi def link nsisGetWinVerKwd Constant hi def link nsisGetDLLVersionKwd Constant hi def link nsisGetFullPathNameKwd Constant hi def link nsisFileAttrib Constant @@ -696,9 +713,12 @@ hi def link nsisIncludeKwd Constant hi def link nsisAddplugindirKwd Constant hi def link nsisAppendfileKwd Constant hi def link nsisDelfileKwd Constant +hi def link nsisPGetdllversionKwd Constant +hi def link nsisPGettlbversionKwd Constant hi def link nsisPragmaKwd Constant hi def link nsisVerboseKwd Constant hi def link nsisDefineKwd Constant +hi def link nsisUndefineKwd Constant hi def link nsisIfKwd Constant hi def link nsisSearchparseKwd Constant hi def link nsisSearchreplaceKwd Constant diff --git a/runtime/syntax/obse.vim b/runtime/syntax/obse.vim new file mode 100644 index 0000000000..4ff04281f3 --- /dev/null +++ b/runtime/syntax/obse.vim @@ -0,0 +1,3360 @@ +" Vim syntax file +" Language: Oblivion Language (obl) +" Original Creator: Ulthar Seramis +" Maintainer: Kat <katisntgood@gmail.com> +" Latest Revision: 13 November 2022 + +if exists("b:current_syntax") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +" obse is case insensitive +syntax case ignore + +" Statements {{{ +syn keyword obseStatement set let to skipwhite +" the second part needs to be separate as to not mess up the next group +syn match obseStatementTwo ":=" +" }}} + +" Regex matched objects {{{ +" these are matched with regex and thus must be set first +syn match obseNames '\w\+' +syn match obseScriptNameRegion '\i\+' contained +syn match obseVariable '\w*\S' contained +syn match obseReference '\zs\w\+\>\ze\.' +" }}} + +" Operators {{{ +syn match obseOperator "\v\*" +syn match obseOperator "\v\-" +syn match obseOperator "\v\+" +syn match obseOperator "\v\/" +syn match obseOperator "\v\^" +syn match obseOperator "\v\=" +syn match obseOperator "\v\>" +syn match obseOperator "\v\<" +syn match obseOperator "\v\!" +syn match obseOperator "\v\&" +syn match obseOperator "\v\|" +" }}} + +" Numbers {{{ +syn match obseInt '\d\+' +syn match obseInt '[-+]\d\+' +syn match obseFloat '\d\+\.\d*' +syn match obseFloat '[-+]\d\+\.\d*' +" }}} + +" Comments and strings {{{ +syn region obseComment start=";" end="$" keepend fold contains=obseToDo +syn region obseString start=/"/ end=/"/ keepend fold contains=obseStringFormatting +syn match obseStringFormatting "%%" contained +syn match obseStringFormatting "%a" contained +syn match obseStringFormatting "%B" contained +syn match obseStringFormatting "%b" contained +syn match obseStringFormatting "%c" contained +syn match obseStringFormatting "%e" contained +syn match obseStringFormatting "%g" contained +syn match obseStringFormatting "%i" contained +syn match obseStringFormatting "%k" contained +syn match obseStringFormatting "%n" contained +syn match obseStringFormatting "%p" contained +syn match obseStringFormatting "%ps" contained +syn match obseStringFormatting "%pp" contained +syn match obseStringFormatting "%po" contained +syn match obseStringFormatting "%q" contained +syn match obseStringFormatting "%r" contained +syn match obseStringFormatting "%v" contained +syn match obseStringFormatting "%x" contained +syn match obseStringFormatting "%z" contained +syn match obseStringFormatting "%{" contained +syn match obseStringFormatting "%}" contained +syn match obseStringFormatting "%\d*.\d*f" contained +syn match obseStringFormatting "% \d*.\d*f" contained +syn match obseStringFormatting "%-\d*.\d*f" contained +syn match obseStringFormatting "%+\d*.\d*f" contained +syn match obseStringFormatting "%\d*.\d*e" contained +syn match obseStringFormatting "%-\d*.\d*e" contained +syn match obseStringFormatting "% \d*.\d*e" contained +syn match obseStringFormatting "%+\d*.\d*e" contained +syn keyword obseToDo contained TODO todo Todo ToDo FIXME fixme NOTE note +" }}} + + +" Conditionals {{{ +syn match obseCondition "If" +syn match obseCondition "Eval" +syn match obseCondition "Return" +syn match obseCondition "EndIf" +syn match obseCondition "ElseIf" +syn match obseCondition "Else" +" }}} + +" Repeat loops {{{ +syn match obseRepeat "Label" +syn match obseRepeat "GoTo" +syn match obseRepeat "While" +syn match obseRepeat "Loop" +syn match obseRepeat "ForEach" +syn match obseRepeat "Break" +syn match obseRepeat "Continue" +" }}} + +" Basic Types {{{ +syn keyword obseTypes array_var float int long ref reference short string_var nextgroup=obseNames skipwhite +syn keyword obseOtherKey Player player playerRef playerREF PlayerRef PlayerREF +syn keyword obseScriptName ScriptName scriptname Scriptname scn nextgroup=obseScriptNameRegion skipwhite +syn keyword obseBlock Begin End +" }}} + +" Fold {{{ +setlocal foldmethod=syntax +syn cluster obseNoFold contains=obseComment,obseString +syn region obseFoldIfContainer + \ start="^\s*\<if\>" + \ end="^\s*\<endif\>" + \ keepend extend + \ containedin=ALLBUT,@obseNoFold + \ contains=ALLBUT,obseScriptName,obseScriptNameRegion +syn region obseFoldIf + \ start="^\s*\<if\>" + \ end="^\s*\<endif\>" + \ fold + \ keepend + \ contained containedin=obseFoldIfContainer + \ nextgroup=obseFoldElseIf,obseFoldElse + \ contains=TOP,NONE +syn region obseFoldElseIf + \ start="^\s*\<elseif\>" + \ end="^\s*\<endif\>" + \ fold + \ keepend + \ contained containedin=obseFoldIfContainer + \ nextgroup=obseFoldElseIf,obseFoldElse + \ contains=TOP +syn region obseFoldElse + \ start="^\s*\<else\>" + \ end="^\s*\<endif\>" + \ fold + \ keepend + \ contained containedin=obseFoldIfContainer + \ contains=TOP +syn region obseFoldWhile + \ start="^\s*\<while\>" + \ end="^\s*\<loop\>" + \ fold + \ keepend extend + \ contains=TOP + \ containedin=ALLBUT,@obseNoFold +" fold for loops +syn region obseFoldFor + \ start="^\s*\<foreach\>" + \ end="^\s*\<loop\>" + \ fold + \ keepend extend + \ contains=TOP + \ containedin=ALLBUT,@obseNoFold + \ nextgroup=obseVariable +" }}} + +" Skills and Attributes {{{ +syn keyword skillAttribute + \ Strength + \ Willpower + \ Speed + \ Personality + \ Intelligence + \ Agility + \ Endurance + \ Luck + \ Armorer + \ Athletics + \ Blade + \ Block + \ Blunt + \ HandToHand + \ HeavyArmor + \ Alchemy + \ Alteration + \ Conjuration + \ Destruction + \ Illusion + \ Mysticism + \ Restoration + \ Acrobatics + \ LightArmor + \ Marksman + \ Mercantile + \ Security + \ Sneak + \ Speechcraft +" }}} + +" Block Types {{{ +syn keyword obseBlockType + \ ExitGame + \ ExitToMainMenu + \ Function + \ GameMode + \ LoadGame + \ MenuMode + \ OnActivate + \ OnActorDrop + \ OnActorEquip + \ OnActorUnequip + \ OnAdd + \ OnAlarm + \ OnAlarmTrespass + \ OnAlarmVictim + \ OnAttack + \ OnBlock + \ OnBowAttack + \ OnClick + \ OnClose + \ OnCreatePotion + \ OnCreateSpell + \ OnDeath + \ OnDodge + \ OnDrinkPotion + \ OnDrop + \ OnEatIngredient + \ OnEnchant + \ OnEquip + \ OnFallImpact + \ OnHealthDamage + \ OnHit + \ OnHitWith + \ OnKnockout + \ OnLoad + \ OnMagicApply + \ OnMagicCast + \ OnMagicEffectHit + \ OnMagicEffectHit2 + \ OnMapMarkerAdd + \ OnMouseover + \ OnMurder + \ OnNewGame + \ OnOpen + \ OnPackageChange + \ OnPackageDone + \ OnPackageStart + \ OnQuestComplete + \ OnRecoil + \ OnRelease + \ OnReset + \ OnSaveIni + \ OnScriptedSkillUp + \ OnScrollCast + \ OnSell + \ OnSkillUp + \ OnSoulTrap + \ OnSpellCast + \ OnStagger + \ OnStartCombat + \ OnTrigger + \ OnTriggerActor + \ OnTriggerMob + \ OnUnequip + \ OnVampireFeed + \ OnWaterDive + \ OnWaterSurface + \ PostLoadGame + \ QQQ + \ SaveGame + \ ScriptEffectFinish + \ ScriptEffectStart + \ ScriptEffectUpdate +" }}} + +" Functions {{{ +" CS functions {{{ +syn keyword csFunction + \ Activate + \ AddAchievement + \ AddFlames + \ AddItem + \ AddScriptPackage + \ AddSpell + \ AddTopic + \ AdvSkill + \ AdvancePCLevel + \ AdvancePCSkill + \ Autosave + \ CanHaveFlames + \ CanPayCrimeGold + \ Cast + \ ClearOwnership + \ CloseCurrentOblivionGate + \ CloseOblivionGate + \ CompleteQuest + \ CreateFullActorCopy + \ DeleteFullActorCopy + \ Disable + \ DisableLinkedPathPoints + \ DisablePlayerControls + \ Dispel + \ DispelAllSpells + \ Drop + \ DropMe + \ DuplicateAllItems + \ DuplicateNPCStats + \ Enable + \ EnableFastTravel + \ EnableLinkedPathPoints + \ EnablePlayerControls + \ EquipItem + \ EssentialDeathReload + \ EvaluatePackage + \ ForceAV + \ ForceActorValue + \ ForceCloseOblivionGate + \ ForceFlee + \ ForceTakeCover + \ ForceWeather + \ GetAV + \ GetActionRef + \ GetActorValue + \ GetAlarmed + \ GetAmountSoldStolen + \ GetAngle + \ GetArmorRating + \ GetArmorRatingUpperBody + \ GetAttacked + \ GetBarterGold + \ GetBaseAV + \ GetBaseActorValue + \ GetButtonPressed + \ GetClassDefaultMatch + \ GetClothingValue + \ GetContainer + \ GetCrime + \ GetCrimeGold + \ GetCrimeKnown + \ GetCurrentAIPackage + \ GetCurrentAIProcedure + \ GetCurrentTime + \ GetCurrentWeatherPercent + \ GetDayOfWeek + \ GetDead + \ GetDeadCount + \ GetDestroyed + \ GetDetected + \ GetDetectionLevel + \ GetDisabled + \ GetDisposition + \ GetDistance + \ GetDoorDefaultOpen + \ GetEquipped + \ GetFactionRank + \ GetFactionRankDifference + \ GetFactionReaction + \ GetFatiguePercentage + \ GetForceRun + \ GetForceSneak + \ GetFriendHit + \ GetFurnitureMarkerID + \ GetGS + \ GetGameSetting + \ GetGlobalValue + \ GetGold + \ GetHeadingAngle + \ GetIdleDoneOnce + \ GetIgnoreFriendlyHits + \ GetInCell + \ GetInCellParam + \ GetInFaction + \ GetInSameCell + \ GetInWorldspace + \ GetInvestmentGold + \ GetIsAlerted + \ GetIsClass + \ GetIsClassDefault + \ GetIsCreature + \ GetIsCurrentPackage + \ GetIsCurrentWeather + \ GetIsGhost + \ GetIsID + \ GetIsPlayableRace + \ GetIsPlayerBirthsign + \ GetIsRace + \ GetIsReference + \ GetIsSex + \ GetIsUsedItem + \ GetIsUsedItemType + \ GetItemCount + \ GetKnockedState + \ GetLOS + \ GetLevel + \ GetLockLevel + \ GetLocked + \ GetMenuHasTrait + \ GetName + \ GetNoRumors + \ GetOffersServicesNow + \ GetOpenState + \ GetPCExpelled + \ GetPCFactionAttack + \ GetPCFactionMurder + \ GetPCFactionSteal + \ GetPCFactionSubmitAuthority + \ GetPCFame + \ GetPCInFaction + \ GetPCInfamy + \ GetPCIsClass + \ GetPCIsRace + \ GetPCIsSex + \ GetPCMiscStat + \ GetPCSleepHours + \ GetPackageTarget + \ GetParentRef + \ GetPersuasionNumber + \ GetPlayerControlsDisabled + \ GetPlayerHasLastRiddenHorse + \ GetPlayerInSEWorld + \ GetPos + \ GetQuestRunning + \ GetQuestVariable + \ GetRandomPercent + \ GetRestrained + \ GetScale + \ GetScriptVariable + \ GetSecondsPassed + \ GetSelf + \ GetShouldAttack + \ GetSitting + \ GetSleeping + \ GetStage + \ GetStageDone + \ GetStartingAngle + \ GetStartingPos + \ GetTalkedToPC + \ GetTalkedToPCParam + \ GetTimeDead + \ GetTotalPersuasionNumber + \ GetTrespassWarningLevel + \ GetUnconscious + \ GetUsedItemActivate + \ GetUsedItemLevel + \ GetVampire + \ GetWalkSpeed + \ GetWeaponAnimType + \ GetWeaponSkillType + \ GetWindSpeed + \ GoToJail + \ HasFlames + \ HasMagicEffect + \ HasVampireFed + \ IsActionRef + \ IsActor + \ IsActorAVictim + \ IsActorDetected + \ IsActorEvil + \ IsActorUsingATorch + \ IsActorsAIOff + \ IsAnimPlayer + \ IsCellOwner + \ IsCloudy + \ IsContinuingPackagePCNear + \ IsCurrentFurnitureObj + \ IsCurrentFurnitureRef + \ IsEssential + \ IsFacingUp + \ IsGuard + \ IsHorseStolen + \ IsIdlePlaying + \ IsInCombat + \ IsInDangerousWater + \ IsInInterior + \ IsInMyOwnedCell + \ IsLeftUp + \ IsOwner + \ IsPCAMurderer + \ IsPCSleeping + \ IsPlayerInJail + \ IsPlayerMovingIntoNewSpace + \ IsPlayersLastRiddenHorse + \ IsPleasant + \ IsRaining + \ IsRidingHorse + \ IsRunning + \ IsShieldOut + \ IsSneaking + \ IsSnowing + \ IsSpellTarget + \ IsSwimming + \ IsTalking + \ IsTimePassing + \ IsTorchOut + \ IsTrespassing + \ IsTurnArrest + \ IsWaiting + \ IsWeaponOut + \ IsXBox + \ IsYielding + \ Kill + \ KillActor + \ KillAllActors + \ Lock + \ Look + \ LoopGroup + \ Message + \ MessageBox + \ ModAV + \ ModActorValue + \ ModAmountSoldStolen + \ ModBarterGold + \ ModCrimeGold + \ ModDisposition + \ ModFactionRank + \ ModFactionReaction + \ ModPCAttribute + \ ModPCA + \ ModPCFame + \ ModPCInfamy + \ ModPCMiscStat + \ ModPCSkill + \ ModPCS + \ ModScale + \ MoveTo + \ MoveToMarker + \ PCB + \ PayFine + \ PayFineThief + \ PickIdle + \ PlaceAtMe + \ PlayBink + \ PlayGroup + \ PlayMagicEffectVisuals + \ PlayMagicShaderVisuals + \ PlaySound + \ PlaySound3D + \ PositionCell + \ PositionWorld + \ PreloadMagicEffect + \ PurgeCellBuffers + \ PushActorAway + \ RefreshTopicList + \ ReleaseWeatherOverride + \ RemoveAllItems + \ RemoveFlames + \ RemoveItem + \ RemoveMe + \ RemoveScriptPackage + \ RemoveSpell + \ Reset3DState + \ ResetFallDamageTimer + \ ResetHealth + \ ResetInterior + \ Resurrect + \ Rotate + \ SCAOnActor + \ SameFaction + \ SameFactionAsPC + \ SameRace + \ SameRaceAsPC + \ SameSex + \ SameSexAsPC + \ Say + \ SayTo + \ ScriptEffectElapsedSeconds + \ SelectPlayerSpell + \ SendTrespassAlarm + \ SetAV + \ SetActorAlpha + \ SetActorFullName + \ SetActorRefraction + \ SetActorValue + \ SetActorsAI + \ SetAlert + \ SetAllReachable + \ SetAllVisible + \ SetAngle + \ SetAtStart + \ SetBarterGold + \ SetCellFullName + \ SetCellOwnership + \ SetCellPublicFlag + \ SetClass + \ SetCrimeGold + \ SetDestroyed + \ SetDoorDefaultOpen + \ SetEssential + \ SetFactionRank + \ SetFactionReaction + \ SetForceRun + \ SetForceSneak + \ SetGhost + \ SetIgnoreFriendlyHits + \ SetInCharGen + \ SetInvestmentGold + \ SetItemValue + \ SetLevel + \ SetNoAvoidance + \ SetNoRumors + \ SetOpenState + \ SetOwnership + \ SetPCExpelled + \ SetPCFactionAttack + \ SetPCFactionMurder + \ SetPCFactionSteal + \ SetPCFactionSubmitAuthority + \ SetPCFame + \ SetPCInfamy + \ SetPCSleepHours + \ SetPackDuration + \ SetPlayerBirthsign + \ SetPlayerInSEWorld + \ SetPos + \ SetQuestObject + \ SetRestrained + \ SetRigidBodyMass + \ SetScale + \ SetSceneIsComplex + \ SetShowQuestItems + \ SetSize + \ SetStage + \ SetUnconscious + \ SetWeather + \ ShowBirthsignMenu + \ ShowClassMenu + \ ShowDialogSubtitles + \ ShowEnchantment + \ ShowMap + \ ShowRaceMenu + \ ShowSpellMaking + \ SkipAnim + \ StartCombat + \ StartConversation + \ StartQuest + \ StopCombat + \ StopCombatAlarmOnActor + \ StopLook + \ StopMagicEffectVisuals + \ StopMagicShaderVisuals + \ StopQuest + \ StopWaiting + \ StreamMusic + \ This + \ ToggleActorsAI + \ TrapUpdate + \ TriggerHitShader + \ UnequipItem + \ Unlock + \ VampireFeed + \ Wait + \ WakeUpPC + \ WhichServiceMenu + \ Yield + \ evp + \ pms + \ saa + \ sms +" }}} + +" OBSE Functions {{{ +syn keyword obseFunction + \ abs + \ acos + \ activate2 + \ actorvaluetocode + \ actorvaluetostring + \ actorvaluetostringc + \ addeffectitem + \ addeffectitemc + \ addfulleffectitem + \ addfulleffectitemc + \ additemns + \ addmagiceffectcounter + \ addmagiceffectcounterc + \ addmecounter + \ addmecounterc + \ addspellns + \ addtoleveledlist + \ ahammerkey + \ animpathincludes + \ appendtoname + \ asciitochar + \ asin + \ atan + \ atan2 + \ avstring + \ calcleveleditem + \ calclevitemnr + \ calclevitems + \ cancastpower + \ cancorpsecheck + \ canfasttravelfromworld + \ cantraveltomapmarker + \ ceil + \ chartoascii + \ clearactivequest + \ clearhotkey + \ clearleveledlist + \ clearownershipt + \ clearplayerslastriddenhorse + \ clickmenubutton + \ cloneform + \ closeallmenus + \ closetextinput + \ colvec + \ comparefemalebipedpath + \ comparefemalegroundpath + \ comparefemaleiconpath + \ compareiconpath + \ comparemalebipedpath + \ comparemalegroundpath + \ comparemaleiconpath + \ comparemodelpath + \ comparename + \ comparenames + \ comparescripts + \ con_cal + \ con_getinisetting + \ con_hairtint + \ con_loadgame + \ con_modwatershader + \ con_playerspellbook + \ con_quitgame + \ con_refreshini + \ con_runmemorypass + \ con_save + \ con_saveini + \ con_setcamerafov + \ con_setclipdist + \ con_setfog + \ con_setgamesetting + \ con_setgamma + \ con_sethdrparam + \ con_setimagespaceglow + \ con_setinisetting + \ con_setskyparam + \ con_settargetrefraction + \ con_settargetrefractionfire + \ con_sexchange + \ con_tcl + \ con_tfc + \ con_tgm + \ con_toggleai + \ con_togglecombatai + \ con_toggledetection + \ con_togglemapmarkers + \ con_togglemenus + \ con_waterdeepcolor + \ con_waterreflectioncolor + \ con_watershallowcolor + \ copyalleffectitems + \ copyeyes + \ copyfemalebipedpath + \ copyfemalegroundpath + \ copyfemaleiconpath + \ copyhair + \ copyiconpath + \ copyir + \ copymalebipedpath + \ copymalegroundpath + \ copymaleiconpath + \ copymodelpath + \ copyname + \ copyntheffectitem + \ copyrace + \ cos + \ cosh + \ createtempref + \ creaturehasnohead + \ creaturehasnoleftarm + \ creaturehasnomovement + \ creaturehasnorightarm + \ creaturenocombatinwater + \ creatureusesweaponandshield + \ dacos + \ dasin + \ datan + \ datan2 + \ dcos + \ dcosh + \ debugprint + \ deletefrominputtext + \ deletereference + \ disablecontrol + \ disablekey + \ disablemouse + \ dispatchevent + \ dispelnthactiveeffect + \ dispelnthae + \ dsin + \ dsinh + \ dtan + \ dtanh + \ enablecontrol + \ enablekey + \ enablemouse + \ equipitem2 + \ equipitem2ns + \ equipitemns + \ equipitemsilent + \ equipme + \ eval + \ evaluatepackage + \ eventhandlerexist + \ exp + \ factionhasspecialcombat + \ fileexists + \ floor + \ fmod + \ forcecolumnvector + \ forcerowvector + \ generateidentitymatrix + \ generaterotationmatrix + \ generatezeromatrix + \ getactiveeffectcasters + \ getactiveeffectcodes + \ getactiveeffectcount + \ getactivemenucomponentid + \ getactivemenufilter + \ getactivemenumode + \ getactivemenuobject + \ getactivemenuref + \ getactivemenuselection + \ getactivequest + \ getactiveuicomponentfullname + \ getactiveuicomponentid + \ getactiveuicomponentname + \ getactoralpha + \ getactorbaselevel + \ getactorlightamount + \ getactormaxlevel + \ getactormaxswimbreath + \ getactorminlevel + \ getactorpackages + \ getactorsoullevel + \ getactorvaluec + \ getalchmenuapparatus + \ getalchmenuingredient + \ getalchmenuingredientcount + \ getallies + \ getallmodlocaldata + \ getaltcontrol2 + \ getapbowench + \ getapench + \ getapparatustype + \ getappoison + \ getarmorar + \ getarmortype + \ getarrayvariable + \ getarrowprojectilebowenchantment + \ getarrowprojectileenchantment + \ getarrowprojectilepoison + \ getattackdamage + \ getavc + \ getavforbaseactor + \ getavforbaseactorc + \ getavmod + \ getavmodc + \ getavskillmastery + \ getavskillmasteryc + \ getbarteritem + \ getbarteritemquantity + \ getbaseactorvaluec + \ getbaseav2 + \ getbaseav2c + \ getbaseav3 + \ getbaseav3c + \ getbaseitems + \ getbaseobject + \ getbipediconpath + \ getbipedmodelpath + \ getbipedslotmask + \ getbirthsignspells + \ getbookcantbetaken + \ getbookisscroll + \ getbooklength + \ getbookskilltaught + \ getbooktext + \ getboundingbox + \ getboundingradius + \ getcalcalllevels + \ getcalceachincount + \ getcallingscript + \ getcellbehavesasexterior + \ getcellchanged + \ getcellclimate + \ getcelldetachtime + \ getcellfactionrank + \ getcelllighting + \ getcellmusictype + \ getcellnorthrotation + \ getcellresethours + \ getcellwatertype + \ getchancenone + \ getclass + \ getclassattribute + \ getclassmenuhighlightedclass + \ getclassmenuselectedclass + \ getclassskill + \ getclassskills + \ getclassspecialization + \ getclimatehasmasser + \ getclimatehassecunda + \ getclimatemoonphaselength + \ getclimatesunrisebegin + \ getclimatesunriseend + \ getclimatesunsetbegin + \ getclimatesunsetend + \ getclimatevolatility + \ getclosesound + \ getcloudspeedlower + \ getcloudspeedupper + \ getcombatspells + \ getcombatstyle + \ getcombatstyleacrobaticsdodgechance + \ getcombatstyleattackchance + \ getcombatstyleattackduringblockmult + \ getcombatstyleattacknotunderattackmult + \ getcombatstyleattackskillmodbase + \ getcombatstyleattackskillmodmult + \ getcombatstyleattackunderattackmult + \ getcombatstyleblockchance + \ getcombatstyleblocknotunderattackmult + \ getcombatstyleblockskillmodbase + \ getcombatstyleblockskillmodmult + \ getcombatstyleblockunderattackmult + \ getcombatstylebuffstandoffdist + \ getcombatstyledodgebacknotunderattackmult + \ getcombatstyledodgebacktimermax + \ getcombatstyledodgebacktimermin + \ getcombatstyledodgebackunderattackmult + \ getcombatstyledodgechance + \ getcombatstyledodgefatiguemodbase + \ getcombatstyledodgefatiguemodmult + \ getcombatstyledodgefwattackingmult + \ getcombatstyledodgefwnotattackingmult + \ getcombatstyledodgefwtimermax + \ getcombatstyledodgefwtimermin + \ getcombatstyledodgelrchance + \ getcombatstyledodgelrtimermax + \ getcombatstyledodgelrtimermin + \ getcombatstyledodgenotunderattackmult + \ getcombatstyledodgeunderattackmult + \ getcombatstyleencumberedspeedmodbase + \ getcombatstyleencumberedspeedmodmult + \ getcombatstylefleeingdisabled + \ getcombatstylegroupstandoffdist + \ getcombatstyleh2hbonustoattack + \ getcombatstyleholdtimermax + \ getcombatstyleholdtimermin + \ getcombatstyleidletimermax + \ getcombatstyleidletimermin + \ getcombatstyleignorealliesinarea + \ getcombatstylekobonustoattack + \ getcombatstylekobonustopowerattack + \ getcombatstylemeleealertok + \ getcombatstylepowerattackchance + \ getcombatstylepowerattackfatiguemodbase + \ getcombatstylepowerattackfatiguemodmult + \ getcombatstyleprefersranged + \ getcombatstylerangedstandoffdist + \ getcombatstylerangemaxmult + \ getcombatstylerangeoptimalmult + \ getcombatstylerejectsyields + \ getcombatstylerushattackchance + \ getcombatstylerushattackdistmult + \ getcombatstylestaggerbonustoattack + \ getcombatstylestaggerbonustopowerattack + \ getcombatstyleswitchdistmelee + \ getcombatstyleswitchdistranged + \ getcombatstylewillyield + \ getcombattarget + \ getcompletedquests + \ getcontainermenuview + \ getcontainerrespawns + \ getcontrol + \ getcreaturebasescale + \ getcreaturecombatskill + \ getcreatureflies + \ getcreaturemagicskill + \ getcreaturemodelpaths + \ getcreaturereach + \ getcreaturesoullevel + \ getcreaturesound + \ getcreaturesoundbase + \ getcreaturestealthskill + \ getcreatureswims + \ getcreaturetype + \ getcreaturewalks + \ getcrosshairref + \ getcurrentcharge + \ getcurrentclimateid + \ getcurrenteditorpackage + \ getcurrenteventname + \ getcurrenthealth + \ getcurrentpackage + \ getcurrentpackageprocedure + \ getcurrentquests + \ getcurrentregion + \ getcurrentregions + \ getcurrentscript + \ getcurrentsoullevel + \ getcurrentweatherid + \ getcursorpos + \ getdebugselection + \ getdescription + \ getdoorteleportrot + \ getdoorteleportx + \ getdoorteleporty + \ getdoorteleportz + \ geteditorid + \ geteditorsize + \ getenchantment + \ getenchantmentcharge + \ getenchantmentcost + \ getenchantmenttype + \ getenchmenubaseitem + \ getenchmenuenchitem + \ getenchmenusoulgem + \ getequipmentslot + \ getequipmentslotmask + \ getequippedcurrentcharge + \ getequippedcurrenthealth + \ getequippeditems + \ getequippedobject + \ getequippedtorchtimeleft + \ getequippedweaponpoison + \ geteyes + \ getfactions + \ getfalltimer + \ getfirstref + \ getfirstrefincell + \ getfogdayfar + \ getfogdaynear + \ getfognightfar + \ getfognightnear + \ getfollowers + \ getformfrommod + \ getformidstring + \ getfps + \ getfullgoldvalue + \ getgamedifficulty + \ getgameloaded + \ getgamerestarted + \ getgodmode + \ getgoldvalue + \ getgridstoload + \ getgroundsurfacematerial + \ gethair + \ gethaircolor + \ gethdrvalue + \ gethidesamulet + \ gethidesrings + \ gethighactors + \ gethorse + \ gethotkeyitem + \ geticonpath + \ getignoresresistance + \ getingredient + \ getingredientchance + \ getinputtext + \ getinventoryobject + \ getinvrefsforitem + \ getitems + \ getkeyname + \ getkeypress + \ getlastcreatedpotion + \ getlastcreatedspell + \ getlastenchanteditem + \ getlastsigilstonecreateditem + \ getlastsigilstoneenchanteditem + \ getlastss + \ getlastsscreated + \ getlastssitem + \ getlasttransactionitem + \ getlasttransactionquantity + \ getlastuniquecreatedpotion + \ getlastusedsigilstone + \ getlevcreaturetemplate + \ getleveledspells + \ getlevitembylevel + \ getlevitemindexbyform + \ getlevitemindexbylevel + \ getlightduration + \ getlightningfrequency + \ getlightradius + \ getlightrgb + \ getlinkeddoor + \ getloadedtypearray + \ getlocalgravity + \ getloopsound + \ getlowactors + \ getluckmodifiedskill + \ getmagiceffectareasound + \ getmagiceffectareasoundc + \ getmagiceffectbarterfactor + \ getmagiceffectbarterfactorc + \ getmagiceffectbasecost + \ getmagiceffectbasecostc + \ getmagiceffectboltsound + \ getmagiceffectboltsoundc + \ getmagiceffectcastingsound + \ getmagiceffectcastingsoundc + \ getmagiceffectchars + \ getmagiceffectcharsc + \ getmagiceffectcode + \ getmagiceffectcounters + \ getmagiceffectcountersc + \ getmagiceffectenchantfactor + \ getmagiceffectenchantfactorc + \ getmagiceffectenchantshader + \ getmagiceffectenchantshaderc + \ getmagiceffecthitshader + \ getmagiceffecthitshaderc + \ getmagiceffecthitsound + \ getmagiceffecthitsoundc + \ getmagiceffecticon + \ getmagiceffecticonc + \ getmagiceffectlight + \ getmagiceffectlightc + \ getmagiceffectmodel + \ getmagiceffectmodelc + \ getmagiceffectname + \ getmagiceffectnamec + \ getmagiceffectnumcounters + \ getmagiceffectnumcountersc + \ getmagiceffectotheractorvalue + \ getmagiceffectotheractorvaluec + \ getmagiceffectprojectilespeed + \ getmagiceffectprojectilespeedc + \ getmagiceffectresistvalue + \ getmagiceffectresistvaluec + \ getmagiceffectschool + \ getmagiceffectschoolc + \ getmagiceffectusedobject + \ getmagiceffectusedobjectc + \ getmagicitemeffectcount + \ getmagicitemtype + \ getmagicprojectilespell + \ getmapmarkers + \ getmapmarkertype + \ getmapmenumarkername + \ getmapmenumarkerref + \ getmaxav + \ getmaxavc + \ getmaxlevel + \ getmeareasound + \ getmeareasoundc + \ getmebarterc + \ getmebasecost + \ getmebasecostc + \ getmeboltsound + \ getmeboltsoundc + \ getmecastingsound + \ getmecastingsoundc + \ getmecounters + \ getmecountersc + \ getmeebarter + \ getmeebarterc + \ getmeenchant + \ getmeenchantc + \ getmeenchantshader + \ getmeenchantshaderc + \ getmehitshader + \ getmehitshaderc + \ getmehitsound + \ getmehitsoundc + \ getmeicon + \ getmeiconc + \ getmelight + \ getmelightc + \ getmemodel + \ getmemodelc + \ getmename + \ getmenamec + \ getmenufloatvalue + \ getmenumcounters + \ getmenumcountersc + \ getmenustringvalue + \ getmeotheractorvalue + \ getmeotheractorvaluec + \ getmeprojspeed + \ getmeprojspeedc + \ getmerchantcontainer + \ getmeresistvalue + \ getmeresistvaluec + \ getmeschool + \ getmeschoolc + \ getmessageboxtype + \ getmeusedobject + \ getmeusedobjectc + \ getmiddlehighactors + \ getmieffectcount + \ getminlevel + \ getmitype + \ getmodelpath + \ getmodindex + \ getmodlocaldata + \ getmousebuttonpress + \ getmousebuttonsswapped + \ getmpspell + \ getnextref + \ getnthacitveeffectmagnitude + \ getnthactiveeffectactorvalue + \ getnthactiveeffectbounditem + \ getnthactiveeffectcaster + \ getnthactiveeffectcode + \ getnthactiveeffectdata + \ getnthactiveeffectduration + \ getnthactiveeffectenchantobject + \ getnthactiveeffectmagicenchantobject + \ getnthactiveeffectmagicitem + \ getnthactiveeffectmagicitemindex + \ getnthactiveeffectmagnitude + \ getnthactiveeffectsummonref + \ getnthactiveeffecttimeelapsed + \ getnthaeav + \ getnthaebounditem + \ getnthaecaster + \ getnthaecode + \ getnthaedata + \ getnthaeduration + \ getnthaeindex + \ getnthaemagicenchantobject + \ getnthaemagicitem + \ getnthaemagnitude + \ getnthaesummonref + \ getnthaetime + \ getnthchildref + \ getnthdetectedactor + \ getntheffectitem + \ getntheffectitemactorvalue + \ getntheffectitemarea + \ getntheffectitemcode + \ getntheffectitemduration + \ getntheffectitemmagnitude + \ getntheffectitemname + \ getntheffectitemrange + \ getntheffectitemscript + \ getntheffectitemscriptname + \ getntheffectitemscriptschool + \ getntheffectitemscriptvisualeffect + \ getntheiarea + \ getntheiav + \ getntheicode + \ getntheiduration + \ getntheimagnitude + \ getntheiname + \ getntheirange + \ getntheiscript + \ getntheisschool + \ getntheisvisualeffect + \ getnthexplicitref + \ getnthfaction + \ getnthfactionrankname + \ getnthfollower + \ getnthlevitem + \ getnthlevitemcount + \ getnthlevitemlevel + \ getnthmagiceffectcounter + \ getnthmagiceffectcounterc + \ getnthmecounter + \ getnthmecounterc + \ getnthmodname + \ getnthpackage + \ getnthplayerspell + \ getnthracebonusskill + \ getnthracespell + \ getnthspell + \ getnumchildrefs + \ getnumdetectedactors + \ getnumericinisetting + \ getnumexplicitrefs + \ getnumfactions + \ getnumfollowers + \ getnumitems + \ getnumkeyspressed + \ getnumlevitems + \ getnumloadedmods + \ getnumloadedplugins + \ getnummousebuttonspressed + \ getnumpackages + \ getnumranks + \ getnumrefs + \ getnumrefsincell + \ getobjectcharge + \ getobjecthealth + \ getobjecttype + \ getobliviondirectory + \ getoblrevision + \ getoblversion + \ getopenkey + \ getopensound + \ getowner + \ getowningfactionrank + \ getowningfactionrequiredrank + \ getpackageallowfalls + \ getpackageallowswimming + \ getpackagealwaysrun + \ getpackagealwayssneak + \ getpackagearmorunequipped + \ getpackagecontinueifpcnear + \ getpackagedata + \ getpackagedefensivecombat + \ getpackagelocationdata + \ getpackagelockdoorsatend + \ getpackagelockdoorsatlocation + \ getpackagelockdoorsatstart + \ getpackagemustcomplete + \ getpackagemustreachlocation + \ getpackagenoidleanims + \ getpackageoffersservices + \ getpackageonceperday + \ getpackagescheduledata + \ getpackageskipfalloutbehavior + \ getpackagetargetdata + \ getpackageunlockdoorsatend + \ getpackageunlockdoorsatlocation + \ getpackageunlockdoorsatstart + \ getpackageusehorse + \ getpackageweaponsunequipped + \ getparentcell + \ getparentcellowner + \ getparentcellowningfactionrank + \ getparentcellowningfactionrequiredrank + \ getparentcellwaterheight + \ getparentworldspace + \ getpathnodelinkedref + \ getpathnodepos + \ getpathnodesinradius + \ getpathnodesinrect + \ getpcattributebonus + \ getpcattributebonusc + \ getpclastdroppeditem + \ getpclastdroppeditemref + \ getpclasthorse + \ getpclastloaddoor + \ getpcmajorskillups + \ getpcmovementspeedmodifier + \ getpcspelleffectivenessmodifier + \ getpctrainingsessionsused + \ getplayerbirthsign + \ getplayerskilladvances + \ getplayerskilladvancesc + \ getplayerskilluse + \ getplayerskillusec + \ getplayerslastactivatedloaddoor + \ getplayerslastriddenhorse + \ getplayerspell + \ getplayerspellcount + \ getpluginversion + \ getplyerspellcount + \ getprocesslevel + \ getprojectile + \ getprojectiledistancetraveled + \ getprojectilelifetime + \ getprojectilesource + \ getprojectilespeed + \ getprojectiletype + \ getqmcurrent + \ getqmitem + \ getqmmaximum + \ getqr + \ getquality + \ getquantitymenucurrentquantity + \ getquantitymenuitem + \ getquantitymenumaximumquantity + \ getrace + \ getraceattribute + \ getraceattributec + \ getracedefaulthair + \ getraceeyes + \ getracehairs + \ getracereaction + \ getracescale + \ getraceskillbonus + \ getraceskillbonusc + \ getracespellcount + \ getracevoice + \ getraceweight + \ getrawformidstring + \ getrefcount + \ getrefvariable + \ getrequiredskillexp + \ getrequiredskillexpc + \ getrider + \ getscript + \ getscriptactiveeffectindex + \ getselectedspells + \ getservicesmask + \ getsigilstoneuses + \ getskillgoverningattribute + \ getskillgoverningattributec + \ getskillspecialization + \ getskillspecializationc + \ getskilluseincrement + \ getskilluseincrementc + \ getsoulgemcapacity + \ getsoullevel + \ getsoundattenuation + \ getsoundplaying + \ getsourcemodindex + \ getspecialanims + \ getspellareaeffectignoreslos + \ getspellcount + \ getspelldisallowabsorbreflect + \ getspelleffectiveness + \ getspellexplodeswithnotarget + \ getspellhostile + \ getspellimmunetosilence + \ getspellmagickacost + \ getspellmasterylevel + \ getspellpcstart + \ getspells + \ getspellschool + \ getspellscripteffectalwaysapplies + \ getspelltype + \ getstageentries + \ getstageids + \ getstringgamesetting + \ getstringinisetting + \ getsundamage + \ getsunglare + \ gettailmodelpath + \ gettargets + \ gettelekinesisref + \ getteleportcell + \ getteleportcellname + \ getterrainheight + \ gettextinputcontrolpressed + \ gettextinputcursorpos + \ gettexturepath + \ gettilechildren + \ gettiletraits + \ gettimeleft + \ gettotalactiveeffectmagnitude + \ gettotalactiveeffectmagnitudec + \ gettotalaeabilitymagnitude + \ gettotalaeabilitymagnitudec + \ gettotalaealchemymagnitude + \ gettotalaealchemymagnitudec + \ gettotalaeallspellsmagnitude + \ gettotalaeallspellsmagnitudec + \ gettotalaediseasemagnitude + \ gettotalaediseasemagnitudec + \ gettotalaeenchantmentmagnitude + \ gettotalaeenchantmentmagnitudec + \ gettotalaelesserpowermagnitude + \ gettotalaelesserpowermagnitudec + \ gettotalaemagnitude + \ gettotalaemagnitudec + \ gettotalaenonabilitymagnitude + \ gettotalaenonabilitymagnitudec + \ gettotalaepowermagnitude + \ gettotalaepowermagnitudec + \ gettotalaespellmagnitude + \ gettotalaespellmagnitudec + \ gettotalpcattributebonus + \ gettrainerlevel + \ gettrainerskill + \ gettransactioninfo + \ gettransdelta + \ gettravelhorse + \ getusedpowers + \ getusertime + \ getvariable + \ getvelocity + \ getverticalvelocity + \ getwaterheight + \ getwatershader + \ getweahtercloudspeedupper + \ getweaponreach + \ getweaponspeed + \ getweapontype + \ getweatherclassification + \ getweathercloudspeedlower + \ getweathercloudspeedupper + \ getweathercolor + \ getweatherfogdayfar + \ getweatherfogdaynear + \ getweatherfognightfar + \ getweatherfognightnear + \ getweatherhdrvalue + \ getweatherlightningfrequency + \ getweatheroverride + \ getweathersundamage + \ getweathersunglare + \ getweathertransdelta + \ getweatherwindspeed + \ getweight + \ getworldparentworld + \ getworldspaceparentworldspace + \ globalvariableexists + \ hammerkey + \ hasbeenpickedup + \ haseffectshader + \ haslowlevelprocessing + \ hasmodel + \ hasname + \ hasnopersuasion + \ hasspell + \ hastail + \ hasvariable + \ haswater + \ holdkey + \ iconpathincludes + \ identitymat + \ incrementplayerskilluse + \ incrementplayerskillusec + \ ininvertfasttravel + \ insertininputtext + \ isactivatable + \ isactivator + \ isactorrespawning + \ isalchemyitem + \ isammo + \ isanimgroupplaying + \ isanimplaying + \ isapparatus + \ isarmor + \ isattacking + \ isautomaticdoor + \ isbartermenuactive + \ isbipediconpathvalid + \ isbipedmodelpathvalid + \ isblocking + \ isbook + \ iscantwait + \ iscasting + \ iscellpublic + \ isclassattribute + \ isclassattributec + \ isclassskill + \ isclassskillc + \ isclonedform + \ isclothing + \ isconsoleopen + \ iscontainer + \ iscontrol + \ iscontroldisabled + \ iscontrolpressed + \ iscreature + \ iscreaturebiped + \ isdigit + \ isdiseased + \ isdodging + \ isdoor + \ isequipped + \ isfactionevil + \ isfactionhidden + \ isfemale + \ isflora + \ isflying + \ isfood + \ isformvalid + \ isfurniture + \ isgamemessagebox + \ isglobalcollisiondisabled + \ isharvested + \ ishiddendoor + \ isiconpathvalid + \ isinair + \ isingredient + \ isinoblivion + \ isjumping + \ iskey + \ iskeydisabled + \ iskeypressed + \ iskeypressed2 + \ iskeypressed3 + \ isletter + \ islight + \ islightcarriable + \ isloaddoor + \ ismagiceffectcanrecover + \ ismagiceffectcanrecoverc + \ ismagiceffectdetrimental + \ ismagiceffectdetrimentalc + \ ismagiceffectforenchanting + \ ismagiceffectforenchantingc + \ ismagiceffectforspellmaking + \ ismagiceffectforspellmakingc + \ ismagiceffecthostile + \ ismagiceffecthostilec + \ ismagiceffectmagnitudepercent + \ ismagiceffectmagnitudepercentc + \ ismagiceffectonselfallowed + \ ismagiceffectonselfallowedc + \ ismagiceffectontargetallowed + \ ismagiceffectontargetallowedc + \ ismagiceffectontouchallowed + \ ismagiceffectontouchallowedc + \ ismagicitemautocalc + \ ismajor + \ ismajorc + \ ismajorref + \ ismapmarkervisible + \ ismecanrecover + \ ismecanrecoverc + \ ismedetrimental + \ ismedetrimentalc + \ ismeforenchanting + \ ismeforenchantingc + \ ismeforspellmaking + \ ismeforspellmakingc + \ ismehostile + \ ismehostilec + \ ismemagnitudepercent + \ ismemagnitudepercentc + \ ismeonselfallowed + \ ismeonselfallowedc + \ ismeontargetallowed + \ ismeontargetallowedc + \ ismeontouchallowed + \ ismeontouchallowedc + \ isminimalusedoor + \ ismiscitem + \ ismodelpathvalid + \ ismodloaded + \ ismovingbackward + \ ismovingforward + \ ismovingleft + \ ismovingright + \ isnaked + \ isnthactiveeffectapplied + \ isntheffectitemscripted + \ isntheffectitemscripthostile + \ isntheishostile + \ isobliviongate + \ isoblivioninterior + \ isoblivionworld + \ isofflimits + \ isonground + \ ispathnodedisabled + \ ispcleveloffset + \ ispersistent + \ isplayable + \ isplayable2 + \ isplugininstalled + \ ispoison + \ ispotion + \ ispowerattacking + \ isprintable + \ ispunctuation + \ isquestcomplete + \ isquestitem + \ isracebonusskill + \ isracebonusskillc + \ israceplayable + \ isrecoiling + \ isrefdeleted + \ isreference + \ isrefessential + \ isscripted + \ issigilstone + \ issoulgem + \ isspellhostile + \ isstaggered + \ issummonable + \ istaken + \ istextinputinuse + \ isthirdperson + \ isturningleft + \ isturningright + \ isunderwater + \ isunsaferespawns + \ isuppercase + \ isweapon + \ leftshift + \ linktodoor + \ loadgameex + \ log + \ log10 + \ logicaland + \ logicalnot + \ logicalor + \ logicalxor + \ magiceffectcodefromchars + \ magiceffectfromchars + \ magiceffectfromcode + \ magiceffectfxpersists + \ magiceffectfxpersistsc + \ magiceffecthasnoarea + \ magiceffecthasnoareac + \ magiceffecthasnoduration + \ magiceffecthasnodurationc + \ magiceffecthasnohiteffect + \ magiceffecthasnohiteffectc + \ magiceffecthasnoingredient + \ magiceffecthasnoingredientc + \ magiceffecthasnomagnitude + \ magiceffecthasnomagnitudec + \ magiceffectusesarmor + \ magiceffectusesarmorc + \ magiceffectusesattribute + \ magiceffectusesattributec + \ magiceffectusescreature + \ magiceffectusescreaturec + \ magiceffectusesotheractorvalue + \ magiceffectusesotheractorvaluec + \ magiceffectusesskill + \ magiceffectusesskillc + \ magiceffectusesweapon + \ magiceffectusesweaponc + \ magichaseffect + \ magichaseffectc + \ magicitemhaseffect + \ magicitemhaseffectcode + \ magicitemhaseffectcount + \ magicitemhaseffectcountc + \ magicitemhaseffectcountcode + \ magicitemhaseffectitemscript + \ matadd + \ matchpotion + \ matinv + \ matmult + \ matrixadd + \ matrixdeterminant + \ matrixinvert + \ matrixmultiply + \ matrixrref + \ matrixscale + \ matrixsubtract + \ matrixtrace + \ matrixtranspose + \ matscale + \ matsubtract + \ mecodefromchars + \ mefxpersists + \ mefxpersistsc + \ mehasnoarea + \ mehasnoareac + \ mehasnoduration + \ mehasnodurationc + \ mehasnohiteffect + \ mehasnohiteffectc + \ mehasnoingredient + \ mehasnoingredientc + \ mehasnomagnitude + \ mehasnomagnitudec + \ menuholdkey + \ menumode + \ menureleasekey + \ menutapkey + \ messageboxex + \ messageex + \ meusesarmor + \ meusesarmorc + \ meusesattribute + \ meusesattributec + \ meusescreature + \ meusescreaturec + \ meusesotheractorvalue + \ meusesotheractorvaluec + \ meusesskill + \ meusesskillc + \ meusesweapon + \ meusesweaponc + \ modactorvalue2 + \ modactorvaluec + \ modarmorar + \ modattackdamage + \ modav2 + \ modavc + \ modavmod + \ modavmodc + \ modcurrentcharge + \ modelpathincludes + \ modenchantmentcharge + \ modenchantmentcost + \ modequippedcurrentcharge + \ modequippedcurrenthealth + \ modfemalebipedpath + \ modfemalegroundpath + \ modfemaleiconpath + \ modgoldvalue + \ modiconpath + \ modlocaldataexists + \ modmalebipedpath + \ modmalegroundpath + \ modmaleiconpath + \ modmodelpath + \ modname + \ modnthactiveeffectmagnitude + \ modnthaemagnitude + \ modntheffectitemarea + \ modntheffectitemduration + \ modntheffectitemmagnitude + \ modntheffectitemscriptname + \ modntheiarea + \ modntheiduration + \ modntheimagnitude + \ modntheisname + \ modobjectcharge + \ modobjecthealth + \ modpcmovementspeed + \ modpcspelleffectiveness + \ modplayerskillexp + \ modplayerskillexpc + \ modquality + \ modsigilstoneuses + \ modspellmagickacost + \ modweaponreach + \ modweaponspeed + \ modweight + \ movemousex + \ movemousey + \ movetextinputcursor + \ nameincludes + \ numtohex + \ offersapparatus + \ offersarmor + \ offersbooks + \ offersclothing + \ offersingredients + \ offerslights + \ offersmagicitems + \ offersmiscitems + \ offerspotions + \ offersrecharging + \ offersrepair + \ offersservicesc + \ offersspells + \ offerstraining + \ offersweapons + \ oncontroldown + \ onkeydown + \ opentextinput + \ outputlocalmappicturesoverride + \ overrideactorswimbreath + \ parentcellhaswater + \ pathedgeexists + \ playidle + \ pow + \ print + \ printactivetileinfo + \ printc + \ printd + \ printtileinfo + \ printtoconsole + \ questexists + \ racos + \ rand + \ rasin + \ ratan + \ ratan2 + \ rcos + \ rcosh + \ refreshcurrentclimate + \ releasekey + \ removealleffectitems + \ removebasespell + \ removeenchantment + \ removeequippedweaponpoison + \ removeeventhandler + \ removefromleveledlist + \ removeitemns + \ removelevitembylevel + \ removemeir + \ removemodlocaldata + \ removentheffect + \ removentheffectitem + \ removenthlevitem + \ removenthmagiceffectcounter + \ removenthmagiceffectcounterc + \ removenthmecounter + \ removenthmecounterc + \ removescript + \ removescr + \ removespellns + \ resetallvariables + \ resetfalrior + \ resolvemodindex + \ rightshift + \ rotmat + \ rowvec + \ rsin + \ rsinh + \ rtan + \ rtanh + \ runbatchscript + \ runscriptline + \ saespassalarm + \ setactivequest + \ setactrfullname + \ setactormaxswimbreath + \ setactorrespawns + \ setactorswimbreath + \ setactorvaluec + \ setalvisible + \ setaltcontrol2 + \ setapparatustype + \ setarmorar + \ setarmortype + \ setarrowprojectilebowenchantment + \ setarrowprojectileenchantment + \ setarrowprojectilepoison + \ setattackdamage + \ setavc + \ setavmod + \ setavmodc + \ setbaseform + \ setbipediconpathex + \ setbipedmodelpathex + \ setbipedslotmask + \ setbookcantbetaken + \ setbookisscroll + \ setbookskilltaught + \ setbuttonpressed + \ setcalcalllevels + \ setcamerafov2 + \ setcancastpower + \ setcancorpsecheck + \ setcanfasttravelfromworld + \ setcantraveltomapmarker + \ setcantwait + \ setcellbehavesasexterior + \ setcellclimate + \ setcellhaswater + \ setcellispublic + \ setcelllighting + \ setcellmusictype + \ setcellublicflag + \ setcellresethours + \ setcellwaterheight + \ setcellwatertype + \ setchancenone + \ setclassattribute + \ setclassattributec + \ setclassskills + \ setclassskills2 + \ setclassspecialization + \ setclimatehasmasser + \ setclimatehasmassser + \ setclimatehassecunda + \ setclimatemoonphaselength + \ setclimatesunrisebegin + \ setclimatesunriseend + \ setclimatesunsetbegin + \ setclimatesunsetend + \ setclimatevolatility + \ setclosesound + \ setcloudspeedlower + \ setcloudspeedupper + \ setcombatstyle + \ setcombatstyleacrobaticsdodgechance + \ setcombatstyleattackchance + \ setcombatstyleattackduringblockmult + \ setcombatstyleattacknotunderattackmult + \ setcombatstyleattackskillmodbase + \ setcombatstyleattackskillmodmult + \ setcombatstyleattackunderattackmult + \ setcombatstyleblockchance + \ setcombatstyleblocknotunderattackmult + \ setcombatstyleblockskillmodbase + \ setcombatstyleblockskillmodmult + \ setcombatstyleblockunderattackmult + \ setcombatstylebuffstandoffdist + \ setcombatstyledodgebacknotunderattackmult + \ setcombatstyledodgebacktimermax + \ setcombatstyledodgebacktimermin + \ setcombatstyledodgebackunderattackmult + \ setcombatstyledodgechance + \ setcombatstyledodgefatiguemodbase + \ setcombatstyledodgefatiguemodmult + \ setcombatstyledodgefwattackingmult + \ setcombatstyledodgefwnotattackingmult + \ setcombatstyledodgefwtimermax + \ setcombatstyledodgefwtimermin + \ setcombatstyledodgelrchance + \ setcombatstyledodgelrtimermax + \ setcombatstyledodgelrtimermin + \ setcombatstyledodgenotunderattackmult + \ setcombatstyledodgeunderattackmult + \ setcombatstyleencumberedspeedmodbase + \ setcombatstyleencumberedspeedmodmult + \ setcombatstylefleeingdisabled + \ setcombatstylegroupstandoffdist + \ setcombatstyleh2hbonustoattack + \ setcombatstyleholdtimermax + \ setcombatstyleholdtimermin + \ setcombatstyleidletimermax + \ setcombatstyleidletimermin + \ setcombatstyleignorealliesinarea + \ setcombatstylekobonustoattack + \ setcombatstylekobonustopowerattack + \ setcombatstylemeleealertok + \ setcombatstylepowerattackchance + \ setcombatstylepowerattackfatiguemodbase + \ setcombatstylepowerattackfatiguemodmult + \ setcombatstyleprefersranged + \ setcombatstylerangedstandoffdist + \ setcombatstylerangemaxmult + \ setcombatstylerangeoptimalmult + \ setcombatstylerejectsyields + \ setcombatstylerushattackchance + \ setcombatstylerushattackdistmult + \ setcombatstylestaggerbonustoattack + \ setcombatstylestaggerbonustopowerattack + \ setcombatstyleswitchdistmelee + \ setcombatstyleswitchdistranged + \ setcombatstylewillyield + \ setcontainerrespawns + \ setcontrol + \ setcreatureskill + \ setcreaturesoundbase + \ setcreaturetype + \ setcurrentcharge + \ setcurrenthealth + \ setcurrentsoullevel + \ setdebugmode + \ setdescription + \ setdetectionstate + \ setdisableglobalcollision + \ setdoorteleport + \ setenchantment + \ setenchantmentcharge + \ setenchantmentcost + \ setenchantmenttype + \ setequipmentslot + \ setequippedcurrentcharge + \ setequippedcurrenthealth + \ setequippedweaponpoison + \ seteventhandler + \ seteyes + \ setfactionevil + \ setfactionhasspecialcombat + \ setfactionhidden + \ setfactonreaction + \ setfactionspecialcombat + \ setfemale + \ setfemalebipedpath + \ setfemalegroundpath + \ setfemaleiconpath + \ setflycameraspeedmult + \ setfogdayfar + \ setfogdaynear + \ setfognightfar + \ setfognightnear + \ setforcsneak + \ setfunctionvalue + \ setgamedifficulty + \ setgoldvalue + \ setgoldvalue_t + \ setgoldvaluet + \ sethair + \ setharvested + \ sethasbeenpickedup + \ sethdrvalue + \ sethidesamulet + \ sethidesrings + \ sethotkeyitem + \ seticonpath + \ setignoresresistance + \ setingredient + \ setingredientchance + \ setinputtext + \ setinvertfasttravel + \ setisautomaticdoor + \ setiscontrol + \ setisfood + \ setishiddendoor + \ setisminimalusedoor + \ setisobliviongate + \ setisplayable + \ setlevcreaturetemplate + \ setlightduration + \ setlightningfrequency + \ setlightradius + \ setlightrgb + \ setlocalgravity + \ setlocalgravityvector + \ setloopsound + \ setlowlevelprocessing + \ setmaagiceffectuseactorvalue + \ setmagiceffectareasound + \ setmagiceffectareasoundc + \ setmagiceffectbarterfactor + \ setmagiceffectbarterfactorc + \ setmagiceffectbasecost + \ setmagiceffectbasecostc + \ setmagiceffectboltsound + \ setmagiceffectboltsoundc + \ setmagiceffectcanrecover + \ setmagiceffectcanrecoverc + \ setmagiceffectcastingsound + \ setmagiceffectcastingsoundc + \ setmagiceffectcounters + \ setmagiceffectcountersc + \ setmagiceffectenchantfactor + \ setmagiceffectenchantfactorc + \ setmagiceffectenchantshader + \ setmagiceffectenchantshaderc + \ setmagiceffectforenchanting + \ setmagiceffectforenchantingc + \ setmagiceffectforspellmaking + \ setmagiceffectforspellmakingc + \ setmagiceffectfxpersists + \ setmagiceffectfxpersistsc + \ setmagiceffecthitshader + \ setmagiceffecthitshaderc + \ setmagiceffecthitsound + \ setmagiceffecthitsoundc + \ setmagiceffecticon + \ setmagiceffecticonc + \ setmagiceffectisdetrimental + \ setmagiceffectisdetrimentalc + \ setmagiceffectishostile + \ setmagiceffectishostilec + \ setmagiceffectlight + \ setmagiceffectlightc + \ setmagiceffectmagnitudepercent + \ setmagiceffectmagnitudepercentc + \ setmagiceffectmodel + \ setmagiceffectmodelc + \ setmagiceffectname + \ setmagiceffectnamec + \ setmagiceffectnoarea + \ setmagiceffectnoareac + \ setmagiceffectnoduration + \ setmagiceffectnodurationc + \ setmagiceffectnohiteffect + \ setmagiceffectnohiteffectc + \ setmagiceffectnoingredient + \ setmagiceffectnoingredientc + \ setmagiceffectnomagnitude + \ setmagiceffectnomagnitudec + \ setmagiceffectonselfallowed + \ setmagiceffectonselfallowedc + \ setmagiceffectontargetallowed + \ setmagiceffectontargetallowedc + \ setmagiceffectontouchallowed + \ setmagiceffectontouchallowedc + \ setmagiceffectotheractorvalue + \ setmagiceffectotheractorvaluec + \ setmagiceffectprojectilespeed + \ setmagiceffectprojectilespeedc + \ setmagiceffectresistvalue + \ setmagiceffectresistvaluec + \ setmagiceffectschool + \ setmagiceffectschoolc + \ setmagiceffectuseactorvaluec + \ setmagiceffectusedobject + \ setmagiceffectusedobjectc + \ setmagiceffectusesactorvalue + \ setmagiceffectusesactorvaluec + \ setmagiceffectusesarmor + \ setmagiceffectusesarmorc + \ setmagiceffectusesattribute + \ setmagiceffectusesattributec + \ setmagiceffectusescreature + \ setmagiceffectusescreaturec + \ setmagiceffectusesskill + \ setmagiceffectusesskillc + \ setmagiceffectusesweapon + \ setmagiceffectusesweaponc + \ setmagicitemautocalc + \ setmagicprojectilespell + \ setmalebipedpath + \ setmalegroundpath + \ setmaleiconpath + \ setmapmarkertype + \ setmapmarkervisible + \ setmeareasound + \ setmeareasoundc + \ setmebarterfactor + \ setmebarterfactorc + \ setmebasecost + \ setmebasecostc + \ setmeboltsound + \ setmeboltsoundc + \ setmecanrecover + \ setmecanrecoverc + \ setmecastingsound + \ setmecastingsoundc + \ setmeenchantfactor + \ setmeenchantfactorc + \ setmeenchantshader + \ setmeenchantshaderc + \ setmeforenchanting + \ setmeforenchantingc + \ setmeforspellmaking + \ setmeforspellmakingc + \ setmefxpersists + \ setmefxpersistsc + \ setmehitshader + \ setmehitshaderc + \ setmehitsound + \ setmehitsoundc + \ setmeicon + \ setmeiconc + \ setmeisdetrimental + \ setmeisdetrimentalc + \ setmeishostile + \ setmeishostilec + \ setmelight + \ setmelightc + \ setmemagnitudepercent + \ setmemagnitudepercentc + \ setmemodel + \ setmemodelc + \ setmename + \ setmenamec + \ setmenoarea + \ setmenoareac + \ setmenoduration + \ setmenodurationc + \ setmenohiteffect + \ setmenohiteffectc + \ setmenoingredient + \ setmenoingredientc + \ setmenomagnitude + \ setmenomagnitudec + \ setmenufloatvalue + \ setmenustringvalue + \ setmeonselfallowed + \ setmeonselfallowedc + \ setmeontargetallowed + \ setmeontargetallowedc + \ setmeontouchallowed + \ setmeontouchallowedc + \ setmeotheractorvalue + \ setmeotheractorvaluec + \ setmeprojectilespeed + \ setmeprojectilespeedc + \ setmerchantcontainer + \ setmeresistvalue + \ setmeresistvaluec + \ setmeschool + \ setmeschoolc + \ setmessageicon + \ setmessagesound + \ setmeuseactorvalue + \ setmeuseactorvaluec + \ setmeusedobject + \ setmeusedobjectc + \ setmeusesarmor + \ setmeusesarmorc + \ setmeusesattribute + \ setmeusesattributec + \ setmeusescreature + \ setmeusescreaturec + \ setmeusesskill + \ setmeusesskillc + \ setmeusesweapon + \ setmeusesweaponc + \ setmodelpath + \ setmodlocaldata + \ setmousespeedx + \ setmousespeedy + \ setmpspell + \ setname + \ setnameex + \ setnopersuasion + \ setnthactiveeffectmagnitude + \ setnthaemagnitude + \ setntheffectitemactorvalue + \ setntheffectitemactorvaluec + \ setntheffectitemarea + \ setntheffectitemduration + \ setntheffectitemmagnitude + \ setntheffectitemrange + \ setntheffectitemscript + \ setntheffectitemscripthostile + \ setntheffectitemscriptname + \ setntheffectitemscriptnameex + \ setntheffectitemscriptschool + \ setntheffectitemscriptvisualeffect + \ setntheffectitemscriptvisualeffectc + \ setntheiarea + \ setntheiav + \ setntheiavc + \ setntheiduration + \ setntheimagnitude + \ setntheirange + \ setntheiscript + \ setntheishostile + \ setntheisname + \ setntheisschool + \ setntheisvisualeffect + \ setntheisvisualeffectc + \ setnthfactionranknameex + \ setnumericgamesetting + \ setnumericinisetting + \ setobjectcharge + \ setobjecthealth + \ setoffersapparatus + \ setoffersarmor + \ setoffersbooks + \ setoffersclothing + \ setoffersingredients + \ setofferslights + \ setoffersmagicitems + \ setoffersmiscitems + \ setofferspotions + \ setoffersrecharging + \ setoffersrepair + \ setoffersservicesc + \ setoffersspells + \ setofferstraining + \ setoffersweapons + \ setolmpgrids + \ setopenkey + \ setopensound + \ setopenstip + \ setownership_t + \ setowningrequiredrank + \ setpackageallowfalls + \ setpackageallowswimming + \ setpackagealwaysrun + \ setpackagealwayssneak + \ setpackagearmorunequipped + \ setpackagecontinueifpcnear + \ setpackagedata + \ setpackagedefensivecombat + \ setpackagelocationdata + \ setpackagelockdoorsatend + \ setpackagelockdoorsatlocation + \ setpackagelockdoorsatstart + \ setpackagemustcomplete + \ setpackagemustreachlocation + \ setpackagenoidleanims + \ setpackageoffersservices + \ setpackageonceperday + \ setpackagescheduledata + \ setpackageskipfalloutbehavior + \ setpackagetarget + \ setpackagetargetdata + \ setpackageunlockdoorsatend + \ setpackageunlockdoorsatlocation + \ setpackageunlockdoorsatstart + \ setpackageusehorse + \ setpackageweaponsunequipped + \ setparentcellowningfactionrequiredrank + \ setpathnodedisabled + \ setpcamurderer + \ setpcattributebonus + \ setpcattributebonusc + \ setpcexpy + \ setpcleveloffset + \ setpcmajorskillups + \ setpctrainingsessionsused + \ setplayerbseworld + \ setplayerprojectile + \ setplayerskeletonpath + \ setplayerskilladvances + \ setplayerskilladvancesc + \ setplayerslastriddenhorse + \ setpos_t + \ setpowertimer + \ setprojectilesource + \ setprojectilespeed + \ setquality + \ setquestitem + \ setracealias + \ setraceplayable + \ setracescale + \ setracevoice + \ setraceweight + \ setrefcount + \ setrefessential + \ setreale + \ setscaleex + \ setscript + \ setsigilstoneuses + \ setskillgoverningattribute + \ setskillgoverningattributec + \ setskillspecialization + \ setskillspecializationc + \ setskilluseincrement + \ setskilluseincrementc + \ setsoulgemcapacity + \ setsoullevel + \ setsoundattenuation + \ setspellareaeffectignoreslos + \ setspelldisallowabsorbreflect + \ setspellexplodeswithnotarget + \ setspellhostile + \ setspellimmunetosilence + \ setspellmagickacost + \ setspellmasterylevel + \ setspellpcstart + \ setspellscripteffectalwaysapplies + \ setspelltype + \ setstagedate + \ setstagetext + \ setstringgamesettingex + \ setstringinisetting + \ setsummonable + \ setsundamage + \ setsunglare + \ settaken + \ settextinputcontrolhandler + \ settextinputdefaultcontrolsdisabled + \ settextinputhandler + \ settexturepath + \ settimeleft + \ settrainerlevel + \ settrainerskill + \ settransdelta + \ settravelhorse + \ setunsafecontainer + \ setvelocity + \ setverticalvelocity + \ setweaponreach + \ setweaponspeed + \ setweapontype + \ setweathercloudspeedlower + \ setweathercloudspeedupper + \ setweathercolor + \ setweatherfogdayfar + \ setweatherfogdaynear + \ setweatherfognightfar + \ setweatherfognightnear + \ setweatherhdrvalue + \ setweatherlightningfrequency + \ setweathersundamage + \ setweathersunglare + \ setweathertransdelta + \ setweatherwindspeed + \ setweight + \ setwindspeed + \ showellmaking + \ sin + \ sinh + \ skipansqrt + \ squareroot + \ startcc + \ stringtoactorvalue + \ tan + \ tanh + \ tapcontrol + \ tapkey + \ testexpr + \ thiactorsai + \ togglecreaturemodel + \ togglefirstperson + \ toggleskillperk + \ togglespecialanim + \ tolower + \ tonumber + \ tostring + \ toupper + \ trapuphitshader + \ triggerplayerskilluse + \ triggerplayerskillusec + \ typeof + \ uncompletequest + \ unequipitemns + \ unequipitemsilent + \ unequipme + \ unhammerkey + \ unsetstagetext + \ update3d + \ updatecontainermenu + \ updatespellpurchasemenu + \ updatetextinput + \ vecmag + \ vecnorm + \ vectorcross + \ vectordot + \ vectormagnitude + \ vectornormalize + \ zeromat +" }}} + +" Array Functions {{{ +syn keyword obseArrayFunction + \ ar_Append + \ ar_BadNumericIndex + \ ar_BadStringIndex + \ ar_Construct + \ ar_Copy + \ ar_CustomSort + \ ar_DeepCopy + \ ar_Dump + \ ar_DumpID + \ ar_Erase + \ ar_Find + \ ar_First + \ ar_HasKey + \ ar_Insert + \ ar_InsertRange + \ ar_Keys + \ ar_Last + \ ar_List + \ ar_Map + \ ar_Next + \ ar_Null + \ ar_Prev + \ ar_Range + \ ar_Resize + \ ar_Size + \ ar_Sort + \ ar_SortAlpha +" }}} + +" String Functions {{{ +syn keyword obseStringFunction + \ sv_ToLower + \ sv_ToUpper + \ sv_Compare + \ sv_Construct + \ sv_Count + \ sv_Destruct + \ sv_Erase + \ sv_Find + \ sv_Insert + \ sv_Length + \ sv_Percentify + \ sv_Replace + \ sv_Split + \ sv_ToNumeric +" }}} + +" Pluggy Functions {{{ +syn keyword pluggyFunction + \ ArrayCmp + \ ArrayCount + \ ArrayEsp + \ ArrayProtect + \ ArraySize + \ AutoSclHudS + \ AutoSclHudT + \ CopyArray + \ CopyString + \ CreateArray + \ CreateEspBook + \ CreateString + \ DelAllHudSs + \ DelAllHudTs + \ DelFile + \ DelHudS + \ DelHudT + \ DelTxtFile + \ DestroyAllArrays + \ DestroyAllStrings + \ DestroyArray + \ DestroyString + \ DupArray + \ EspToString + \ FileToString + \ FindFirstFile + \ FindFloatInArray + \ FindInArray + \ FindNextFile + \ FindRefInArray + \ FirstFreeInArray + \ FirstInArray + \ FixName + \ FixNameEx + \ FloatToString + \ FmtString + \ FromOBSEString + \ FromTSFC + \ GetEsp + \ GetFileSize + \ GetInArray + \ GetRefEsp + \ GetTypeInArray + \ Halt + \ HasFixedName + \ HudSEsp + \ HudSProtect + \ HudS_Align + \ HudS_L + \ HudS_Opac + \ HudS_SclX + \ HudS_SclY + \ HudS_Show + \ HudS_Tex + \ HudS_X + \ HudS_Y + \ HudTEsp + \ HudTInfo + \ HudTProtect + \ HudT_Align + \ HudT_Font + \ HudT_L + \ HudT_Opac + \ HudT_SclX + \ HudT_SclY + \ HudT_Show + \ HudT_Text + \ HudT_X + \ HudT_Y + \ HudsInfo + \ IniDelKey + \ IniGetNthSection + \ IniKeyExists + \ IniReadFloat + \ IniReadInt + \ IniReadRef + \ IniReadString + \ IniSectionsCount + \ IniWriteFloat + \ IniWriteInt + \ IniWriteRef + \ IniWriteString + \ IntToHex + \ IntToString + \ IsHUDEnabled + \ IsPluggyDataReset + \ KillMenu + \ LC + \ LongToRef + \ ModRefEsp + \ NewHudS + \ NewHudT + \ PackArray + \ PauseBox + \ PlgySpcl + \ RefToLong + \ RefToString + \ RemInArray + \ RenFile + \ RenTxtFile + \ ResetName + \ RunBatString + \ SanString + \ ScreenInfo + \ SetFloatInArray + \ SetHudT + \ SetInArray + \ SetRefInArray + \ SetString + \ StrLC + \ StringCat + \ StringCmp + \ StringEsp + \ StringGetName + \ StringGetNameEx + \ StringIns + \ StringLen + \ StringMsg + \ StringMsgBox + \ StringPos + \ StringProtect + \ StringRep + \ StringSetName + \ StringSetNameEx + \ StringToFloat + \ StringToInt + \ StringToRef + \ StringToTxtFile + \ ToOBSE + \ ToOBSEString + \ ToTSFC + \ TxtFileExists + \ UserFileExists + \ csc + \ rcsc +" }}} + +" tfscFunction {{{ +syn keyword tfscFunction + \ StrAddNewLine + \ StrAppend + \ StrAppendCharCode + \ StrCat + \ StrClear + \ StrClearLast + \ StrCompare + \ StrCopy + \ StrDel + \ StrDeleteAll + \ StrExpr + \ StrGetFemaleBipedPath + \ StrGetFemaleGroundPath + \ StrGetFemaleIconPath + \ StrGetMaleBipedPath + \ StrGetMaleIconPath + \ StrGetModelPath + \ StrGetName + \ StrGetNthEffectItemScriptName + \ StrGetNthFactionRankName + \ StrGetRandomName + \ StrIDReplace + \ StrLength + \ StrLoad + \ StrMessageBox + \ StrNew + \ StrPrint + \ StrReplace + \ StrSave + \ StrSet + \ StrSetFemaleBipedPath + \ StrSetFemaleGroundPath + \ StrSetFemaleIconPath + \ StrSetMaleBipedPath + \ StrSetMaleIconPath + \ StrSetModelPath + \ StrSetName + \ StrSetNthEffectItemScriptName +" }}} + +" Blockhead Functions {{{ +syn keyword blockheadFunction + \ GetBodyAssetOverride + \ GetFaceGenAge + \ GetHeadAssetOverride + \ RefreshAnimData + \ RegisterEquipmentOverrideHandler + \ ResetAgeTextureOverride + \ ResetBodyAssetOverride + \ ResetHeadAssetOverride + \ SetAgeTextureOverride + \ SetBodyAssetOverride + \ SetFaceGenAge + \ SetHeadAssetOverride + \ ToggleAnimOverride + \ UnregisterEquipmentOverrideHandler +" }}} + +" switchNightEyeShaderFunction {{{ +syn keyword switchNightEyeShaderFunction + \ EnumNightEyeShader + \ SetNightEyeShader +" }}} + +" Oblivion Reloaded Functions {{{ +syn keyword obseivionReloadedFunction + \ cameralookat + \ cameralookatposition + \ camerareset + \ camerarotate + \ camerarotatetoposition + \ cameratranslate + \ cameratranslatetoposition + \ getlocationname + \ getsetting + \ getversion + \ getweathername + \ isthirdperson + \ setcustomconstant + \ setextraeffectenabled + \ setsetting +" }}} +" menuQue Functions {{{ +syn keyword menuQueFunction + \ GetAllSkills + \ GetAVSkillMasteryLevelC + \ GetAVSkillMasteryLevelF + \ GetFontLoaded + \ GetGenericButtonPressed + \ GetLoadedFonts + \ GetLocalMapSeen + \ GetMenuEventType + \ GetMenuFloatValue + \ GetMenuStringValue + \ GetMouseImage + \ GetMousePos + \ GetPlayerSkillAdvancesF + \ GetPlayerSkillUseF + \ GetRequiredSkillExpC + \ GetRequiredSkillExpF + \ GetSkillCode + \ GetSkillForm + \ GetSkillGoverningAttributeF + \ GetSkillSpecializationC + \ GetSkillSpecializationF + \ GetSkillUseIncrementF + \ GetTextEditBox + \ GetTextEditString + \ GetTrainingMenuCost + \ GetTrainingMenuLevel + \ GetTrainingMenuSkill + \ GetWorldMapData + \ GetWorldMapDoor + \ IncrementPlayerSkillUseF + \ InsertXML + \ InsertXMLTemplate + \ IsTextEditInUse + \ Kyoma_Test + \ ModPlayerSkillExpF + \ mqCreateMenuFloatValue + \ mqCreateMenuStringValue + \ mqGetActiveQuest + \ mqGetActiveQuestTargets + \ mqGetCompletedQuests + \ mqGetCurrentQuests + \ mqGetEnchMenuBaseItem + \ mqGetHighlightedClass + \ mqGetMapMarkers + \ mqGetMenuActiveChildIndex + \ mqGetMenuActiveFloatValue + \ mqGetMenuActiveStringValue + \ mqGetMenuChildCount + \ mqGetMenuChildFloatValue + \ mqGetMenuChildHasTrait + \ mqGetMenuChildName + \ mqGetMenuChildStringValue + \ mqGetMenuGlobalFloatValue + \ mqGetMenuGlobalStringValue + \ mqGetQuestCompleted + \ mqGetSelectedClass + \ mqSetActiveQuest + \ mqSetMenuActiveFloatValue + \ mqSetMenuActiveStringValue + \ mqSetMenuChildFloatValue + \ mqSetMenuChildStringValue + \ mqSetMenuGlobalStringValue + \ mqSetMenuGlobalFloatValue + \ mqSetMessageBoxSource + \ mqUncompleteQuest + \ RemoveMenuEventHandler + \ SetMenuEventHandler + \ SetMouseImage + \ SetPlayerSkillAdvancesF + \ SetSkillGoverningAttributeF + \ SetSkillSpecializationC + \ SetSkillSpecializationF + \ SetSkillUseIncrementF + \ SetTextEditString + \ SetTrainerSkillC + \ SetWorldMapData + \ ShowGenericMenu + \ ShowLevelUpMenu + \ ShowMagicPopupMenu + \ ShowTextEditMenu + \ ShowTrainingMenu + \ tile_FadeFloat + \ tile_GetFloat + \ tile_GetInfo + \ tile_GetName + \ tile_GetString + \ tile_GetVar + \ tile_HasTrait + \ tile_SetFloat + \ tile_SetString + \ TriggerPlayerSkillUseF + \ UpdateLocalMap +" }}} + +" eaxFunction {{{ +syn keyword eaxFunction + \ CreateEAXeffect + \ DeleteEAXeffect + \ DisableEAX + \ EAXcopyEffect + \ EAXeffectExists + \ EAXeffectsAreEqual + \ EAXgetActiveEffect + \ EAXnumEffects + \ EAXpushEffect + \ EAXpopEffect + \ EAXremoveAllInstances + \ EAXremoveFirstInstance + \ EAXstackIsEmpty + \ EAXstackSize + \ EnableEAX + \ GetEAXAirAbsorptionHF + \ GetEAXDecayHFRatio + \ GetEAXDecayTime + \ GetEAXEnvironment + \ GetEAXEnvironmentSize + \ GetEAXEnvironmentDiffusion + \ GetEAXReflections + \ GetEAXReflectionsDelay + \ GetEAXReverb + \ GetEAXReverbDelay + \ GetEAXRoom + \ GetEAXRoomHF + \ GetEAXRoomRolloffFactor + \ InitializeEAX + \ IsEAXEnabled + \ IsEAXInitialized + \ SetEAXAirAbsorptionHF + \ SetEAXallProperties + \ SetEAXDecayTime + \ SetEAXDecayHFRatio + \ SetEAXEnvironment + \ SetEAXEnvironmentSize + \ SetEAXEnvironmentDiffusion + \ SetEAXReflections + \ SetEAXReflectionsDelay + \ SetEAXReverb + \ SetEAXReverbDelay + \ SetEAXRoom + \ SetEAXRoomHF + \ SetEAXRoomRolloffFactor +" }}} + +" networkPipeFunction {{{ +syn keyword networkPipeFunction + \ NetworkPipe_CreateClient + \ NetworkPipe_GetData + \ NetworkPipe_IsNewGame + \ NetworkPipe_KillClient + \ NetworkPipe_Receive + \ NetworkPipe_SetData + \ NetworkPipe_Send + \ NetworkPipe_StartService + \ NetworkPipe_StopService +" }}} + +" nifseFunction {{{ +syn keyword nifseFunction + \ BSFurnitureMarkerGetPositionRefs + \ BSFurnitureMarkerSetPositionRefs + \ GetNifTypeIndex + \ NiAVObjectAddProperty + \ NiAVObjectClearCollisionObject + \ NiAVObjectCopyCollisionObject + \ NiAVObjectDeleteProperty + \ NiAVObjectGetCollisionMode + \ NiAVObjectGetCollisionObject + \ NiAVObjectGetLocalRotation + \ NiAVObjectGetLocalScale + \ NiAVObjectGetLocalTransform + \ NiAVObjectGetLocalTranslation + \ NiAVObjectGetNumProperties + \ NiAVObjectGetProperties + \ NiAVObjectGetPropertyByType + \ NiAVObjectSetCollisionMode + \ NiAVObjectSetLocalRotation + \ NiAVObjectSetLocalScale + \ NiAVObjectSetLocalTransform + \ NiAVObjectSetLocalTranslation + \ NiAlphaPropertyGetBlendState + \ NiAlphaPropertyGetDestinationBlendFunction + \ NiAlphaPropertyGetSourceBlendFunction + \ NiAlphaPropertyGetTestFunction + \ NiAlphaPropertyGetTestState + \ NiAlphaPropertyGetTestThreshold + \ NiAlphaPropertyGetTriangleSortMode + \ NiAlphaPropertySetBlendState + \ NiAlphaPropertySetDestinationBlendFunction + \ NiAlphaPropertySetSourceBlendFunction + \ NiAlphaPropertySetTestFunction + \ NiAlphaPropertySetTestState + \ NiAlphaPropertySetTestThreshold + \ NiAlphaPropertySetTriangleSortMode + \ NiExtraDataGetArray + \ NiExtraDataGetName + \ NiExtraDataGetNumber + \ NiExtraDataGetString + \ NiExtraDataSetArray + \ NiExtraDataSetName + \ NiExtraDataSetNumber + \ NiExtraDataSetString + \ NiMaterialPropertyGetAmbientColor + \ NiMaterialPropertyGetDiffuseColor + \ NiMaterialPropertyGetEmissiveColor + \ NiMaterialPropertyGetGlossiness + \ NiMaterialPropertyGetSpecularColor + \ NiMaterialPropertyGetTransparency + \ NiMaterialPropertySetAmbientColor + \ NiMaterialPropertySetDiffuseColor + \ NiMaterialPropertySetEmissiveColor + \ NiMaterialPropertySetGlossiness + \ NiMaterialPropertySetSpecularColor + \ NiMaterialPropertySetTransparency + \ NiNodeAddChild + \ NiNodeCopyChild + \ NiNodeDeleteChild + \ NiNodeGetChildByName + \ NiNodeGetChildren + \ NiNodeGetNumChildren + \ NiObjectGetType + \ NiObjectGetTypeName + \ NiObjectNETAddExtraData + \ NiObjectNETDeleteExtraData + \ NiObjectNETGetExtraData + \ NiObjectNETGetExtraDataByName + \ NiObjectNETGetName + \ NiObjectNETGetNumExtraData + \ NiObjectNETSetName + \ NiObjectTypeDerivesFrom + \ NiSourceTextureGetFile + \ NiSourceTextureIsExternal + \ NiSourceTextureSetExternalTexture + \ NiStencilPropertyGetFaceDrawMode + \ NiStencilPropertyGetFailAction + \ NiStencilPropertyGetPassAction + \ NiStencilPropertyGetStencilFunction + \ NiStencilPropertyGetStencilMask + \ NiStencilPropertyGetStencilRef + \ NiStencilPropertyGetStencilState + \ NiStencilPropertyGetZFailAction + \ NiStencilPropertySetFaceDrawMode + \ NiStencilPropertySetFailAction + \ NiStencilPropertySetPassAction + \ NiStencilPropertySetStencilFunction + \ NiStencilPropertySetStencilMask + \ NiStencilPropertySetStencilRef + \ NiStencilPropertySetStencilState + \ NiStencilPropertySetZFailAction + \ NiTexturingPropertyAddTextureSource + \ NiTexturingPropertyDeleteTextureSource + \ NiTexturingPropertyGetTextureCenterOffset + \ NiTexturingPropertyGetTextureClampMode + \ NiTexturingPropertyGetTextureCount + \ NiTexturingPropertyGetTextureFilterMode + \ NiTexturingPropertyGetTextureFlags + \ NiTexturingPropertyGetTextureRotation + \ NiTexturingPropertyGetTextureSource + \ NiTexturingPropertyGetTextureTiling + \ NiTexturingPropertyGetTextureTranslation + \ NiTexturingPropertyGetTextureUVSet + \ NiTexturingPropertyHasTexture + \ NiTexturingPropertySetTextureCenterOffset + \ NiTexturingPropertySetTextureClampMode + \ NiTexturingPropertySetTextureCount + \ NiTexturingPropertySetTextureFilterMode + \ NiTexturingPropertySetTextureFlags + \ NiTexturingPropertySetTextureHasTransform + \ NiTexturingPropertySetTextureRotation + \ NiTexturingPropertySetTextureTiling + \ NiTexturingPropertySetTextureTranslation + \ NiTexturingPropertySetTextureUVSet + \ NiTexturingPropertyTextureHasTransform + \ NiVertexColorPropertyGetLightingMode + \ NiVertexColorPropertyGetVertexMode + \ NiVertexColorPropertySetLightingMode + \ NiVertexColorPropertySetVertexMode + \ NifClose + \ NifGetAltGrip + \ NifGetBackShield + \ NifGetNumBlocks + \ NifGetOffHand + \ NifGetOriginalPath + \ NifGetPath + \ NifOpen + \ NifWriteToDisk +" }}} + +" reidFunction {{{ +syn keyword reidFunction + \ GetRuntimeEditorID +" }}} + +" runtimeDebuggerFunction {{{ +syn keyword runtimeDebuggerFunction + \ DebugBreak + \ ToggleDebugBreaking +" }}} + +" addActorValuesFunction {{{ +syn keyword addActorValuesFunction + \ DumpActorValueC + \ DumpActorValueF + \ GetActorValueBaseCalcC + \ GetActorValueBaseCalcF + \ GetActorValueCurrentC + \ GetActorValueCurrentF + \ GetActorValueMaxC + \ GetActorValueMaxF + \ GetActorValueModC + \ GetActorValueModF + \ ModActorValueModC + \ ModActorValueModF + \ SetActorValueModC + \ SetActorValueModF + \ DumpAVC + \ DumpAVF + \ GetAVModC + \ GetAVModF + \ ModAVModC + \ ModAVModF + \ SetAVModC + \ SetAVModF + \ GetAVBaseCalcC + \ GetAVBaseCalcF + \ GetAVMaxC + \ GetAVMaxF + \ GetAVCurrentC + \ GetAVCurrent +" }}} + +" memoryDumperFunction {{{ +syn keyword memoryDumperFunction + \ SetDumpAddr + \ SetDumpType + \ SetFadeAmount + \ SetObjectAddr + \ ShowMemoryDump +" }}} + +" algoholFunction {{{ +syn keyword algoholFunction + \ QFromAxisAngle + \ QFromEuler + \ QInterpolate + \ QMultQuat + \ QMultVector3 + \ QNormalize + \ QToEuler + \ V3Crossproduct + \ V3Length + \ V3Normalize +" }}} + +" soundCommandsFunction {{{ +syn keyword soundCommandsFunction + \ FadeMusic + \ GetEffectsVolume + \ GetFootVolume + \ GetMasterVolume + \ GetMusicVolume + \ GetVoiceVolume + \ PlayMusicFile + \ SetEffectsVolume + \ SetFootVolume + \ SetMasterVolume + \ SetMusicVolume + \ SetVoiceVolume +" }}} + +" emcFunction {{{ +syn keyword emcFunction + \ emcAddPathToPlaylist + \ emcCreatePlaylist + \ emcGetAllPlaylists + \ emcGetAfterBattleDelay + \ emcGetBattleDelay + \ emcGetEffectsVolume + \ emcGetFadeTime + \ emcGetFootVolume + \ emcGetMasterVolume + \ emcGetMaxRestoreTime + \ emcGetMusicSpeed + \ emcGetMusicType + \ emcGetMusicVolume + \ emcGetPauseTime + \ emcGetPlaylist + \ emcGetPlaylistTracks + \ emcGetTrackName + \ emcGetTrackDuration + \ emcGetTrackPosition + \ emcGetVoiceVolume + \ emcIsBattleOverridden + \ emcIsMusicOnHold + \ emcIsMusicSwitching + \ emcIsPlaylistActive + \ emcMusicNextTrack + \ emcMusicPause + \ emcMusicRestart + \ emcMusicResume + \ emcMusicStop + \ emcPlaylistExists + \ emcPlayTrack + \ emcRestorePlaylist + \ emcSetAfterBattleDelay + \ emcSetBattleDelay + \ emcSetBattleOverride + \ emcSetEffectsVolume + \ emcSetFadeTime + \ emcSetFootVolume + \ emcSetMasterVolume + \ emcSetMaxRestoreTime + \ emcSetMusicHold + \ emcSetMusicSpeed + \ emcSetMusicVolume + \ emcSetPauseTime + \ emcSetPlaylist + \ emcSetTrackPosition + \ emcSetMusicType + \ emcSetVoiceVolume +" }}} + +" vipcxjFunction {{{ +syn keyword vipcxjFunction + \ vcAddMark + \ vcGetFilePath + \ vcGetHairColorRGB + \ vcGetValueNumeric + \ vcGetValueString + \ vcIsMarked + \ vcPrintIni + \ vcSetActorState + \ vcSetHairColor + \ vcSetHairColorRGB + \ vcSetHairColorRGB3P +" }}} + +" cameraCommandsFunction {{{ +syn keyword cameraCommandsFunction + \ CameraGetRef + \ CameraLookAt + \ CameraLookAtPosition + \ CameraMove + \ CameraMoveToPosition + \ CameraReset + \ CameraRotate + \ CameraRotateToPosition + \ CameraSetRef + \ CameraStopLook +" }}} + +" obmeFunction {{{ +syn keyword obmeFunction + \ ClearNthEIBaseCost + \ ClearNthEIEffectName + \ ClearNthEIHandlerParam + \ ClearNthEIHostility + \ ClearNthEIIconPath + \ ClearNthEIResistAV + \ ClearNthEISchool + \ ClearNthEIVFXCode + \ CreateMgef + \ GetMagicEffectHandlerC + \ GetMagicEffectHandlerParamC + \ GetMagicEffectHostilityC + \ GetNthEIBaseCost + \ GetNthEIEffectName + \ GetNthEIHandlerParam + \ GetNthEIHostility + \ GetNthEIIconPath + \ GetNthEIResistAV + \ GetNthEISchool + \ GetNthEIVFXCode + \ ResolveMgefCode + \ SetMagicEffectHandlerC + \ SetMagicEffectHandlerIntParamC + \ SetMagicEffectHandlerRefParamC + \ SetMagicEffectHostilityC + \ SetNthEIBaseCost + \ SetNthEIEffectName + \ SetNthEIHandlerIntParam + \ SetNthEIHandlerRefParam + \ SetNthEIHostility + \ SetNthEIIconPath + \ SetNthEIResistAV + \ SetNthEISchool + \ SetNthEIVFXCode +" }}} + +" conscribeFunction {{{ +syn keyword conscribeFunction + \ DeleteLinesFromLog + \ GetLogLineCount + \ GetRegisteredLogNames + \ ReadFromLog + \ RegisterLog + \ Scribe + \ UnregisterLog +" }}} + +" systemDialogFunction {{{ +syn keyword systemDialogFunction + \ Sysdlg_Browser + \ Sysdlg_ReadBrowser + \ Sysdlg_TextInput +" }}} + +" csiFunction {{{ +syn keyword csiFunction + \ ClearSpellIcon + \ HasAssignedIcon + \ OverwriteSpellIcon + \ SetSpellIcon +" }}} + +" haelFunction {{{ +syn keyword haelFunction + \ GetHUDActiveEffectLimit + \ SetHUDActiveEffectLimit +" }}} + +" lcdFunction {{{ +syn keyword lcdFunction + \ lcd_addinttobuffer + \ lcd_addtexttobuffer + \ lcd_clearrect + \ lcd_cleartextbuffer + \ lcd_close + \ lcd_drawcircle + \ lcd_drawgrid + \ lcd_drawint + \ lcd_drawline + \ lcd_drawprogressbarh + \ lcd_drawprogressbarv + \ lcd_drawprogresscircle + \ lcd_drawrect + \ lcd_drawtext + \ lcd_drawtextbuffer + \ lcd_drawtexture + \ lcd_flush + \ lcd_getbuttonstate + \ lcd_getheight + \ lcd_getwidth + \ lcd_ismulti + \ lcd_isopen + \ lcd_open + \ lcd_refresh + \ lcd_savebuttonsnapshot + \ lcd_scale + \ lcd_setfont +" }}} + +" Deprecated: {{{ +syn keyword obDeprecated + \ SetAltControl + \ GetAltControl + \ RefreshControlMap +" }}} +" }}} + +if !exists("did_obl_inits") + + let did_obl_inits = 1 + hi def link obseStatement Statement + hi def link obseStatementTwo Statement + hi def link obseDescBlock String + hi def link obseComment Comment + hi def link obseString String + hi def link obseStringFormatting Keyword + hi def link obseFloat Float + hi def link obseInt Number + hi def link obseToDo Todo + hi def link obseTypes Type + hi def link obseCondition Conditional + hi def link obseOperator Operator + hi def link obseOtherKey Special + hi def link obseScriptName Special + hi def link obseBlock Conditional + hi def link obseBlockType Structure + hi def link obseScriptNameRegion Underlined + hi def link obseNames Identifier + hi def link obseVariable Identifier + hi def link obseReference Special + hi def link obseRepeat Repeat + + hi def link csFunction Function + hi def link obseFunction Function + hi def link obseArrayFunction Function + hi def link pluggyFunction Function + hi def link obseStringFunction Function + hi def link obseArrayFunction Function + hi def link tsfcFunction Function + hi def link blockheadFunction Function + hi def link switchNightEyeShaderFunction Function + hi def link obseivionReloadedFunction Function + hi def link menuQueFunction Function + hi def link eaxFunction Function + hi def link networkPipeFunction Function + hi def link nifseFunction Function + hi def link reidFunction Function + hi def link runtimeDebuggerFunction Function + hi def link addActorValuesFunction Function + hi def link memoryDumperFunction Function + hi def link algoholFunction Function + hi def link soundCommandsFunction Function + hi def link emcFunction Function + hi def link vipcxjFunction Function + hi def link cameraCommands Function + hi def link obmeFunction Function + hi def link conscribeFunction Function + hi def link systemDialogFunction Function + hi def link csiFunction Function + hi def link haelFunction Function + hi def link lcdFunction Function + hi def link skillAttribute String + hi def link obDeprecated WarningMsg + +endif + +let b:current_syntax = 'obse' + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/openvpn.vim b/runtime/syntax/openvpn.vim new file mode 100644 index 0000000000..02fd24bf39 --- /dev/null +++ b/runtime/syntax/openvpn.vim @@ -0,0 +1,72 @@ +" Vim syntax file +" Language: OpenVPN +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: *.ovpn +" Last Change: 2022 Oct 16 + +if exists('b:current_syntax') + finish +endif + +let s:cpo_save = &cpoptions +set cpoptions&vim + +" Options +syntax match openvpnOption /^[a-z-]\+/ + \ skipwhite nextgroup=openvpnArgList +syntax match openvpnArgList /.*$/ transparent contained + \ contains=openvpnArgument,openvpnNumber, + \ openvpnIPv4Address,openvpnIPv6Address, + \ openvpnSignal,openvpnComment + +" Arguments +syntax match openvpnArgument /[^\\"' \t]\+/ + \ contained contains=openvpnEscape +syntax region openvpnArgument matchgroup=openvpnQuote + \ start=/"/ skip=/\\"/ end=/"/ + \ oneline contained contains=openvpnEscape +syntax region openvpnArgument matchgroup=openvpnQuote + \ start=/'/ skip=/\\'/ end=/'/ + \ oneline contained +syntax match openvpnEscape /\\[\\" \t]/ contained + +" Numbers +syntax match openvpnNumber /\<[1-9][0-9]*\(\.[0-9]\+\)\?\>/ contained + +" Signals +syntax match openvpnSignal /SIG\(HUP\|INT\|TERM\|USER[12]\)/ contained + +" IP addresses +syntax match openvpnIPv4Address /\(\d\{1,3}\.\)\{3}\d\{1,3}/ + \ contained nextgroup=openvpnSlash +syntax match openvpnIPv6Address /\([A-F0-9]\{1,4}:\)\{7}\[A-F0-9]\{1,4}/ + \ contained nextgroup=openvpnSlash +syntax match openvpnSlash "/" contained + \ nextgroup=openvpnIPv4Address,openvpnIPv6Address,openvpnNumber + +" Inline files +syntax region openvpnInline matchgroup=openvpnTag + \ start=+^<\z([a-z-]\+\)>+ end=+^</\z1>+ + +" Comments +syntax keyword openvpnTodo contained TODO FIXME NOTE XXX +syntax match openvpnComment /^[;#].*$/ contains=openvpnTodo +syntax match openvpnComment /\s\+\zs[;#].*$/ contains=openvpnTodo + +hi def link openvpnArgument String +hi def link openvpnComment Comment +hi def link openvpnEscape SpecialChar +hi def link openvpnIPv4Address Constant +hi def link openvpnIPv6Address Constant +hi def link openvpnNumber Number +hi def link openvpnOption Keyword +hi def link openvpnQuote Quote +hi def link openvpnSignal Special +hi def link openvpnSlash Delimiter +hi def link openvpnTag Tag +hi def link openvpnTodo Todo + +let b:current_syntax = 'openvpn' + +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/poefilter.vim b/runtime/syntax/poefilter.vim new file mode 100644 index 0000000000..f7e92034ee --- /dev/null +++ b/runtime/syntax/poefilter.vim @@ -0,0 +1,167 @@ +" Vim syntax file +" Language: PoE item filter +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: *.filter +" Last Change: 2022 Oct 07 + +if exists('b:current_syntax') + finish +endif + +let s:cpo_save = &cpoptions +set cpoptions&vim + +" Comment +syn keyword poefilterTodo TODO NOTE XXX contained +syn match poefilterCommentTag /\[[0-9A-Z\[\]]\+\]/ contained +syn match poefilterComment /#.*$/ contains=poefilterTodo,poefilterCommentTag,@Spell + +" Blocks +syn keyword poefilterBlock Show Hide + +" Conditions +syn keyword poefilterCondition + \ AlternateQuality + \ AnyEnchantment + \ BlightedMap + \ Corrupted + \ ElderItem + \ ElderMap + \ FracturedItem + \ Identified + \ Mirrored + \ Replica + \ Scourged + \ ShapedMap + \ ShaperItem + \ SynthesisedItem + \ UberBlightedMap + \ skipwhite nextgroup=poefilterBoolean +syn keyword poefilterCondition + \ ArchnemesisMod + \ BaseType + \ Class + \ EnchantmentPassiveNode + \ HasEnchantment + \ HasExplicitMod + \ ItemLevel + \ SocketGroup + \ Sockets + \ skipwhite nextgroup=poefilterOperator,poefilterString +syn keyword poefilterCondition + \ AreaLevel + \ BaseArmour + \ BaseDefencePercentile + \ BaseEnergyShield + \ BaseEvasion + \ BaseWard + \ CorruptedMods + \ DropLevel + \ EnchantmentPassiveNum + \ GemLevel + \ HasEaterOfWorldsImplicit + \ HasSearingExarchImplicit + \ Height + \ LinkedSockets + \ MapTier + \ Quality + \ StackSize + \ Width + \ skipwhite nextgroup=poefilterOperator,poefilterNumber +syn keyword poefilterCondition + \ GemQualityType + \ skipwhite nextgroup=poefilterString,poefilterQuality +syn keyword poefilterCondition + \ HasInfluence + \ skipwhite nextgroup=poefilterString,poefilterInfluence +syn keyword poefilterCondition + \ Rarity + \ skipwhite nextgroup=poefilterString,poefilterRarity + +" Actions +syn keyword poefilterAction + \ PlayAlertSound + \ PlayAlertSoundPositional + \ skipwhite nextgroup=poefilterNumber,poefilterDisable +syn keyword poefilterAction + \ CustomAlertSound + \ CustomAlertSoundOptional + \ skipwhite nextgroup=poefilterString +syn keyword poefilterAction + \ DisableDropSound + \ EnableDropSound + \ DisableDropSoundIfAlertSound + \ EnableDropSoundIfAlertSound + \ skipwhite nextgroup=poefilterBoolean +syn keyword poefilterAction + \ MinimapIcon + \ SetBackgroundColor + \ SetBorderColor + \ SetFontSize + \ SetTextColor + \ skipwhite nextgroup=poefilterNumber +syn keyword poefilterAction + \ PlayEffect + \ skipwhite nextgroup=poefilterColour + +" Operators +syn match poefilterOperator /!\|[<>=]=\?/ contained + \ skipwhite nextgroup=poefilterString,poefilterNumber, + \ poefilterQuality,poefilterRarity,poefilterInfluence + +" Arguments +syn match poefilterString /[-a-zA-Z0-9:,']/ contained contains=@Spell + \ skipwhite nextgroup=poefilterString,poefilterNumber, + \ poefilterQuality,poefilterRarity,poefilterInfluence +syn region poefilterString matchgroup=poefilterQuote keepend + \ start=/"/ end=/"/ concealends contained contains=@Spell + \ skipwhite nextgroup=poefilterString,poefilterNumber, + \ poefilterQuality,poefilterRarity,poefilterInfluence +syn match poefilterNumber /-1\|0\|[1-9][0-9]*/ contained + \ skipwhite nextgroup=poefilterString,poefilterNumber, + \ poefilterQuality,poefilterRarity,poefilterInfluence,poefilterColour +syn keyword poefilterBoolean True False contained + +" Special arguments (conditions) +syn keyword poefilterQuality Superior Divergent Anomalous Phantasmal + \ contained skipwhite nextgroup=poefilterString,poefilterQuality +syn keyword poefilterRarity Normal Magic Rare Unique + \ contained skipwhite nextgroup=poefilterString,poefilterRarity +syn keyword poefilterInfluence Shaper Elder + \ Crusader Hunter Redeemer Warlord None + \ contained skipwhite nextgroup=poefilterString,poefilterInfluence + +" Special arguments (actions) +syn keyword poefilterColour Red Green Blue Brown + \ White Yellow Cyan Grey Orange Pink Purple + \ contained skipwhite nextgroup=poefilterShape,poefilterTemp +syn keyword poefilterShape Circle Diamond Hecagon Square Star Triangle + \ Cross Moon Raindrop Kite Pentagon UpsideDownHouse contained +syn keyword poefilterDisable None contained +syn keyword poefilterTemp Temp contained + +" Colours + +hi def link poefilterAction Statement +hi def link poefilterBlock Structure +hi def link poefilterBoolean Boolean +hi def link poefilterColour Special +hi def link poefilterComment Comment +hi def link poefilterCommentTag SpecialComment +hi def link poefilterCondition Conditional +hi def link poefilterDisable Constant +hi def link poefilterInfluence Special +hi def link poefilterNumber Number +hi def link poefilterOperator Operator +hi def link poefilterQuality Special +hi def link poefilterQuote Delimiter +hi def link poefilterRarity Special +hi def link poefilterShape Special +hi def link poefilterString String +hi def link poefilterTemp StorageClass +hi def link poefilterTodo Todo + +let b:current_syntax = 'poefilter' + +let &cpoptions = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/ptcap.vim b/runtime/syntax/ptcap.vim index 1ebeb5227b..5db7bda896 100644 --- a/runtime/syntax/ptcap.vim +++ b/runtime/syntax/ptcap.vim @@ -53,7 +53,7 @@ syn match ptcapNumberError "#0x\x*[^[:xdigit:]:\\]"lc=1 contained " The `=' operator assigns a string to the preceding flag syn match ptcapOperator "[@#=]" contained -" Some terminal capabilites have special names like `#5' and `@1', and we +" Some terminal capabilities have special names like `#5' and `@1', and we " need special rules to match these properly syn match ptcapSpecialCap "\W[#@]\d" contains=ptcapDelimiter contained 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/rego.vim b/runtime/syntax/rego.vim index a04fc7007b..bc82030488 100644 --- a/runtime/syntax/rego.vim +++ b/runtime/syntax/rego.vim @@ -2,7 +2,7 @@ " Language: rego policy language " Maintainer: Matt Dunford (zenmatic@gmail.com) " URL: https://github.com/zenmatic/vim-syntax-rego -" Last Change: 2019 Dec 12 +" Last Change: 2022 Dec 4 " https://www.openpolicyagent.org/docs/latest/policy-language/ @@ -14,36 +14,56 @@ endif syn case match syn keyword regoDirective package import allow deny -syn keyword regoKeywords as default else false not null true with some +syn keyword regoKeywords as default else every false if import package not null true with some in print syn keyword regoFuncAggregates count sum product max min sort all any -syn match regoFuncArrays "\<array\.\(concat\|slice\)\>" +syn match regoFuncArrays "\<array\.\(concat\|slice\|reverse\)\>" syn keyword regoFuncSets intersection union -syn keyword regoFuncStrings concat /\<contains\>/ endswith format_int indexof lower replace split sprintf startswith substring trim trim_left trim_prefix trim_right trim_suffix trim_space upper -syn match regoFuncStrings2 "\<strings\.replace_n\>" +syn keyword regoFuncStrings concat /\<contains\>/ endswith format_int indexof indexof_n lower replace split sprintf startswith substring trim trim_left trim_prefix trim_right trim_suffix trim_space upper +syn match regoFuncStrings2 "\<strings\.\(replace_n\|reverse\|any_prefix_match\|any_suffix_match\)\>" syn match regoFuncStrings3 "\<contains\>" syn keyword regoFuncRegex re_match -syn match regoFuncRegex2 "\<regex\.\(split\|globs_match\|template_match\|find_n\|find_all_string_submatch_n\)\>" +syn match regoFuncRegex2 "\<regex\.\(is_valid\|split\|globs_match\|template_match\|find_n\|find_all_string_submatch_n\|replace\)\>" +syn match regoFuncUuid "\<uuid.rfc4122\>" +syn match regoFuncBits "\<bits\.\(or\|and\|negate\|xor\|lsh\|rsh\)\>" +syn match regoFuncObject "\<object\.\(get\|remove\|subset\|union\|union_n\|filter\)\>" syn match regoFuncGlob "\<glob\.\(match\|quote_meta\)\>" -syn match regoFuncUnits "\<units\.parse_bytes\>" +syn match regoFuncUnits "\<units\.parse\(_bytes\)\=\>" syn keyword regoFuncTypes is_number is_string is_boolean is_array is_set is_object is_null type_name -syn match regoFuncEncoding1 "\<\(base64\|base64url\)\.\(encode\|decode\)\>" -syn match regoFuncEncoding2 "\<urlquery\.\(encode\|decode\|encode_object\)\>" -syn match regoFuncEncoding3 "\<\(json\|yaml\)\.\(marshal\|unmarshal\)\>" +syn match regoFuncEncoding1 "\<base64\.\(encode\|decode\|is_valid\)\>" +syn match regoFuncEncoding2 "\<base64url\.\(encode\(_no_pad\)\=\|decode\)\>" +syn match regoFuncEncoding3 "\<urlquery\.\(encode\|decode\|\(en\|de\)code_object\)\>" +syn match regoFuncEncoding4 "\<\(json\|yaml\)\.\(is_valid\|marshal\|unmarshal\)\>" +syn match regoFuncEncoding5 "\<json\.\(filter\|patch\|remove\)\>" syn match regoFuncTokenSigning "\<io\.jwt\.\(encode_sign_raw\|encode_sign\)\>" -syn match regoFuncTokenVerification "\<io\.jwt\.\(verify_rs256\|verify_ps256\|verify_es256\|verify_hs256\|decode\|decode_verify\)\>" -syn match regoFuncTime "\<time\.\(now_ns\|parse_ns\|parse_rfc3339_ns\|parse_duration_ns\|date\|clock\|weekday\)\>" -syn match regoFuncCryptography "\<crypto\.x509\.parse_certificates\>" +syn match regoFuncTokenVerification1 "\<io\.jwt\.\(decode\|decode_verify\)\>" +syn match regoFuncTokenVerification2 "\<io\.jwt\.verify_\(rs\|ps\|es\|hs\)\(256\|384\|512\)\>" +syn match regoFuncTime "\<time\.\(now_ns\|parse_ns\|parse_rfc3339_ns\|parse_duration_ns\|date\|clock\|weekday\|diff\|add_date\)\>" +syn match regoFuncCryptography "\<crypto\.x509\.\(parse_certificates\|parse_certificate_request\|parse_and_verify_certificates\|parse_rsa_private_key\)\>" +syn match regoFuncCryptography "\<crypto\.\(md5\|sha1\|sha256\)" +syn match regoFuncCryptography "\<crypto\.hmac\.\(md5\|sha1\|sha256\|sha512\)" syn keyword regoFuncGraphs walk +syn match regoFuncGraphs2 "\<graph\.reachable\(_paths\)\=\>" +syn match regoFuncGraphQl "\<graphql\.\(\(schema_\)\=is_valid\|parse\(_\(and_verify\|query\|schema\)\)\=\)\>" syn match regoFuncHttp "\<http\.send\>" -syn match regoFuncNet "\<net\.\(cidr_contains\|cidr_intersects\)\>" -syn match regoFuncRego "\<rego\.parse_module\>" +syn match regoFuncNet "\<net\.\(cidr_merge\|cidr_contains\|cidr_contains_matches\|cidr_intersects\|cidr_expand\|lookup_ip_addr\|cidr_is_valid\)\>" +syn match regoFuncRego "\<rego\.\(parse_module\|metadata\.\(rule\|chain\)\)\>" syn match regoFuncOpa "\<opa\.runtime\>" syn keyword regoFuncDebugging trace +syn match regoFuncRand "\<rand\.intn\>" +syn match regoFuncNumbers "\<numbers\.\(range\|intn\)\>" +syn keyword regoFuncNumbers round ceil floor abs + +syn match regoFuncSemver "\<semver\.\(is_valid\|compare\)\>" +syn keyword regoFuncConversions to_number +syn match regoFuncHex "\<hex\.\(encode\|decode\)\>" + +hi def link regoFuncUuid Statement +hi def link regoFuncBits Statement hi def link regoDirective Statement hi def link regoKeywords Statement hi def link regoFuncAggregates Statement @@ -60,16 +80,27 @@ hi def link regoFuncTypes Statement hi def link regoFuncEncoding1 Statement hi def link regoFuncEncoding2 Statement hi def link regoFuncEncoding3 Statement +hi def link regoFuncEncoding4 Statement +hi def link regoFuncEncoding5 Statement hi def link regoFuncTokenSigning Statement -hi def link regoFuncTokenVerification Statement +hi def link regoFuncTokenVerification1 Statement +hi def link regoFuncTokenVerification2 Statement hi def link regoFuncTime Statement hi def link regoFuncCryptography Statement hi def link regoFuncGraphs Statement +hi def link regoFuncGraphQl Statement +hi def link regoFuncGraphs2 Statement hi def link regoFuncHttp Statement hi def link regoFuncNet Statement hi def link regoFuncRego Statement hi def link regoFuncOpa Statement hi def link regoFuncDebugging Statement +hi def link regoFuncObject Statement +hi def link regoFuncNumbers Statement +hi def link regoFuncSemver Statement +hi def link regoFuncConversions Statement +hi def link regoFuncHex Statement +hi def link regoFuncRand Statement " https://www.openpolicyagent.org/docs/latest/policy-language/#strings syn region regoString start=+"+ skip=+\\\\\|\\"+ end=+"+ diff --git a/runtime/syntax/sed.vim b/runtime/syntax/sed.vim index 63b39db81f..d1f631df4b 100644 --- a/runtime/syntax/sed.vim +++ b/runtime/syntax/sed.vim @@ -1,30 +1,42 @@ " Vim syntax file -" Language: sed -" Maintainer: Haakon Riiser <hakonrk@fys.uio.no> -" URL: http://folk.uio.no/hakonrk/vim/syntax/sed.vim -" Last Change: 2010 May 29 +" Language: sed +" Maintainer: Doug Kearns <dougkearns@gmail.com> +" Previous Maintainer: Haakon Riiser <hakonrk@fys.uio.no> +" Contributor: Jack Haden-Enneking +" Last Change: 2022 Oct 15 " quit when a syntax file was already loaded if exists("b:current_syntax") - finish + finish endif +syn keyword sedTodo contained TODO FIXME XXX + syn match sedError "\S" syn match sedWhitespace "\s\+" contained syn match sedSemicolon ";" syn match sedAddress "[[:digit:]$]" syn match sedAddress "\d\+\~\d\+" -syn region sedAddress matchgroup=Special start="[{,;]\s*/\(\\/\)\="lc=1 skip="[^\\]\(\\\\\)*\\/" end="/I\=" contains=sedTab,sedRegexpMeta -syn region sedAddress matchgroup=Special start="^\s*/\(\\/\)\=" skip="[^\\]\(\\\\\)*\\/" end="/I\=" contains=sedTab,sedRegexpMeta -syn match sedComment "^\s*#.*$" -syn match sedFunction "[dDgGhHlnNpPqQx=]\s*\($\|;\)" contains=sedSemicolon,sedWhitespace +syn region sedAddress matchgroup=Special start="[{,;]\s*/\%(\\/\)\="lc=1 skip="[^\\]\%(\\\\\)*\\/" end="/I\=" contains=sedTab,sedRegexpMeta +syn region sedAddress matchgroup=Special start="^\s*/\%(\\/\)\=" skip="[^\\]\%(\\\\\)*\\/" end="/I\=" contains=sedTab,sedRegexpMeta +syn match sedFunction "[dDgGhHlnNpPqQx=]\s*\%($\|;\)" contains=sedSemicolon,sedWhitespace +if exists("g:sed_dialect") && g:sed_dialect ==? "bsd" + syn match sedComment "^\s*#.*$" contains=sedTodo +else + syn match sedFunction "[dDgGhHlnNpPqQx=]\s*\ze#" contains=sedSemicolon,sedWhitespace + syn match sedComment "#.*$" contains=sedTodo +endif syn match sedLabel ":[^;]*" -syn match sedLineCont "^\(\\\\\)*\\$" contained -syn match sedLineCont "[^\\]\(\\\\\)*\\$"ms=e contained +syn match sedLineCont "^\%(\\\\\)*\\$" contained +syn match sedLineCont "[^\\]\%(\\\\\)*\\$"ms=e contained syn match sedSpecial "[{},!]" -if exists("highlight_sedtabs") - syn match sedTab "\t" contained + +" continue to silently support the old name +let s:highlight_tabs = v:false +if exists("g:highlight_sedtabs") || get(g:, "sed_highlight_tabs", 0) + let s:highlight_tabs = v:true + syn match sedTab "\t" contained endif " Append/Change/Insert @@ -34,39 +46,39 @@ syn region sedBranch matchgroup=sedFunction start="[bt]" matchgroup=sedSemicolon syn region sedRW matchgroup=sedFunction start="[rw]" matchgroup=sedSemicolon end=";\|$" contains=sedWhitespace " Substitution/transform with various delimiters -syn region sedFlagwrite matchgroup=sedFlag start="w" matchgroup=sedSemicolon end=";\|$" contains=sedWhitespace contained -syn match sedFlag "[[:digit:]gpI]*w\=" contains=sedFlagwrite contained +syn region sedFlagWrite matchgroup=sedFlag start="w" matchgroup=sedSemicolon end=";\|$" contains=sedWhitespace contained +syn match sedFlag "[[:digit:]gpI]*w\=" contains=sedFlagWrite contained syn match sedRegexpMeta "[.*^$]" contained syn match sedRegexpMeta "\\." contains=sedTab contained syn match sedRegexpMeta "\[.\{-}\]" contains=sedTab contained syn match sedRegexpMeta "\\{\d\*,\d*\\}" contained -syn match sedRegexpMeta "\\(.\{-}\\)" contains=sedTab contained -syn match sedReplaceMeta "&\|\\\($\|.\)" contains=sedTab contained +syn match sedRegexpMeta "\\%(.\{-}\\)" contains=sedTab contained +syn match sedReplaceMeta "&\|\\\%($\|.\)" contains=sedTab contained " Metacharacters: $ * . \ ^ [ ~ " @ is used as delimiter and treated on its own below -let __at = char2nr("@") -let __sed_i = char2nr(" ") " ASCII: 32, EBCDIC: 64 +let s:at = char2nr("@") +let s:i = char2nr(" ") " ASCII: 32, EBCDIC: 64 if has("ebcdic") - let __sed_last = 255 + let s:last = 255 else - let __sed_last = 126 + let s:last = 126 endif -let __sed_metacharacters = '$*.\^[~' -while __sed_i <= __sed_last - let __sed_delimiter = escape(nr2char(__sed_i), __sed_metacharacters) - if __sed_i != __at - exe 'syn region sedAddress matchgroup=Special start=@\\'.__sed_delimiter.'\(\\'.__sed_delimiter.'\)\=@ skip=@[^\\]\(\\\\\)*\\'.__sed_delimiter.'@ end=@'.__sed_delimiter.'I\=@ contains=sedTab' - exe 'syn region sedRegexp'.__sed_i 'matchgroup=Special start=@'.__sed_delimiter.'\(\\\\\|\\'.__sed_delimiter.'\)*@ skip=@[^\\'.__sed_delimiter.']\(\\\\\)*\\'.__sed_delimiter.'@ end=@'.__sed_delimiter.'@me=e-1 contains=sedTab,sedRegexpMeta keepend contained nextgroup=sedReplacement'.__sed_i - exe 'syn region sedReplacement'.__sed_i 'matchgroup=Special start=@'.__sed_delimiter.'\(\\\\\|\\'.__sed_delimiter.'\)*@ skip=@[^\\'.__sed_delimiter.']\(\\\\\)*\\'.__sed_delimiter.'@ end=@'.__sed_delimiter.'@ contains=sedTab,sedReplaceMeta keepend contained nextgroup=sedFlag' - endif - let __sed_i = __sed_i + 1 +let s:metacharacters = '$*.\^[~' +while s:i <= s:last + let s:delimiter = escape(nr2char(s:i), s:metacharacters) + if s:i != s:at + exe 'syn region sedAddress matchgroup=Special start=@\\'.s:delimiter.'\%(\\'.s:delimiter.'\)\=@ skip=@[^\\]\%(\\\\\)*\\'.s:delimiter.'@ end=@'.s:delimiter.'[IM]\=@ contains=sedTab' + exe 'syn region sedRegexp'.s:i 'matchgroup=Special start=@'.s:delimiter.'\%(\\\\\|\\'.s:delimiter.'\)*@ skip=@[^\\'.s:delimiter.']\%(\\\\\)*\\'.s:delimiter.'@ end=@'.s:delimiter.'@me=e-1 contains=sedTab,sedRegexpMeta keepend contained nextgroup=sedReplacement'.s:i + exe 'syn region sedReplacement'.s:i 'matchgroup=Special start=@'.s:delimiter.'\%(\\\\\|\\'.s:delimiter.'\)*@ skip=@[^\\'.s:delimiter.']\%(\\\\\)*\\'.s:delimiter.'@ end=@'.s:delimiter.'@ contains=sedTab,sedReplaceMeta keepend contained nextgroup=@sedFlags' + endif + let s:i = s:i + 1 endwhile -syn region sedAddress matchgroup=Special start=+\\@\(\\@\)\=+ skip=+[^\\]\(\\\\\)*\\@+ end=+@I\=+ contains=sedTab,sedRegexpMeta -syn region sedRegexp64 matchgroup=Special start=+@\(\\\\\|\\@\)*+ skip=+[^\\@]\(\\\\\)*\\@+ end=+@+me=e-1 contains=sedTab,sedRegexpMeta keepend contained nextgroup=sedReplacement64 -syn region sedReplacement64 matchgroup=Special start=+@\(\\\\\|\\@\)*+ skip=+[^\\@]\(\\\\\)*\\@+ end=+@+ contains=sedTab,sedReplaceMeta keepend contained nextgroup=sedFlag +syn region sedAddress matchgroup=Special start=+\\@\%(\\@\)\=+ skip=+[^\\]\%(\\\\\)*\\@+ end=+@I\=+ contains=sedTab,sedRegexpMeta +syn region sedRegexp64 matchgroup=Special start=+@\%(\\\\\|\\@\)*+ skip=+[^\\@]\%(\\\\\)*\\@+ end=+@+me=e-1 contains=sedTab,sedRegexpMeta keepend contained nextgroup=sedReplacement64 +syn region sedReplacement64 matchgroup=Special start=+@\%(\\\\\|\\@\)*+ skip=+[^\\@]\%(\\\\\)*\\@+ end=+@+ contains=sedTab,sedReplaceMeta keepend contained nextgroup=sedFlag -" Since the syntax for the substituion command is very similar to the +" Since the syntax for the substitution command is very similar to the " syntax for the transform command, I use the same pattern matching " for both commands. There is one problem -- the transform command " (y) does not allow any flags. To save memory, I ignore this problem. @@ -80,7 +92,7 @@ hi def link sedComment Comment hi def link sedDelete Function hi def link sedError Error hi def link sedFlag Type -hi def link sedFlagwrite Constant +hi def link sedFlagWrite Constant hi def link sedFunction Function hi def link sedLabel Label hi def link sedLineCont Special @@ -88,23 +100,24 @@ hi def link sedPutHoldspc Function hi def link sedReplaceMeta Special hi def link sedRegexpMeta Special hi def link sedRW Constant -hi def link sedSemicolon Special +hi def link sedSemicolon Special hi def link sedST Function hi def link sedSpecial Special +hi def link sedTodo Todo hi def link sedWhitespace NONE -if exists("highlight_sedtabs") -hi def link sedTab Todo +if s:highlight_tabs + hi def link sedTab Todo endif -let __sed_i = char2nr(" ") " ASCII: 32, EBCDIC: 64 -while __sed_i <= __sed_last -exe "hi def link sedRegexp".__sed_i "Macro" -exe "hi def link sedReplacement".__sed_i "NONE" -let __sed_i = __sed_i + 1 +let s:i = char2nr(" ") " ASCII: 32, EBCDIC: 64 +while s:i <= s:last + exe "hi def link sedRegexp".s:i "Macro" + exe "hi def link sedReplacement".s:i "NONE" + let s:i = s:i + 1 endwhile - -unlet __sed_i __sed_last __sed_delimiter __sed_metacharacters +unlet s:i s:last s:delimiter s:metacharacters s:at +unlet s:highlight_tabs let b:current_syntax = "sed" -" vim: sts=4 sw=4 ts=8 +" vim: nowrap sw=2 sts=2 ts=8 noet: diff --git a/runtime/syntax/sh.vim b/runtime/syntax/sh.vim index e44699faa5..6722d62c89 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: Nov 25, 2022 +" Version: 204 " 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 @@ -84,15 +84,9 @@ elseif g:sh_fold_enabled != 0 && !has("folding") let g:sh_fold_enabled= 0 echomsg "Ignoring g:sh_fold_enabled=".g:sh_fold_enabled."; need to re-compile vim for +fold support" endif -if !exists("s:sh_fold_functions") - let s:sh_fold_functions= and(g:sh_fold_enabled,1) -endif -if !exists("s:sh_fold_heredoc") - let s:sh_fold_heredoc = and(g:sh_fold_enabled,2) -endif -if !exists("s:sh_fold_ifdofor") - let s:sh_fold_ifdofor = and(g:sh_fold_enabled,4) -endif +let s:sh_fold_functions= and(g:sh_fold_enabled,1) +let s:sh_fold_heredoc = and(g:sh_fold_enabled,2) +let s:sh_fold_ifdofor = and(g:sh_fold_enabled,4) if g:sh_fold_enabled && &fdm == "manual" " Given that the user provided g:sh_fold_enabled " AND g:sh_fold_enabled is manual (usual default) @@ -113,6 +107,9 @@ endif " Set up folding commands for shell {{{1 " ================================= +sil! delc ShFoldFunctions +sil! delc ShFoldHereDoc +sil! delc ShFoldIfDoFor if s:sh_fold_functions com! -nargs=* ShFoldFunctions <args> fold else @@ -141,7 +138,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 @@ -415,22 +412,22 @@ syn match shBQComment contained "#.\{-}\ze`" contains=@shCommentGroup " Here Documents: {{{1 " (modified by Felipe Contreras) " ========================================= -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc01 start="<<\s*\z([^ \t|>]\+\)" matchgroup=shHereDoc01 end="^\z1\s*$" contains=@shDblQuoteList -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc02 start="<<-\s*\z([^ \t|>]\+\)" matchgroup=shHereDoc02 end="^\s*\z1\s*$" contains=@shDblQuoteList -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc03 start="<<\s*\\\z([^ \t|>]\+\)" matchgroup=shHereDoc03 end="^\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc04 start="<<-\s*\\\z([^ \t|>]\+\)" matchgroup=shHereDoc04 end="^\s*\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc05 start="<<\s*'\z([^']\+\)'" matchgroup=shHereDoc05 end="^\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc06 start="<<-\s*'\z([^']\+\)'" matchgroup=shHereDoc06 end="^\s*\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc07 start="<<\s*\"\z([^"]\+\)\"" matchgroup=shHereDoc07 end="^\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc08 start="<<-\s*\"\z([^"]\+\)\"" matchgroup=shHereDoc08 end="^\s*\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc09 start="<<\s*\\\_$\_s*\z([^ \t|>]\+\)" matchgroup=shHereDoc09 end="^\z1\s*$" contains=@shDblQuoteList -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc10 start="<<-\s*\\\_$\_s*\z([^ \t|>]\+\)" matchgroup=shHereDoc10 end="^\s*\z1\s*$" contains=@shDblQuoteList -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc11 start="<<\s*\\\_$\_s*\\\z([^ \t|>]\+\)" matchgroup=shHereDoc11 end="^\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc12 start="<<-\s*\\\_$\_s*\\\z([^ \t|>]\+\)" matchgroup=shHereDoc12 end="^\s*\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc13 start="<<\s*\\\_$\_s*'\z([^']\+\)'" matchgroup=shHereDoc13 end="^\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc14 start="<<-\s*\\\_$\_s*'\z([^']\+\)'" matchgroup=shHereDoc14 end="^\s*\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc15 start="<<\s*\\\_$\_s*\"\z([^"]\+\)\"" matchgroup=shHereDoc15 end="^\z1\s*$" -ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc16 start="<<-\s*\\\_$\_s*\"\z([^"]\+\)\"" matchgroup=shHereDoc16 end="^\s*\z1\s*$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc01 start="<<\s*\z([^ \t|>]\+\)" matchgroup=shHereDoc01 end="^\z1$" contains=@shDblQuoteList +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc02 start="<<-\s*\z([^ \t|>]\+\)" matchgroup=shHereDoc02 end="^\s*\z1$" contains=@shDblQuoteList +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc03 start="<<\s*\\\z([^ \t|>]\+\)" matchgroup=shHereDoc03 end="^\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc04 start="<<-\s*\\\z([^ \t|>]\+\)" matchgroup=shHereDoc04 end="^\s*\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc05 start="<<\s*'\z([^']\+\)'" matchgroup=shHereDoc05 end="^\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc06 start="<<-\s*'\z([^']\+\)'" matchgroup=shHereDoc06 end="^\s*\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc07 start="<<\s*\"\z([^"]\+\)\"" matchgroup=shHereDoc07 end="^\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc08 start="<<-\s*\"\z([^"]\+\)\"" matchgroup=shHereDoc08 end="^\s*\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc09 start="<<\s*\\\_$\_s*\z([^ \t|>]\+\)" matchgroup=shHereDoc09 end="^\z1$" contains=@shDblQuoteList +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc10 start="<<-\s*\\\_$\_s*\z([^ \t|>]\+\)" matchgroup=shHereDoc10 end="^\s*\z1$" contains=@shDblQuoteList +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc11 start="<<\s*\\\_$\_s*\\\z([^ \t|>]\+\)" matchgroup=shHereDoc11 end="^\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc12 start="<<-\s*\\\_$\_s*\\\z([^ \t|>]\+\)" matchgroup=shHereDoc12 end="^\s*\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc13 start="<<\s*\\\_$\_s*'\z([^']\+\)'" matchgroup=shHereDoc13 end="^\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc14 start="<<-\s*\\\_$\_s*'\z([^']\+\)'" matchgroup=shHereDoc14 end="^\s*\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc15 start="<<\s*\\\_$\_s*\"\z([^"]\+\)\"" matchgroup=shHereDoc15 end="^\z1$" +ShFoldHereDoc syn region shHereDoc matchgroup=shHereDoc16 start="<<-\s*\\\_$\_s*\"\z([^"]\+\)\"" matchgroup=shHereDoc16 end="^\s*\z1$" " Here Strings: {{{1 diff --git a/runtime/syntax/shared/hgcommitDiff.vim b/runtime/syntax/shared/hgcommitDiff.vim new file mode 100644 index 0000000000..949cdf0b1c --- /dev/null +++ b/runtime/syntax/shared/hgcommitDiff.vim @@ -0,0 +1,390 @@ +" Vim syntax file +" Language: Sapling / Mecurial Diff (context or unified) +" Maintainer: Max Coplan <mchcopl@gmail.com> +" Translations by Jakson Alves de Aquino. +" Last Change: 2022-12-08 +" Copied from: runtime/syntax/diff.vim + +" Quit when a (custom) syntax file was already loaded +if exists("b:current_syntax") + finish +endif +scriptencoding utf-8 + +syn match hgDiffOnly "^\%(SL\|HG\): Only in .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Files .* and .* are identical$" +syn match hgDiffDiffer "^\%(SL\|HG\): Files .* and .* differ$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binary files .* and .* differ$" +syn match hgDiffIsA "^\%(SL\|HG\): File .* is a .* while file .* is a .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ No newline at end of file .*" +syn match hgDiffCommon "^\%(SL\|HG\): Common subdirectories: .*" + +" Disable the translations by setting diff_translations to zero. +if !exists("diff_translations") || diff_translations + +" ca +syn match hgDiffOnly "^\%(SL\|HG\): Només a .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Els fitxers .* i .* són idèntics$" +syn match hgDiffDiffer "^\%(SL\|HG\): Els fitxers .* i .* difereixen$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Els fitxers .* i .* difereixen$" +syn match hgDiffIsA "^\%(SL\|HG\): El fitxer .* és un .* mentre que el fitxer .* és un .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ No hi ha cap carà cter de salt de lÃnia al final del fitxer" +syn match hgDiffCommon "^\%(SL\|HG\): Subdirectoris comuns: .* i .*" + +" cs +syn match hgDiffOnly "^\%(SL\|HG\): Pouze v .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Soubory .* a .* jsou identické$" +syn match hgDiffDiffer "^\%(SL\|HG\): Soubory .* a .* jsou různé$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binárnà soubory .* a .* jsou rozdÃlné$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Soubory .* a .* jsou různé$" +syn match hgDiffIsA "^\%(SL\|HG\): Soubor .* je .* pokud soubor .* je .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Chybà znak konce řádku na konci souboru" +syn match hgDiffCommon "^\%(SL\|HG\): SpoleÄné podadresáře: .* a .*" + +" da +syn match hgDiffOnly "^\%(SL\|HG\): Kun i .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Filerne .* og .* er identiske$" +syn match hgDiffDiffer "^\%(SL\|HG\): Filerne .* og .* er forskellige$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binære filer .* og .* er forskellige$" +syn match hgDiffIsA "^\%(SL\|HG\): Filen .* er en .* mens filen .* er en .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Intet linjeskift ved filafslutning" +syn match hgDiffCommon "^\%(SL\|HG\): Identiske underkataloger: .* og .*" + +" de +syn match hgDiffOnly "^\%(SL\|HG\): Nur in .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Dateien .* und .* sind identisch.$" +syn match hgDiffDiffer "^\%(SL\|HG\): Dateien .* und .* sind verschieden.$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binärdateien .* and .* sind verschieden.$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binärdateien .* und .* sind verschieden.$" +syn match hgDiffIsA "^\%(SL\|HG\): Datei .* ist ein .* während Datei .* ein .* ist.$" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Kein Zeilenumbruch am Dateiende." +syn match hgDiffCommon "^\%(SL\|HG\): Gemeinsame Unterverzeichnisse: .* und .*.$" + +" el +syn match hgDiffOnly "^\%(SL\|HG\): Μόνο στο .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Τα αÏχεία .* καί .* είναι πανομοιότυπα$" +syn match hgDiffDiffer "^\%(SL\|HG\): Τα αÏχεία .* και .* διαφÎÏουν$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Τα αÏχεία .* και .* διαφÎÏουν$" +syn match hgDiffIsA "^\%(SL\|HG\): Το αÏχείο .* είναι .* ενώ το αÏχείο .* είναι .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Δεν υπάÏχει χαÏακτήÏας νÎας γÏαμμής στο Ï„Îλος του αÏχείου" +syn match hgDiffCommon "^\%(SL\|HG\): Οι υποκατάλογοι .* και .* είναι ταυτόσημοι$" + +" eo +syn match hgDiffOnly "^\%(SL\|HG\): Nur en .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Dosieroj .* kaj .* estas samaj$" +syn match hgDiffDiffer "^\%(SL\|HG\): Dosieroj .* kaj .* estas malsamaj$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Dosieroj .* kaj .* estas malsamaj$" +syn match hgDiffIsA "^\%(SL\|HG\): Dosiero .* estas .*, dum dosiero .* estas .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Mankas linifino ĉe fino de dosiero" +syn match hgDiffCommon "^\%(SL\|HG\): Komunaj subdosierujoj: .* kaj .*" + +" es +syn match hgDiffOnly "^\%(SL\|HG\): Sólo en .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Los ficheros .* y .* son idénticos$" +syn match hgDiffDiffer "^\%(SL\|HG\): Los ficheros .* y .* son distintos$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Los ficheros binarios .* y .* son distintos$" +syn match hgDiffIsA "^\%(SL\|HG\): El fichero .* es un .* mientras que el .* es un .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ No hay ningún carácter de nueva lÃnea al final del fichero" +syn match hgDiffCommon "^\%(SL\|HG\): Subdirectorios comunes: .* y .*" + +" fi +syn match hgDiffOnly "^\%(SL\|HG\): Vain hakemistossa .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Tiedostot .* ja .* ovat identtiset$" +syn match hgDiffDiffer "^\%(SL\|HG\): Tiedostot .* ja .* eroavat$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binääritiedostot .* ja .* eroavat$" +syn match hgDiffIsA "^\%(SL\|HG\): Tiedosto .* on .*, kun taas tiedosto .* on .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Ei rivinvaihtoa tiedoston lopussa" +syn match hgDiffCommon "^\%(SL\|HG\): Yhteiset alihakemistot: .* ja .*" + +" fr +syn match hgDiffOnly "^\%(SL\|HG\): Seulement dans .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Les fichiers .* et .* sont identiques.*" +syn match hgDiffDiffer "^\%(SL\|HG\): Les fichiers .* et .* sont différents.*" +syn match hgDiffBDiffer "^\%(SL\|HG\): Les fichiers binaires .* et .* sont différents.*" +syn match hgDiffIsA "^\%(SL\|HG\): Le fichier .* est un .* alors que le fichier .* est un .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Pas de fin de ligne à la fin du fichier.*" +syn match hgDiffCommon "^\%(SL\|HG\): Les sous-répertoires .* et .* sont identiques.*" + +" ga +syn match hgDiffOnly "^\%(SL\|HG\): I .* amháin: .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Is comhionann iad na comhaid .* agus .*" +syn match hgDiffDiffer "^\%(SL\|HG\): Tá difrÃocht idir na comhaid .* agus .*" +syn match hgDiffBDiffer "^\%(SL\|HG\): Tá difrÃocht idir na comhaid .* agus .*" +syn match hgDiffIsA "^\%(SL\|HG\): Tá comhad .* ina .* ach tá comhad .* ina .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Gan lÃne nua ag an chomhadchrÃoch" +syn match hgDiffCommon "^\%(SL\|HG\): Fochomhadlanna i gcoitianta: .* agus .*" + +" gl +syn match hgDiffOnly "^\%(SL\|HG\): Só en .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Os ficheiros .* e .* son idénticos$" +syn match hgDiffDiffer "^\%(SL\|HG\): Os ficheiros .* e .* son diferentes$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Os ficheiros binarios .* e .* son diferentes$" +syn match hgDiffIsA "^\%(SL\|HG\): O ficheiro .* é un .* mentres que o ficheiro .* é un .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Non hai un salto de liña na fin da liña" +syn match hgDiffCommon "^\%(SL\|HG\): Subdirectorios comúns: .* e .*" + +" he +" ^\%(SL\|HG\): .* are expansive patterns for long lines, so disabled unless we can match +" some specific hebrew chars +if search('\%u05d5\|\%u05d1', 'nw', '', 100) + syn match hgDiffOnly "^\%(SL\|HG\): .*-ב קר ××¦×ž× .*" + syn match hgDiffIdentical "^\%(SL\|HG\): ××™×”×– ×× ×™×” .*-ו .* ×יצבקה$" + syn match hgDiffDiffer "^\%(SL\|HG\): הזמ ×”×– ××™× ×•×© `.*'-ו `.*' ×יצבקה$" + syn match hgDiffBDiffer "^\%(SL\|HG\): הזמ ×”×– ××™× ×•×© `.*'-ו `.*' ××™×™×¨× ×™×‘ ×יצבק$" + syn match hgDiffIsA "^\%(SL\|HG\): .* .*-ל .* .* תוושהל ×Ÿ×ª×™× ×ל$" + syn match hgDiffNoEOL "^\%(SL\|HG\): \\ ץבוקה ףוסב השד.-הרוש ות רס." + syn match hgDiffCommon "^\%(SL\|HG\): .*-ו .* :תוהז תויקית-תת$" +endif + +" hr +syn match hgDiffOnly "^\%(SL\|HG\): Samo u .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Datoteke .* i .* su identiÄne$" +syn match hgDiffDiffer "^\%(SL\|HG\): Datoteke .* i .* se razlikuju$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binarne datoteke .* i .* se razlikuju$" +syn match hgDiffIsA "^\%(SL\|HG\): Datoteka .* je .*, a datoteka .* je .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Nema novog retka na kraju datoteke" +syn match hgDiffCommon "^\%(SL\|HG\): UobiÄajeni poddirektoriji: .* i .*" + +" hu +syn match hgDiffOnly "^\%(SL\|HG\): Csak .* -ben: .*" +syn match hgDiffIdentical "^\%(SL\|HG\): .* és .* fájlok azonosak$" +syn match hgDiffDiffer "^\%(SL\|HG\): A(z) .* és a(z) .* fájlok különböznek$" +syn match hgDiffBDiffer "^\%(SL\|HG\): A(z) .* és a(z) .* fájlok különböznek$" +syn match hgDiffIsA "^\%(SL\|HG\): A(z) .* fájl egy .*, viszont a(z) .* fájl egy .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Nincs újsor a fájl végén" +syn match hgDiffCommon "^\%(SL\|HG\): Közös alkönyvtárak: .* és .*" + +" id +syn match hgDiffOnly "^\%(SL\|HG\): Hanya dalam .*" +syn match hgDiffIdentical "^\%(SL\|HG\): File .* dan .* identik$" +syn match hgDiffDiffer "^\%(SL\|HG\): Berkas .* dan .* berbeda$" +syn match hgDiffBDiffer "^\%(SL\|HG\): File biner .* dan .* berbeda$" +syn match hgDiffIsA "^\%(SL\|HG\): File .* adalah .* sementara file .* adalah .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Tidak ada baris-baru di akhir dari berkas" +syn match hgDiffCommon "^\%(SL\|HG\): Subdirektori sama: .* dan .*" + +" it +syn match hgDiffOnly "^\%(SL\|HG\): Solo in .*" +syn match hgDiffIdentical "^\%(SL\|HG\): I file .* e .* sono identici$" +syn match hgDiffDiffer "^\%(SL\|HG\): I file .* e .* sono diversi$" +syn match hgDiffBDiffer "^\%(SL\|HG\): I file .* e .* sono diversi$" +syn match hgDiffBDiffer "^\%(SL\|HG\): I file binari .* e .* sono diversi$" +syn match hgDiffIsA "^\%(SL\|HG\): File .* è un .* mentre file .* è un .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Manca newline alla fine del file" +syn match hgDiffCommon "^\%(SL\|HG\): Sottodirectory in comune: .* e .*" + +" ja +syn match hgDiffOnly "^\%(SL\|HG\): .*ã ã‘ã«ç™ºè¦‹: .*" +syn match hgDiffIdentical "^\%(SL\|HG\): ファイル.*ã¨.*ã¯åŒä¸€$" +syn match hgDiffDiffer "^\%(SL\|HG\): ファイル.*ã¨.*ã¯é•ã„ã¾ã™$" +syn match hgDiffBDiffer "^\%(SL\|HG\): ãƒã‚¤ãƒŠãƒªãƒ¼ãƒ»ãƒ•ァイル.*ã¨.*ã¯é•ã„ã¾ã™$" +syn match hgDiffIsA "^\%(SL\|HG\): ファイル.*ã¯.*ã€ãƒ•ァイル.*ã¯.*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ ãƒ•ã‚¡ã‚¤ãƒ«æœ«å°¾ã«æ”¹è¡ŒãŒã‚りã¾ã›ã‚“" +syn match hgDiffCommon "^\%(SL\|HG\): 共通ã®ä¸‹ä½ãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒªãƒ¼: .*ã¨.*" + +" ja DiffUtils 3.3 +syn match hgDiffOnly "^\%(SL\|HG\): .* ã®ã¿ã«å˜åœ¨: .*" +syn match hgDiffIdentical "^\%(SL\|HG\): ファイル .* 㨠.* ã¯åŒä¸€ã§ã™$" +syn match hgDiffDiffer "^\%(SL\|HG\): ファイル .* 㨠.* ã¯ç•°ãªã‚Šã¾ã™$" +syn match hgDiffBDiffer "^\%(SL\|HG\): ãƒã‚¤ãƒŠãƒªãƒ¼ãƒ•ァイル .* ã¨.* ã¯ç•°ãªã‚Šã¾ã™$" +syn match hgDiffIsA "^\%(SL\|HG\): ファイル .* 㯠.* ã§ã™ã€‚一方ã€ãƒ•ァイル .* 㯠.* ã§ã™$" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ ãƒ•ã‚¡ã‚¤ãƒ«æœ«å°¾ã«æ”¹è¡ŒãŒã‚りã¾ã›ã‚“" +syn match hgDiffCommon "^\%(SL\|HG\): 共通ã®ã‚µãƒ–ディレクトリー: .* 㨠.*" + +" lv +syn match hgDiffOnly "^\%(SL\|HG\): Tikai iekÅ¡ .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Fails .* un .* ir identiski$" +syn match hgDiffDiffer "^\%(SL\|HG\): Faili .* un .* atšķiras$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Faili .* un .* atšķiras$" +syn match hgDiffBDiffer "^\%(SL\|HG\): BinÄrie faili .* un .* atšķiras$" +syn match hgDiffIsA "^\%(SL\|HG\): Fails .* ir .* kamÄ“r fails .* ir .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Nav jaunu rindu faila beigÄs" +syn match hgDiffCommon "^\%(SL\|HG\): KopÄ“jÄs apakÅ¡direktorijas: .* un .*" + +" ms +syn match hgDiffOnly "^\%(SL\|HG\): Hanya dalam .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Fail .* dan .* adalah serupa$" +syn match hgDiffDiffer "^\%(SL\|HG\): Fail .* dan .* berbeza$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Fail .* dan .* berbeza$" +syn match hgDiffIsA "^\%(SL\|HG\): Fail .* adalah .* manakala fail .* adalah .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Tiada baris baru pada penghujung fail" +syn match hgDiffCommon "^\%(SL\|HG\): Subdirektori umum: .* dan .*" + +" nl +syn match hgDiffOnly "^\%(SL\|HG\): Alleen in .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Bestanden .* en .* zijn identiek$" +syn match hgDiffDiffer "^\%(SL\|HG\): Bestanden .* en .* zijn verschillend$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Bestanden .* en .* zijn verschillend$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binaire bestanden .* en .* zijn verschillend$" +syn match hgDiffIsA "^\%(SL\|HG\): Bestand .* is een .* terwijl bestand .* een .* is$" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Geen regeleindeteken (LF) aan einde van bestand" +syn match hgDiffCommon "^\%(SL\|HG\): Gemeenschappelijke submappen: .* en .*" + +" pl +syn match hgDiffOnly "^\%(SL\|HG\): Tylko w .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Pliki .* i .* sÄ… identyczne$" +syn match hgDiffDiffer "^\%(SL\|HG\): Pliki .* i .* różniÄ… siÄ™$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Pliki .* i .* różniÄ… siÄ™$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Binarne pliki .* i .* różniÄ… siÄ™$" +syn match hgDiffIsA "^\%(SL\|HG\): Plik .* jest .*, podczas gdy plik .* jest .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Brak znaku nowej linii na koÅ„cu pliku" +syn match hgDiffCommon "^\%(SL\|HG\): Wspólne podkatalogi: .* i .*" + +" pt_BR +syn match hgDiffOnly "^\%(SL\|HG\): Somente em .*" +syn match hgDiffOnly "^\%(SL\|HG\): Apenas em .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Os aquivos .* e .* são idênticos$" +syn match hgDiffDiffer "^\%(SL\|HG\): Os arquivos .* e .* são diferentes$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Os arquivos binários .* e .* são diferentes$" +syn match hgDiffIsA "^\%(SL\|HG\): O arquivo .* é .* enquanto o arquivo .* é .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Falta o caracter nova linha no final do arquivo" +syn match hgDiffCommon "^\%(SL\|HG\): Subdiretórios idênticos: .* e .*" + +" ro +syn match hgDiffOnly "^\%(SL\|HG\): Doar în .*" +syn match hgDiffIdentical "^\%(SL\|HG\): FiÅŸierele .* ÅŸi .* sunt identice$" +syn match hgDiffDiffer "^\%(SL\|HG\): FiÅŸierele .* ÅŸi .* diferă$" +syn match hgDiffBDiffer "^\%(SL\|HG\): FiÅŸierele binare .* ÅŸi .* diferă$" +syn match hgDiffIsA "^\%(SL\|HG\): FiÅŸierul .* este un .* pe când fiÅŸierul .* este un .*.$" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Nici un element de linie nouă la sfârÅŸitul fiÅŸierului" +syn match hgDiffCommon "^\%(SL\|HG\): Subdirectoare comune: .* ÅŸi .*.$" + +" ru +syn match hgDiffOnly "^\%(SL\|HG\): Только в .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Файлы .* и .* идентичны$" +syn match hgDiffDiffer "^\%(SL\|HG\): Файлы .* и .* различаютÑÑ$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Файлы .* и .* различаютÑÑ$" +syn match hgDiffIsA "^\%(SL\|HG\): Файл .* Ñто .*, тогда как файл .* -- .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Ð’ конце файла нет новой Ñтроки" +syn match hgDiffCommon "^\%(SL\|HG\): Общие подкаталоги: .* и .*" + +" sr +syn match hgDiffOnly "^\%(SL\|HG\): Само у .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Датотеке „.*“ и „.*“ Ñе подударају$" +syn match hgDiffDiffer "^\%(SL\|HG\): Датотеке .* и .* различите$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Бинарне датотеке .* и .* различите$" +syn match hgDiffIsA "^\%(SL\|HG\): Датотека „.*“ је „.*“ док је датотека „.*“ „.*“$" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Без новог реда на крају датотеке" +syn match hgDiffCommon "^\%(SL\|HG\): Заједнички поддиректоријуми: .* и .*" + +" sv +syn match hgDiffOnly "^\%(SL\|HG\): Endast i .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Filerna .* och .* är lika$" +syn match hgDiffDiffer "^\%(SL\|HG\): Filerna .* och .* skiljer$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Filerna .* och .* skiljer$" +syn match hgDiffIsA "^\%(SL\|HG\): Fil .* är en .* medan fil .* är en .*" +syn match hgDiffBDiffer "^\%(SL\|HG\): De binära filerna .* och .* skiljer$" +syn match hgDiffIsA "^\%(SL\|HG\): Filen .* är .* medan filen .* är .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Ingen nyrad vid filslut" +syn match hgDiffCommon "^\%(SL\|HG\): Lika underkataloger: .* och .*" + +" tr +syn match hgDiffOnly "^\%(SL\|HG\): Yalnızca .*'da: .*" +syn match hgDiffIdentical "^\%(SL\|HG\): .* ve .* dosyaları birbirinin aynı$" +syn match hgDiffDiffer "^\%(SL\|HG\): .* ve .* dosyaları birbirinden farklı$" +syn match hgDiffBDiffer "^\%(SL\|HG\): .* ve .* dosyaları birbirinden farklı$" +syn match hgDiffBDiffer "^\%(SL\|HG\): İkili .* ve .* birbirinden farklı$" +syn match hgDiffIsA "^\%(SL\|HG\): .* dosyası, bir .*, halbuki .* dosyası bir .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Dosya sonunda yenisatır yok." +syn match hgDiffCommon "^\%(SL\|HG\): Ortak alt dizinler: .* ve .*" + +" uk +syn match hgDiffOnly "^\%(SL\|HG\): Лише у .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Файли .* та .* ідентичні$" +syn match hgDiffDiffer "^\%(SL\|HG\): Файли .* та .* відрізнÑютьÑÑ$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Файли .* та .* відрізнÑютьÑÑ$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Двійкові файли .* та .* відрізнÑютьÑÑ$" +syn match hgDiffIsA "^\%(SL\|HG\): Файл .* це .*, тоді Ñк файл .* -- .*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Ðаприкінці файлу немає нового Ñ€Ñдка" +syn match hgDiffCommon "^\%(SL\|HG\): Спільні підкаталоги: .* та .*" + +" vi +syn match hgDiffOnly "^\%(SL\|HG\): Chỉ trong .*" +syn match hgDiffIdentical "^\%(SL\|HG\): Hai táºp tin .* và .* là bằng nhau.$" +syn match hgDiffIdentical "^\%(SL\|HG\): Cả .* và .* là cùng má»™t táºp tin$" +syn match hgDiffDiffer "^\%(SL\|HG\): Hai táºp tin .* và .* là khác nhau.$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Hai táºp tin nhị phân .* và .* khác nhau$" +syn match hgDiffIsA "^\%(SL\|HG\): Táºp tin .* là má»™t .* trong khi táºp tin .* là má»™t .*.$" +syn match hgDiffBDiffer "^\%(SL\|HG\): Hai táºp tin .* và .* là khác nhau.$" +syn match hgDiffIsA "^\%(SL\|HG\): Táºp tin .* là má»™t .* còn táºp tin .* là má»™t .*.$" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ Không có ký tá»± dòng má»›i tại kêt thức táºp tin." +syn match hgDiffCommon "^\%(SL\|HG\): Thư mục con chung: .* và .*" + +" zh_CN +syn match hgDiffOnly "^\%(SL\|HG\): åªåœ¨ .* å˜åœ¨ï¼š.*" +syn match hgDiffIdentical "^\%(SL\|HG\): 檔案 .* å’Œ .* 相åŒ$" +syn match hgDiffDiffer "^\%(SL\|HG\): 文件 .* å’Œ .* ä¸åŒ$" +syn match hgDiffBDiffer "^\%(SL\|HG\): 文件 .* å’Œ .* ä¸åŒ$" +syn match hgDiffIsA "^\%(SL\|HG\): 文件 .* 是.*而文件 .* 是.*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ 文件尾没有 newline å—符" +syn match hgDiffCommon "^\%(SL\|HG\): .* å’Œ .* 有共åŒçš„å目录$" + +" zh_TW +syn match hgDiffOnly "^\%(SL\|HG\): åªåœ¨ .* å˜åœ¨ï¼š.*" +syn match hgDiffIdentical "^\%(SL\|HG\): 檔案 .* å’Œ .* 相åŒ$" +syn match hgDiffDiffer "^\%(SL\|HG\): 檔案 .* 與 .* ä¸åŒ$" +syn match hgDiffBDiffer "^\%(SL\|HG\): 二元碼檔 .* 與 .* ä¸åŒ$" +syn match hgDiffIsA "^\%(SL\|HG\): 檔案 .* 是.*而檔案 .* 是.*" +syn match hgDiffNoEOL "^\%(SL\|HG\): \\ 檔案末沒有 newline å—å…ƒ" +syn match hgDiffCommon "^\%(SL\|HG\): .* å’Œ .* 有共åŒçš„副目錄$" + +endif + + +syn match hgDiffRemoved "^\%(SL\|HG\): -.*" +syn match hgDiffRemoved "^\%(SL\|HG\): <.*" +syn match hgDiffAdded "^\%(SL\|HG\): +.*" +syn match hgDiffAdded "^\%(SL\|HG\): >.*" +syn match hgDiffChanged "^\%(SL\|HG\): ! .*" + +syn match hgDiffSubname " @@..*"ms=s+3 contained +syn match hgDiffLine "^\%(SL\|HG\): @.*" contains=hgDiffSubname +syn match hgDiffLine "^\%(SL\|HG\): \<\d\+\>.*" +syn match hgDiffLine "^\%(SL\|HG\): \*\*\*\*.*" +syn match hgDiffLine "^\%(SL\|HG\): ---$" + +" Some versions of diff have lines like "#c#" and "#d#" (where # is a number) +syn match hgDiffLine "^\%(SL\|HG\): \d\+\(,\d\+\)\=[cda]\d\+\>.*" + +syn match hgDiffFile "^\%(SL\|HG\): diff\>.*" +syn match hgDiffFile "^\%(SL\|HG\): Index: .*" +syn match hgDiffFile "^\%(SL\|HG\): ==== .*" + +if search('^\%(SL\|HG\): @@ -\S\+ +\S\+ @@', 'nw', '', 100) + " unified + syn match hgDiffOldFile "^\%(SL\|HG\): --- .*" + syn match hgDiffNewFile "^\%(SL\|HG\): +++ .*" +else + " context / old style + syn match hgDiffOldFile "^\%(SL\|HG\): \*\*\* .*" + syn match hgDiffNewFile "^\%(SL\|HG\): --- .*" +endif + +" Used by git +syn match hgDiffIndexLine "^\%(SL\|HG\): index \x\x\x\x.*" + +syn match hgDiffComment "^\%(SL\|HG\): #.*" + +" Define the default highlighting. +" Only used when an item doesn't have highlighting yet +hi def link hgDiffOldFile hgDiffFile +hi def link hgDiffNewFile hgDiffFile +hi def link hgDiffIndexLine PreProc +hi def link hgDiffFile Type +hi def link hgDiffOnly Constant +hi def link hgDiffIdentical Constant +hi def link hgDiffDiffer Constant +hi def link hgDiffBDiffer Constant +hi def link hgDiffIsA Constant +hi def link hgDiffNoEOL Constant +hi def link hgDiffCommon Constant +hi def link hgDiffRemoved Special +hi def link hgDiffChanged PreProc +hi def link hgDiffAdded Identifier +hi def link hgDiffLine Statement +hi def link hgDiffSubname PreProc +hi def link hgDiffComment Comment + +let b:current_syntax = "hgcommitDiff" + +" vim: ts=8 sw=2 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/ssa.vim b/runtime/syntax/ssa.vim new file mode 100644 index 0000000000..a5dbf37c30 --- /dev/null +++ b/runtime/syntax/ssa.vim @@ -0,0 +1,63 @@ +" Vim syntax file +" Language: SubStation Alpha +" Maintainer: ObserverOfTime <chronobserver@disroot.org> +" Filenames: *.ass,*.ssa +" Last Change: 2022 Oct 10 + +if exists('b:current_syntax') + finish +endif + +" Comments +syn keyword ssaTodo TODO FIXME NOTE XXX contained +syn match ssaComment /^\(;\|!:\).*$/ contains=ssaTodo,@Spell +syn match ssaTextComment /{[^}]*}/ contained contains=@Spell + +" Sections +syn match ssaSection /^\[[a-zA-Z0-9+ ]\+\]$/ + +" Headers +syn match ssaHeader /^[^;!:]\+:/ skipwhite nextgroup=ssaField + +" Fields +syn match ssaField /[^,]*/ contained skipwhite nextgroup=ssaDelimiter + +" Time +syn match ssaTime /\d:\d\d:\d\d\.\d\d/ contained skipwhite nextgroup=ssaDelimiter + +" Delimiter +syn match ssaDelimiter /,/ contained skipwhite nextgroup=ssaField,ssaTime,ssaText + +" Text +syn match ssaText /\(^Dialogue:\(.*,\)\{9}\)\@<=.*$/ contained contains=@ssaTags,@Spell +syn cluster ssaTags contains=ssaOverrideTag,ssaEscapeChar,ssaTextComment,ssaItalics,ssaBold,ssaUnderline,ssaStrikeout + +" Override tags +syn match ssaOverrideTag /{\\[^}]\+}/ contained contains=@NoSpell + +" Special characters +syn match ssaEscapeChar /\\[nNh{}]/ contained contains=@NoSpell + +" Markup +syn region ssaItalics start=/{\\i1}/ end=/{\\i0}/ matchgroup=ssaOverrideTag keepend oneline contained contains=@ssaTags,@Spell +syn region ssaBold start=/{\\b1}/ end=/{\\b0}/ matchgroup=ssaOverrideTag keepend oneline contained contains=@ssaTags,@Spell +syn region ssaUnderline start=/{\\u1}/ end=/{\\u0}/ matchgroup=ssaOverrideTag keepend oneline contained contains=@ssaTags,@Spell +syn region ssaStrikeout start=/{\\s1}/ end=/{\\s0}/ matchgroup=ssaOverrideTag keepend oneline contained contains=@ssaTags,@Spell + +hi def link ssaDelimiter Delimiter +hi def link ssaComment Comment +hi def link ssaEscapeChar SpecialChar +hi def link ssaField String +hi def link ssaHeader Label +hi def link ssaSection StorageClass +hi def link ssaOverrideTag Special +hi def link ssaTextComment Comment +hi def link ssaTime Number +hi def link ssaTodo Todo + +hi ssaBold cterm=bold gui=bold +hi ssaItalics cterm=italic gui=italic +hi ssaStrikeout cterm=strikethrough gui=strikethrough +hi ssaUnderline cterm=underline gui=underline + +let b:current_syntax = 'srt' diff --git a/runtime/syntax/sshconfig.vim b/runtime/syntax/sshconfig.vim index ae3c7dd8cc..750289d83e 100644 --- a/runtime/syntax/sshconfig.vim +++ b/runtime/syntax/sshconfig.vim @@ -6,9 +6,10 @@ " Contributor: Leonard Ehrenfried <leonard.ehrenfried@web.de> " Contributor: Karsten Hopp <karsten@redhat.com> " Contributor: Dean, Adam Kenneth <adam.ken.dean@hpe.com> -" Last Change: 2021 Mar 29 +" Last Change: 2022 Nov 10 " Added RemoteCommand from pull request #4809 " Included additional keywords from Martin. +" Included PR #5753 " SSH Version: 8.5p1 " @@ -57,12 +58,12 @@ syn match sshconfigCiphers "\<aes256-gcm@openssh\.com\>" syn match sshconfigCiphers "\<chacha20-poly1305@openssh\.com\>" syn keyword sshconfigMAC hmac-sha1 -syn keyword sshconfigMAC mac-sha1-96 -syn keyword sshconfigMAC mac-sha2-256 -syn keyword sshconfigMAC mac-sha2-512 -syn keyword sshconfigMAC mac-md5 -syn keyword sshconfigMAC mac-md5-96 -syn keyword sshconfigMAC mac-ripemd160 +syn keyword sshconfigMAC hmac-sha1-96 +syn keyword sshconfigMAC hmac-sha2-256 +syn keyword sshconfigMAC hmac-sha2-512 +syn keyword sshconfigMAC hmac-md5 +syn keyword sshconfigMAC hmac-md5-96 +syn keyword sshconfigMAC hmac-ripemd160 syn match sshconfigMAC "\<hmac-ripemd160@openssh\.com\>" syn match sshconfigMAC "\<umac-64@openssh\.com\>" syn match sshconfigMAC "\<umac-128@openssh\.com\>" @@ -78,16 +79,24 @@ syn match sshconfigMAC "\<umac-128-etm@openssh\.com\>" syn keyword sshconfigHostKeyAlgo ssh-ed25519 syn match sshconfigHostKeyAlgo "\<ssh-ed25519-cert-v01@openssh\.com\>" +syn match sshconfigHostKeyAlgo "\<sk-ssh-ed25519@openssh\.com\>" +syn match sshconfigHostKeyAlgo "\<sk-ssh-ed25519-cert-v01@openssh\.com\>" syn keyword sshconfigHostKeyAlgo ssh-rsa +syn keyword sshconfigHostKeyAlgo rsa-sha2-256 +syn keyword sshconfigHostKeyAlgo rsa-sha2-512 syn keyword sshconfigHostKeyAlgo ssh-dss syn keyword sshconfigHostKeyAlgo ecdsa-sha2-nistp256 syn keyword sshconfigHostKeyAlgo ecdsa-sha2-nistp384 syn keyword sshconfigHostKeyAlgo ecdsa-sha2-nistp521 +syn match sshconfigHostKeyAlgo "\<sk-ecdsa-sha2-nistp256@openssh\.com\>" syn match sshconfigHostKeyAlgo "\<ssh-rsa-cert-v01@openssh\.com\>" +syn match sshconfigHostKeyAlgo "\<rsa-sha2-256-cert-v01@openssh\.com\>" +syn match sshconfigHostKeyAlgo "\<rsa-sha2-512-cert-v01@openssh\.com\>" syn match sshconfigHostKeyAlgo "\<ssh-dss-cert-v01@openssh\.com\>" syn match sshconfigHostKeyAlgo "\<ecdsa-sha2-nistp256-cert-v01@openssh\.com\>" syn match sshconfigHostKeyAlgo "\<ecdsa-sha2-nistp384-cert-v01@openssh\.com\>" syn match sshconfigHostKeyAlgo "\<ecdsa-sha2-nistp521-cert-v01@openssh\.com\>" +syn match sshconfigHostKeyAlgo "\<sk-ecdsa-sha2-nistp256-cert-v01@openssh\.com\>" syn keyword sshconfigPreferredAuth hostbased publickey password gssapi-with-mic syn keyword sshconfigPreferredAuth keyboard-interactive @@ -162,6 +171,7 @@ syn keyword sshconfigKeyword EnableSSHKeysign syn keyword sshconfigKeyword EscapeChar syn keyword sshconfigKeyword ExitOnForwardFailure syn keyword sshconfigKeyword FingerprintHash +syn keyword sshconfigKeyword ForkAfterAuthentication syn keyword sshconfigKeyword ForwardAgent syn keyword sshconfigKeyword ForwardX11 syn keyword sshconfigKeyword ForwardX11Timeout @@ -212,13 +222,16 @@ syn keyword sshconfigKeyword RekeyLimit syn keyword sshconfigKeyword RemoteCommand syn keyword sshconfigKeyword RemoteForward syn keyword sshconfigKeyword RequestTTY +syn keyword sshconfigKeyword RequiredRSASize syn keyword sshconfigKeyword RevokedHostKeys syn keyword sshconfigKeyword SecurityKeyProvider syn keyword sshconfigKeyword SendEnv syn keyword sshconfigKeyword ServerAliveCountMax syn keyword sshconfigKeyword ServerAliveInterval +syn keyword sshconfigKeyword SessionType syn keyword sshconfigKeyword SmartcardDevice syn keyword sshconfigKeyword SetEnv +syn keyword sshconfigKeyword StdinNull syn keyword sshconfigKeyword StreamLocalBindMask syn keyword sshconfigKeyword StreamLocalBindUnlink syn keyword sshconfigKeyword StrictHostKeyChecking diff --git a/runtime/syntax/sshdconfig.vim b/runtime/syntax/sshdconfig.vim index 6b0d2af4d1..c0d9c3f598 100644 --- a/runtime/syntax/sshdconfig.vim +++ b/runtime/syntax/sshdconfig.vim @@ -7,7 +7,7 @@ " Contributor: Leonard Ehrenfried <leonard.ehrenfried@web.de> " Contributor: Karsten Hopp <karsten@redhat.com> " Originally: 2009-07-09 -" Last Change: 2021-03-29 +" Last Change: 2022 Nov 10 " SSH Version: 8.5p1 " @@ -59,12 +59,12 @@ syn match sshdconfigCiphers "\<aes256-gcm@openssh\.com\>" syn match sshdconfigCiphers "\<chacha20-poly1305@openssh\.com\>" syn keyword sshdconfigMAC hmac-sha1 -syn keyword sshdconfigMAC mac-sha1-96 -syn keyword sshdconfigMAC mac-sha2-256 -syn keyword sshdconfigMAC mac-sha2-512 -syn keyword sshdconfigMAC mac-md5 -syn keyword sshdconfigMAC mac-md5-96 -syn keyword sshdconfigMAC mac-ripemd160 +syn keyword sshdconfigMAC hmac-sha1-96 +syn keyword sshdconfigMAC hmac-sha2-256 +syn keyword sshdconfigMAC hmac-sha2-512 +syn keyword sshdconfigMAC hmac-md5 +syn keyword sshdconfigMAC hmac-md5-96 +syn keyword sshdconfigMAC hmac-ripemd160 syn match sshdconfigMAC "\<hmac-ripemd160@openssh\.com\>" syn match sshdconfigMAC "\<umac-64@openssh\.com\>" syn match sshdconfigMAC "\<umac-128@openssh\.com\>" @@ -221,6 +221,7 @@ syn keyword sshdconfigKeyword Match syn keyword sshdconfigKeyword MaxAuthTries syn keyword sshdconfigKeyword MaxSessions syn keyword sshdconfigKeyword MaxStartups +syn keyword sshdconfigKeyword ModuliFile syn keyword sshdconfigKeyword PasswordAuthentication syn keyword sshdconfigKeyword PerSourceMaxStartups syn keyword sshdconfigKeyword PerSourceNetBlockSize @@ -244,6 +245,7 @@ syn keyword sshdconfigKeyword PubkeyAuthentication syn keyword sshdconfigKeyword PubkeyAuthOptions syn keyword sshdconfigKeyword RSAAuthentication syn keyword sshdconfigKeyword RekeyLimit +syn keyword sshdconfigKeyword RequiredRSASize syn keyword sshdconfigKeyword RevokedKeys syn keyword sshdconfigKeyword RDomain syn keyword sshdconfigKeyword RhostsRSAAuthentication @@ -258,6 +260,8 @@ syn keyword sshdconfigKeyword Subsystem syn keyword sshdconfigKeyword SyslogFacility syn keyword sshdconfigKeyword TCPKeepAlive syn keyword sshdconfigKeyword TrustedUserCAKeys +syn keyword sshdconfigKeyword UseBlacklist +syn keyword sshdconfigKeyword UseBlocklist syn keyword sshdconfigKeyword UseDNS syn keyword sshdconfigKeyword UseLogin syn keyword sshdconfigKeyword UsePAM diff --git a/runtime/syntax/swayconfig.vim b/runtime/syntax/swayconfig.vim index d9f31da47b..996b8f596c 100644 --- a/runtime/syntax/swayconfig.vim +++ b/runtime/syntax/swayconfig.vim @@ -2,7 +2,8 @@ " Language: sway window manager config " Original Author: James Eapen <james.eapen@vai.org> " Maintainer: James Eapen <james.eapen@vai.org> -" Version: 0.11.1 +" Version: 0.1.6 +" Reference version (jamespeapen/swayconfig.vim): 0.11.6 " Last Change: 2022 Aug 08 " References: @@ -23,10 +24,6 @@ scriptencoding utf-8 " Error "syn match swayConfigError /.*/ -" Group mode/bar -syn keyword swayConfigBlockKeyword set input contained -syn region swayConfigBlock start=+.*s\?{$+ end=+^}$+ contains=i3ConfigBlockKeyword,swayConfigBlockKeyword,i3ConfigString,i3ConfigBind,i3ConfigComment,i3ConfigFont,i3ConfigFocusWrappingType,i3ConfigColor,i3ConfigVariable transparent keepend extend - " binding syn keyword swayConfigBindKeyword bindswitch bindgesture contained syn match swayConfigBind /^\s*\(bindswitch\)\s\+.*$/ contains=i3ConfigVariable,i3ConfigBindKeyword,swayConfigBindKeyword,i3ConfigVariableAndModifier,i3ConfigNumber,i3ConfigUnit,i3ConfigUnitOr,i3ConfigBindArgument,i3ConfigModifier,i3ConfigAction,i3ConfigString,i3ConfigGapStyleKeyword,i3ConfigBorderStyleKeyword @@ -45,7 +42,7 @@ syn match swayConfigFloating /^\s*floating\s\+\(enable\|disable\|toggle\)\s*$/ c syn clear i3ConfigFloatingModifier syn keyword swayConfigFloatingModifier floating_modifier contained -syn match swayConfigFloatingMouseAction /^\s\?.*floating_modifier\s.*\(normal\|inverted\)$/ contains=swayConfigFloatingModifier,i3ConfigVariable +syn match swayConfigFloatingMouseAction /^\s\?.*floating_modifier\s\S\+\s\?\(normal\|inverted\|none\)\?$/ contains=swayConfigFloatingModifier,i3ConfigVariable " Gaps syn clear i3ConfigSmartBorderKeyword @@ -57,6 +54,10 @@ syn match swayConfigSmartBorder /^\s*smart_borders\s\+\(on\|no_gaps\|off\)\s\?$/ syn keyword swayConfigClientColorKeyword focused_tab_title contained syn match swayConfigClientColor /^\s*client.\w\+\s\+.*$/ contains=i3ConfigClientColorKeyword,i3ConfigColor,i3ConfigVariable,i3ConfigClientColorKeyword,swayConfigClientColorKeyword +" Input config +syn keyword swayConfigInputKeyword input contained +syn match swayConfigInput /^\s*input\s\+.*$/ contains=swayConfigInputKeyword + " set display outputs syn match swayConfigOutput /^\s*output\s\+.*$/ contains=i3ConfigOutput @@ -65,21 +66,34 @@ syn keyword swayConfigFocusKeyword focus contained syn keyword swayConfigFocusType output contained syn match swayConfigFocus /^\s*focus\soutput\s.*$/ contains=swayConfigFocusKeyword,swayConfigFocusType +" focus follows mouse +syn clear i3ConfigFocusFollowsMouseType +syn clear i3ConfigFocusFollowsMouse + +syn keyword swayConfigFocusFollowsMouseType yes no always contained +syn match swayConfigFocusFollowsMouse /^\s*focus_follows_mouse\s\+\(yes\|no\|always\)\s\?$/ contains=i3ConfigFocusFollowsMouseKeyword,swayConfigFocusFollowsMouseType + + " xwayland syn keyword swayConfigXwaylandKeyword xwayland contained syn match swayConfigXwaylandModifier /^\s*xwayland\s\+\(enable\|disable\|force\)\s\?$/ contains=swayConfigXwaylandKeyword +" Group mode/bar +syn clear i3ConfigBlock +syn region swayConfigBlock start=+.*s\?{$+ end=+^}$+ contains=i3ConfigBlockKeyword,i3ConfigString,i3ConfigBind,i3ConfigInitializeKeyword,i3ConfigComment,i3ConfigFont,i3ConfigFocusWrappingType,i3ConfigColor,i3ConfigVariable,swayConfigInputKeyword,i3ConfigOutput transparent keepend extend + "hi def link swayConfigError Error hi def link i3ConfigFloating Error hi def link swayConfigFloating Type hi def link swayConfigFloatingMouseAction Type hi def link swayConfigFocusKeyword Type hi def link swayConfigSmartBorderKeyword Type +hi def link swayConfigInputKeyword Type +hi def link swayConfigFocusFollowsMouseType Type hi def link swayConfigBindGestureCommand Identifier hi def link swayConfigBindGestureDirection Constant hi def link swayConfigBindGesturePinchDirection Constant hi def link swayConfigBindKeyword Identifier -hi def link swayConfigBlockKeyword Identifier hi def link swayConfigClientColorKeyword Identifier hi def link swayConfigFloatingKeyword Identifier hi def link swayConfigFloatingModifier Identifier 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..a1c39e4dcf 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 " ============= @@ -451,7 +451,7 @@ if !exists("g:vimsyn_noerror") && !exists("g:vimsyn_novimfunctionerror") syn match vimBufnrWarn /\<bufnr\s*(\s*["']\.['"]\s*)/ endif -syn match vimNotFunc "\<if\>\|\<el\%[seif]\>\|\<return\>\|\<while\>" skipwhite nextgroup=vimOper,vimOperParen,vimVar,vimFunc,vimNotation +syn match vimNotFunc "\<if\>\|\<el\%[seif]\>\|\<retu\%[rn]\>\|\<while\>" skipwhite nextgroup=vimOper,vimOperParen,vimVar,vimFunc,vimNotation " Norm: {{{2 " ==== diff --git a/runtime/syntax/wdl.vim b/runtime/syntax/wdl.vim new file mode 100644 index 0000000000..3b8369e8bd --- /dev/null +++ b/runtime/syntax/wdl.vim @@ -0,0 +1,41 @@ +" Vim syntax file +" Language: wdl +" Maintainer: Matt Dunford (zenmatic@gmail.com) +" URL: https://github.com/zenmatic/vim-syntax-wdl +" Last Change: 2022 Nov 24 + +" https://github.com/openwdl/wdl + +" quit when a (custom) syntax file was already loaded +if exists("b:current_syntax") + finish +endif + +syn case match + +syn keyword wdlStatement alias task input command runtime input output workflow call scatter import as meta parameter_meta in version +syn keyword wdlConditional if then else +syn keyword wdlType struct Array String File Int Float Boolean Map Pair Object + +syn keyword wdlFunctions stdout stderr read_lines read_tsv read_map read_object read_objects read_json read_int read_string read_float read_boolean write_lines write_tsv write_map write_object write_objects write_json size sub range transpose zip cross length flatten prefix select_first defined basename floor ceil round + +syn region wdlCommandSection start="<<<" end=">>>" + +syn region wdlString start=+"+ skip=+\\\\\|\\"+ end=+"+ +syn region wdlString start=+'+ skip=+\\\\\|\\'+ end=+'+ + +" Comments; their contents +syn keyword wdlTodo contained TODO FIXME XXX BUG +syn cluster wdlCommentGroup contains=wdlTodo +syn region wdlComment start="#" end="$" contains=@wdlCommentGroup + +hi def link wdlStatement Statement +hi def link wdlConditional Conditional +hi def link wdlType Type +hi def link wdlFunctions Function +hi def link wdlString String +hi def link wdlCommandSection String +hi def link wdlComment Comment +hi def link wdlTodo Todo + +let b:current_syntax = 'wdl' diff --git a/runtime/syntax/zig.vim b/runtime/syntax/zig.vim new file mode 100644 index 0000000000..e09b5e8815 --- /dev/null +++ b/runtime/syntax/zig.vim @@ -0,0 +1,292 @@ +" Vim syntax file +" Language: Zig +" Upstream: https://github.com/ziglang/zig.vim + +if exists("b:current_syntax") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +let s:zig_syntax_keywords = { + \ 'zigBoolean': ["true" + \ , "false"] + \ , 'zigNull': ["null"] + \ , 'zigType': ["bool" + \ , "f16" + \ , "f32" + \ , "f64" + \ , "f80" + \ , "f128" + \ , "void" + \ , "type" + \ , "anytype" + \ , "anyerror" + \ , "anyframe" + \ , "volatile" + \ , "linksection" + \ , "noreturn" + \ , "allowzero" + \ , "i0" + \ , "u0" + \ , "isize" + \ , "usize" + \ , "comptime_int" + \ , "comptime_float" + \ , "c_short" + \ , "c_ushort" + \ , "c_int" + \ , "c_uint" + \ , "c_long" + \ , "c_ulong" + \ , "c_longlong" + \ , "c_ulonglong" + \ , "c_longdouble" + \ , "anyopaque"] + \ , 'zigConstant': ["undefined" + \ , "unreachable"] + \ , 'zigConditional': ["if" + \ , "else" + \ , "switch"] + \ , 'zigRepeat': ["while" + \ , "for"] + \ , 'zigComparatorWord': ["and" + \ , "or" + \ , "orelse"] + \ , 'zigStructure': ["struct" + \ , "enum" + \ , "union" + \ , "error" + \ , "packed" + \ , "opaque"] + \ , 'zigException': ["error"] + \ , 'zigVarDecl': ["var" + \ , "const" + \ , "comptime" + \ , "threadlocal"] + \ , 'zigDummyVariable': ["_"] + \ , 'zigKeyword': ["fn" + \ , "try" + \ , "test" + \ , "pub" + \ , "usingnamespace"] + \ , 'zigExecution': ["return" + \ , "break" + \ , "continue"] + \ , 'zigMacro': ["defer" + \ , "errdefer" + \ , "async" + \ , "nosuspend" + \ , "await" + \ , "suspend" + \ , "resume" + \ , "export" + \ , "extern"] + \ , 'zigPreProc': ["catch" + \ , "inline" + \ , "noinline" + \ , "asm" + \ , "callconv" + \ , "noalias"] + \ , 'zigBuiltinFn': ["align" + \ , "@addWithOverflow" + \ , "@as" + \ , "@atomicLoad" + \ , "@atomicStore" + \ , "@bitCast" + \ , "@breakpoint" + \ , "@alignCast" + \ , "@alignOf" + \ , "@cDefine" + \ , "@cImport" + \ , "@cInclude" + \ , "@cUndef" + \ , "@clz" + \ , "@cmpxchgWeak" + \ , "@cmpxchgStrong" + \ , "@compileError" + \ , "@compileLog" + \ , "@ctz" + \ , "@popCount" + \ , "@divExact" + \ , "@divFloor" + \ , "@divTrunc" + \ , "@embedFile" + \ , "@export" + \ , "@extern" + \ , "@tagName" + \ , "@TagType" + \ , "@errorName" + \ , "@call" + \ , "@errorReturnTrace" + \ , "@fence" + \ , "@fieldParentPtr" + \ , "@field" + \ , "@unionInit" + \ , "@frameAddress" + \ , "@import" + \ , "@newStackCall" + \ , "@asyncCall" + \ , "@intToPtr" + \ , "@max" + \ , "@min" + \ , "@memcpy" + \ , "@memset" + \ , "@mod" + \ , "@mulAdd" + \ , "@mulWithOverflow" + \ , "@splat" + \ , "@src" + \ , "@bitOffsetOf" + \ , "@byteOffsetOf" + \ , "@offsetOf" + \ , "@OpaqueType" + \ , "@panic" + \ , "@prefetch" + \ , "@ptrCast" + \ , "@ptrToInt" + \ , "@rem" + \ , "@returnAddress" + \ , "@setCold" + \ , "@Type" + \ , "@shuffle" + \ , "@reduce" + \ , "@select" + \ , "@setRuntimeSafety" + \ , "@setEvalBranchQuota" + \ , "@setFloatMode" + \ , "@shlExact" + \ , "@This" + \ , "@hasDecl" + \ , "@hasField" + \ , "@shlWithOverflow" + \ , "@shrExact" + \ , "@sizeOf" + \ , "@bitSizeOf" + \ , "@sqrt" + \ , "@byteSwap" + \ , "@subWithOverflow" + \ , "@intCast" + \ , "@floatCast" + \ , "@intToFloat" + \ , "@floatToInt" + \ , "@boolToInt" + \ , "@errSetCast" + \ , "@truncate" + \ , "@typeInfo" + \ , "@typeName" + \ , "@TypeOf" + \ , "@atomicRmw" + \ , "@intToError" + \ , "@errorToInt" + \ , "@intToEnum" + \ , "@enumToInt" + \ , "@setAlignStack" + \ , "@frame" + \ , "@Frame" + \ , "@frameSize" + \ , "@bitReverse" + \ , "@Vector" + \ , "@sin" + \ , "@cos" + \ , "@tan" + \ , "@exp" + \ , "@exp2" + \ , "@log" + \ , "@log2" + \ , "@log10" + \ , "@fabs" + \ , "@floor" + \ , "@ceil" + \ , "@trunc" + \ , "@wasmMemorySize" + \ , "@wasmMemoryGrow" + \ , "@round"] + \ } + +function! s:syntax_keyword(dict) + for key in keys(a:dict) + execute 'syntax keyword' key join(a:dict[key], ' ') + endfor +endfunction + +call s:syntax_keyword(s:zig_syntax_keywords) + +syntax match zigType "\v<[iu][1-9]\d*>" +syntax match zigOperator display "\V\[-+/*=^&?|!><%~]" +syntax match zigArrowCharacter display "\V->" + +" 12_34 (. but not ..)? (12_34)? (exponent 12_34)? +syntax match zigDecNumber display "\v<\d%(_?\d)*%(\.\.@!)?%(\d%(_?\d)*)?%([eE][+-]?\d%(_?\d)*)?" +syntax match zigHexNumber display "\v<0x\x%(_?\x)*%(\.\.@!)?%(\x%(_?\x)*)?%([pP][+-]?\d%(_?\d)*)?" +syntax match zigOctNumber display "\v<0o\o%(_?\o)*" +syntax match zigBinNumber display "\v<0b[01]%(_?[01])*" + +syntax match zigCharacterInvalid display contained /b\?'\zs[\n\r\t']\ze'/ +syntax match zigCharacterInvalidUnicode display contained /b'\zs[^[:cntrl:][:graph:][:alnum:][:space:]]\ze'/ +syntax match zigCharacter /b'\([^\\]\|\\\(.\|x\x\{2}\)\)'/ contains=zigEscape,zigEscapeError,zigCharacterInvalid,zigCharacterInvalidUnicode +syntax match zigCharacter /'\([^\\]\|\\\(.\|x\x\{2}\|u\x\{4}\|U\x\{6}\)\)'/ contains=zigEscape,zigEscapeUnicode,zigEscapeError,zigCharacterInvalid + +syntax region zigBlock start="{" end="}" transparent fold + +syntax region zigCommentLine start="//" end="$" contains=zigTodo,@Spell +syntax region zigCommentLineDoc start="//[/!]/\@!" end="$" contains=zigTodo,@Spell + +syntax match zigMultilineStringPrefix /c\?\\\\/ contained containedin=zigMultilineString +syntax region zigMultilineString matchgroup=zigMultilineStringDelimiter start="c\?\\\\" end="$" contains=zigMultilineStringPrefix display + +syntax keyword zigTodo contained TODO + +syntax region zigString matchgroup=zigStringDelimiter start=+c\?"+ skip=+\\\\\|\\"+ end=+"+ oneline contains=zigEscape,zigEscapeUnicode,zigEscapeError,@Spell +syntax match zigEscapeError display contained /\\./ +syntax match zigEscape display contained /\\\([nrt\\'"]\|x\x\{2}\)/ +syntax match zigEscapeUnicode display contained /\\\(u\x\{4}\|U\x\{6}\)/ + +highlight default link zigDecNumber zigNumber +highlight default link zigHexNumber zigNumber +highlight default link zigOctNumber zigNumber +highlight default link zigBinNumber zigNumber + +highlight default link zigBuiltinFn Statement +highlight default link zigKeyword Keyword +highlight default link zigType Type +highlight default link zigCommentLine Comment +highlight default link zigCommentLineDoc Comment +highlight default link zigDummyVariable Comment +highlight default link zigTodo Todo +highlight default link zigString String +highlight default link zigStringDelimiter String +highlight default link zigMultilineString String +highlight default link zigMultilineStringContent String +highlight default link zigMultilineStringPrefix String +highlight default link zigMultilineStringDelimiter Delimiter +highlight default link zigCharacterInvalid Error +highlight default link zigCharacterInvalidUnicode zigCharacterInvalid +highlight default link zigCharacter Character +highlight default link zigEscape Special +highlight default link zigEscapeUnicode zigEscape +highlight default link zigEscapeError Error +highlight default link zigBoolean Boolean +highlight default link zigNull Boolean +highlight default link zigConstant Constant +highlight default link zigNumber Number +highlight default link zigArrowCharacter zigOperator +highlight default link zigOperator Operator +highlight default link zigStructure Structure +highlight default link zigExecution Special +highlight default link zigMacro Macro +highlight default link zigConditional Conditional +highlight default link zigComparatorWord Keyword +highlight default link zigRepeat Repeat +highlight default link zigSpecial Special +highlight default link zigVarDecl Function +highlight default link zigPreProc PreProc +highlight default link zigException Exception + +delfunction s:syntax_keyword + +let b:current_syntax = "zig" + +let &cpo = s:cpo_save +unlet! s:cpo_save diff --git a/runtime/syntax/zir.vim b/runtime/syntax/zir.vim new file mode 100644 index 0000000000..6553d322b7 --- /dev/null +++ b/runtime/syntax/zir.vim @@ -0,0 +1,49 @@ +" Vim syntax file +" Language: Zir +" Upstream: https://github.com/ziglang/zig.vim + +if exists("b:current_syntax") + finish +endif +let b:current_syntax = "zir" + +syn region zirCommentLine start=";" end="$" contains=zirTodo,@Spell + +syn region zirBlock start="{" end="}" transparent fold + +syn keyword zirKeyword primitive fntype int str as ptrtoint fieldptr deref asm unreachable export ref fn + +syn keyword zirTodo contained TODO + +syn region zirString start=+c\?"+ skip=+\\\\\|\\"+ end=+"+ oneline contains=zirEscape,zirEscapeUnicode,zirEscapeError,@Spell + +syn match zirEscapeError display contained /\\./ +syn match zirEscape display contained /\\\([nrt\\'"]\|x\x\{2}\)/ +syn match zirEscapeUnicode display contained /\\\(u\x\{4}\|U\x\{6}\)/ + +syn match zirDecNumber display "\<[0-9]\+\%(.[0-9]\+\)\=\%([eE][+-]\?[0-9]\+\)\=" +syn match zirHexNumber display "\<0x[a-fA-F0-9]\+\%([a-fA-F0-9]\+\%([pP][+-]\?[0-9]\+\)\?\)\=" +syn match zirOctNumber display "\<0o[0-7]\+" +syn match zirBinNumber display "\<0b[01]\+\%(.[01]\+\%([eE][+-]\?[0-9]\+\)\?\)\=" + +syn match zirGlobal display "[^a-zA-Z0-9_]\?\zs@[a-zA-Z0-9_]\+" +syn match zirLocal display "[^a-zA-Z0-9_]\?\zs%[a-zA-Z0-9_]\+" + +hi def link zirCommentLine Comment +hi def link zirTodo Todo + +hi def link zirKeyword Keyword + +hi def link zirString Constant + +hi def link zirEscape Special +hi def link zirEscapeUnicode zirEscape +hi def link zirEscapeError Error + +hi def link zirDecNumber Constant +hi def link zirHexNumber Constant +hi def link zirOctNumber Constant +hi def link zirBinNumber Constant + +hi def link zirGlobal Identifier +hi def link zirLocal Identifier 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 diff --git a/runtime/tutor/tutor.tutor.json b/runtime/tutor/tutor.tutor.json index bf3eae8586..e8628e2f0e 100644 --- a/runtime/tutor/tutor.tutor.json +++ b/runtime/tutor/tutor.tutor.json @@ -2,8 +2,8 @@ "expect": { "63": "This is text with **important information**", "64": "This is text with **important information**", - "71": "Document '&variable'", - "72": "Document '&variable'", + "71": "TODO: Document '&variable'", + "72": "TODO: Document '&variable'", "78": "# This is a level 1 header", "79": "# This is a level 1 header", "80": "### This is a level 3 header", |