Repository: xolox/vim-lua-ftplugin Branch: master Commit: bcbf91404668 Files: 14 Total size: 80.9 KB Directory structure: gitextract_ktfrvdj1/ ├── .gitignore ├── INSTALL.md ├── README.md ├── TODO.md ├── addon-info.json ├── autoload/ │ └── xolox/ │ ├── lua.vim │ └── lua_data.vim ├── doc/ │ └── ft_lua.txt ├── ftplugin/ │ └── lua.vim ├── misc/ │ └── lua-ftplugin/ │ ├── complete.lua │ ├── getsignatures.lua │ ├── globals.lua │ └── omnicomplete.lua └── plugin/ └── lua-ftplugin.vim ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ doc/tags ================================================ FILE: INSTALL.md ================================================ *Please note that the vim-lua-ftplugin plug-in requires my vim-misc plug-in which is separately distributed.* Unzip the most recent ZIP archives of the [vim-lua-ftplugin] [download-lua-ftplugin] and [vim-misc] [download-misc] plug-ins inside your Vim profile directory (usually this is `~/.vim` on UNIX and `%USERPROFILE%\vimfiles` on Windows), restart Vim and execute the command `:helptags ~/.vim/doc` (use `:helptags ~\vimfiles\doc` instead on Windows). If you prefer you can also use [Pathogen] [pathogen], [Vundle] [vundle] or a similar tool to install & update the [vim-lua-ftplugin] [github-lua-ftplugin] and [vim-misc] [github-misc] plug-ins using a local clone of the git repository. [download-lua-ftplugin]: http://peterodding.com/code/vim/downloads/lua-ftplugin.zip [download-misc]: http://peterodding.com/code/vim/downloads/misc.zip [github-lua-ftplugin]: http://github.com/xolox/vim-lua-ftplugin [github-misc]: http://github.com/xolox/vim-misc [pathogen]: http://www.vim.org/scripts/script.php?script_id=2332 [vundle]: https://github.com/gmarik/vundle ================================================ FILE: README.md ================================================ # Lua file type plug-in for the Vim text editor The [Lua][lua] file type plug-in for [Vim][vim] makes it easier to work with Lua source code in Vim by providing the following features: * The ['includeexpr'][inex] option is set so that the [gf][gf] (go to file) mapping knows how to resolve Lua module names using [package.path][pp] * The ['include'][inc] option is set so that Vim follows [dofile()][dof], [loadfile()][lof] and [require()][req] calls when looking for identifiers in included files (this works together with the ['includeexpr'][inex] option) * An automatic command is installed that runs `luac -p` when you save your Lua scripts. If `luac` reports any errors they are shown in the quick-fix list and Vim jumps to the line of the first error. If `luac -p` doesn't report any errors a check for undefined global variables is performed by parsing the output of `luac -p -l` * `K` (normal mode) and `` (insert mode) on a Lua function or 'method' call will try to open the relevant documentation in the [Lua Reference for Vim][lrv] * The ['completefunc'][cfu] option is set to allow completion of Lua 5.2 keywords, global variables and library members using Control-X Control-U * The ['omnifunc'][ofu] option is set to allow dynamic completion of the variables defined in all modules installed on the system using Control-X Control-O, however it needs to be explicitly enabled by setting the `lua_complete_omni` option because this functionality may have undesired side effects! When you invoke omni completion after typing `require '` or `require('` you get completion of module names ![Screenshot of omni completion](http://peterodding.com/code/vim/lua-ftplugin/screenshots/omni-completion.png) * Several [text-objects][tob] are defined so you can jump between blocks and functions * A pretty nifty hack of the [matchit plug-in][mit] is included: When the cursor is on a `function` or `return` keyword the `%` mapping cycles between the relevant keywords (`function`, `return`, `end`), this also works for branching statements (`if`, `elseif`, `else`, `end`) and looping statements (`for`, `while`, `repeat`, `until`, `end`) ## Installation *Please note that the vim-lua-ftplugin plug-in requires my vim-misc plug-in which is separately distributed.* Unzip the most recent ZIP archives of the [vim-lua-ftplugin] [download-lua-ftplugin] and [vim-misc] [download-misc] plug-ins inside your Vim profile directory (usually this is `~/.vim` on UNIX and `%USERPROFILE%\vimfiles` on Windows), restart Vim and execute the command `:helptags ~/.vim/doc` (use `:helptags ~\vimfiles\doc` instead on Windows). If you prefer you can also use [Pathogen] [pathogen], [Vundle] [vundle] or a similar tool to install & update the [vim-lua-ftplugin] [github-lua-ftplugin] and [vim-misc] [github-misc] plug-ins using a local clone of the git repository. Now try it out: Edit a Lua script and try any of the features documented above. Note that on Windows a command prompt window pops up whenever Lua is run as an external process. If this bothers you then you can install my [shell.vim][shell] plug-in which includes a [DLL][dll] that works around this issue. Once you've installed both plug-ins it should work out of the box! ## Options The Lua file type plug-in handles options as follows: First it looks at buffer local variables, then it looks at global variables and if neither exists a default is chosen. This means you can change how the plug-in works for individual buffers. For example to change the location of the Lua compiler used to check the syntax: " This sets the default value for all buffers. :let g:lua_compiler_name = '/usr/local/bin/luac' " This is how you change the value for one buffer. :let b:lua_compiler_name = '/usr/local/bin/lualint' ### The `lua_path` option This option contains the value of `package.path` as a string. You shouldn't need to change this because the plug-in is aware of [$LUA_PATH][pp] and if that isn't set the plug-in will run a Lua interpreter to get the value of [package.path][pp]. ### The `lua_check_syntax` option When you write a Lua script to disk the plug-in automatically runs the Lua compiler to check for syntax errors. To disable this behavior you can set this option to false (0): let g:lua_check_syntax = 0 You can manually check the syntax using the `:CheckSyntax` command. ### The `lua_check_globals` option When you write a Lua script to disk the plug-in automatically runs the Lua compiler to check for undefined global variables. To disable this behavior you can set this option to false (0): let g:lua_check_globals = 0 You can manually check the globals using the `:CheckGlobals` command. ### The `lua_interpreter_path` option The name or path of the Lua interpreter used to evaluate Lua scripts used by the plug-in (for example the script that checks for undefined global variables, see `:LuaCheckGlobals`). ### The `lua_internal` option If you're running a version of Vim that supports the Lua Interface for Vim (see [if_lua.txt][if_lua.txt]) then all Lua code evaluated by the Lua file type plug-in is evaluated using the Lua Interface for Vim. If the Lua Interface for Vim is not available the plug-in falls back to using an external Lua interpreter. You can set this to false (0) to force the plug-in to use an external Lua interpreter. ### The `lua_compiler_name` option The name or path of the Lua compiler used to check for syntax errors (defaults to `luac`). You can set this option to run the Lua compiler from a non-standard location or to run a dedicated syntax checker like [lualint][ll]. ### The `lua_compiler_args` option The argument(s) required by the compiler or syntax checker (defaults to `-p`). ### The `lua_error_format` option If you use a dedicated syntax checker you may need to change this option to reflect the format of the messages printed by the syntax checker. ### The `lua_complete_keywords` option To disable completion of keywords you can set this option to false (0). ### The `lua_complete_globals` option To disable completion of global functions you can set this option to false (0). ### The `lua_complete_library` option To disable completion of library functions you can set this option to false (0). ### The `lua_complete_dynamic` option When you type a dot after a word the Lua file type plug-in will automatically start completion. To disable this behavior you can set this option to false (0). ### The `lua_complete_omni` option This option is disabled by default for two reasons: * The omni completion support works by enumerating and loading all installed modules. **If module loading has side effects this can have unintended consequences!** * Because all modules installed on the system are loaded, collecting the completion candidates can be slow. After the first run the completion candidates are cached so this will only bother you once (until you restart Vim). If you want to use the omni completion despite the warnings above, execute the following command: :let g:lua_complete_omni = 1 Now when you type Control-X Control-O Vim will hang for a moment, after which you should be presented with an enormous list of completion candidates :-) ### The `lua_omni_blacklist` option If you like the omni completion mode but certain modules are giving you trouble (for example crashing Vim) you can exclude such modules from being loaded by the omni completion. You can do so by setting `lua_omni_blacklist` to a list of strings containing Vim regular expression patterns. The patterns are combined as follows: " Here's the black list: let g:lua_omni_blacklist = ['pl\.strict', 'lgi\..'] " Here's the resulting regular expression pattern: '^\(pl\.strict\|lgi\..\)$' The example above prevents the module `pl.strict` and all modules with the prefix `lgi.` from being loaded. ### The `lua_safe_omni_modules` option To track down modules that cause side effects while loading, setting :let g:lua_safe_omni_modules = 1 restricts the modules to be loaded to the standard Lua modules - which should be safe to load - and provides a list of modules that would have been loaded if this option was not set via the `:messages` command. With this list, the `lua_omni_blacklist` can be iteratively refined to exclude offending modules from omni completion module loading. Note that the ['verbose'] [] option has to be set to 1 or higher for the list to be recorded. ### The `lua_define_completefunc` option By default the Lua file type plug-in sets the ['completefunc'] [] option so that Vim can complete Lua keywords, global variables and library members using Control-X Control-U. If you don't want the 'completefunc' option to be changed by the plug-in, you can set this option to zero (false) in your [vimrc script] [vimrc]: :let g:lua_define_completefunc = 0 ### The `lua_define_omnifunc` option By default the Lua file type plug-in sets the ['omnifunc'] [] option so that Vim can complete the names of all Lua modules installed on the local system. If you don't want the 'omnifunc' option to be changed by the plug-in, you can set this option to zero (false) in your [vimrc script] [vimrc]: :let g:lua_define_omnifunc = 0 ### The `lua_define_completion_mappings` option By default the Lua file type plug-in defines insert mode mappings so that the plug-in is called whenever you type a single quote, double quote or a dot inside a Lua buffer. This enables context sensitive completion. If you don't like these mappings you can set this option to zero (false). In that case the mappings will not be defined. ## Commands ### The `:LuaCheckSyntax` command Check the current file for syntax errors using the Lua compiler. This command is executed automatically when you write a Lua script to disk (i.e. when you save your changes) unless `lua_check_syntax` is false. ### The `:LuaCheckGlobals` command Check the current file for undefined global variables. This command is executed automatically when you write a Lua script to disk (i.e. when you save your changes) unless `lua_check_globals` is false or syntax errors were detected. ## Contact If you have questions, bug reports, suggestions, etc. the author can be contacted at . The latest version is available at and . If you like this plug-in please vote for it on [Vim Online][script]. ## License This software is licensed under the [MIT license](http://en.wikipedia.org/wiki/MIT_License). © 2014 Peter Odding <>. Thanks go out to everyone who has helped to improve the Lua file type plug-in for Vim (whether through pull requests, bug reports or personal e-mails). ['verbose']: http://vimdoc.sourceforge.net/htmldoc/options.html#'verbose' ['completefunc']: http://vimdoc.sourceforge.net/htmldoc/options.html#'completefunc' ['omnifunc']: http://vimdoc.sourceforge.net/htmldoc/options.html#'omnifunc' [cfu]: http://vimdoc.sourceforge.net/htmldoc/options.html#%27completefunc%27 [dll]: http://en.wikipedia.org/wiki/Dynamic-link_library [dof]: http://www.lua.org/manual/5.2/manual.html#pdf-dofile [download-lua-ftplugin]: http://peterodding.com/code/vim/downloads/lua-ftplugin.zip [download-misc]: http://peterodding.com/code/vim/downloads/misc.zip [gf]: http://vimdoc.sourceforge.net/htmldoc/editing.html#gf [github-lua-ftplugin]: http://github.com/xolox/vim-lua-ftplugin [github-misc]: http://github.com/xolox/vim-misc [if_lua.txt]: http://vimdoc.sourceforge.net/htmldoc/if_lua.html#if_lua.txt [inc]: http://vimdoc.sourceforge.net/htmldoc/options.html#%27include%27 [inex]: http://vimdoc.sourceforge.net/htmldoc/options.html#%27includeexpr%27 [ll]: http://lua-users.org/wiki/LuaLint [lof]: http://www.lua.org/manual/5.2/manual.html#pdf-loadfile [lrv]: http://www.vim.org/scripts/script.php?script_id=1291 [lua]: http://www.lua.org/ [mit]: http://vimdoc.sourceforge.net/htmldoc/usr_05.html#matchit-install [ofu]: http://vimdoc.sourceforge.net/htmldoc/options.html#%27omnifunc%27 [pathogen]: http://www.vim.org/scripts/script.php?script_id=2332 [pp]: http://www.lua.org/manual/5.2/manual.html#pdf-package.path [req]: http://www.lua.org/manual/5.2/manual.html#pdf-require [script]: http://www.vim.org/scripts/script.php?script_id=3625 [shell]: http://peterodding.com/code/vim/shell/ [tob]: http://vimdoc.sourceforge.net/htmldoc/motion.html#text-objects [vim]: http://www.vim.org/ [vimrc]: http://vimdoc.sourceforge.net/htmldoc/starting.html#vimrc [vundle]: https://github.com/gmarik/vundle ================================================ FILE: TODO.md ================================================ # To-do list for the Lua file type plug-in for Vim * `BufReadCmd` automatic command that converts `*.luac` files to byte code listings :-) * Make the globals checking smarter so it can be enabled by default without being too much of a nuisance? ## Smarter completion Make completion smarter by supporting function arguments: * `collectgarbage()`: stop, restart, collect, count, step, setpause, setstepmul * `io.open()`, `io.popen()`: r, w, a, r+, w+, a+ * `file:read()`: \*n, \*a, \*l * `file:seek()`: set, cur, end * `file:setvbuf()`: no, full, line * `debug.sethook()`: c, r, l ================================================ FILE: addon-info.json ================================================ {"vim_script_nr": 3625, "dependencies": {"vim-misc": {}}, "homepage": "http://peterodding.com/code/vim/lua-ftplugin", "name": "vim-lua-ftplugin"} ================================================ FILE: autoload/xolox/lua.vim ================================================ " Vim auto-load script " Author: Peter Odding " Last Change: September 14, 2014 " URL: http://peterodding.com/code/vim/lua-ftplugin let g:xolox#lua#version = '0.8' let s:miscdir = expand(':p:h:h:h') . '/misc/lua-ftplugin' let s:omnicomplete_script = s:miscdir . '/omnicomplete.lua' let s:globals_script = s:miscdir . '/globals.lua' function! xolox#lua#includeexpr(fname) " {{{1 " Search module path for matching Lua scripts. let module = substitute(a:fname, '\.', '/', 'g') for template in xolox#lua#getsearchpath('$LUA_PATH', 'package.path') let expanded = substitute(template, '?', module, 'g') call xolox#misc#msg#debug("lua.vim %s: Expanded %s -> %s", g:xolox#lua#version, template, expanded) if filereadable(expanded) call xolox#misc#msg#debug("lua.vim %s: Matched existing file %s", g:xolox#lua#version, expanded) return expanded endif endfor " Default to given name. return a:fname endfunction function! xolox#lua#getsearchpath(envvar, luavar) " {{{1 let path = '' if xolox#misc#option#get('lua_internal', has('lua')) " Try to get the search path using the Lua Interface for Vim. try redir => path execute 'silent lua print(' . a:luavar . ')' redir END call xolox#misc#msg#debug("lua.vim %s: Got %s from Lua Interface for Vim", g:xolox#lua#version, a:luavar) catch redir END endtry endif if empty(path) let path = eval(a:envvar) if !empty(path) call xolox#misc#msg#debug("lua.vim %s: Got %s from %s", g:xolox#lua#version, a:luavar, a:envvar) else try let interpreter = xolox#misc#escape#shell(xolox#misc#option#get('lua_interpreter_path', 'lua')) let command = printf('%s -e "io.write(%s)"', interpreter, a:luavar) let path = xolox#misc#os#exec({'command': command})['stdout'][0] call xolox#misc#msg#debug("lua.vim %s: Got %s from external Lua interpreter", g:xolox#lua#version, a:luavar) catch call xolox#misc#msg#warn("lua.vim %s: Failed to get %s from external Lua interpreter: %s", g:xolox#lua#version, a:luavar, v:exception) endtry endif endif return split(xolox#misc#str#trim(path), ';') endfunction function! xolox#lua#autocheck() " {{{1 if &filetype == 'lua' let success = 1 if xolox#misc#option#get('lua_check_syntax', 1) let success = xolox#lua#checksyntax() endif if xolox#misc#option#get('lua_check_globals', 0) && success call xolox#lua#checkglobals(0) endif endif endfunction function! xolox#lua#checksyntax() " {{{1 let compiler_name = xolox#misc#option#get('lua_compiler_name', 'luac') let compiler_args = xolox#misc#option#get('lua_compiler_args', '-p') let error_format = xolox#misc#option#get('lua_error_format', 'luac: %f:%l: %m') if !executable(compiler_name) let message = "lua.vim %s: The configured Lua compiler" let message .= " doesn't seem to be available! I'm disabling" let message .= " automatic syntax checking for Lua scripts." let g:lua_check_syntax = 0 call xolox#misc#msg#warn(message, g:xolox#lua#version) return 1 endif " Check for errors using my shell.vim plug-in so that executing " luac.exe on Windows doesn't pop up the nasty console window. call xolox#misc#msg#debug("lua.vim %s: Checking syntax of '%s' using Lua compiler ..", g:xolox#lua#version, expand('%')) let command = [compiler_name, compiler_args, xolox#misc#escape#shell(expand('%'))] let output = xolox#misc#os#exec({'command': join(command) . ' 2>&1', 'check': 0})['stdout'] if empty(output) " Clear location list. call setloclist(winnr(), [], 'r') lclose return 1 endif " Save the errors to a file we can load with :lgetfile. let errorfile = tempname() call writefile(output, errorfile) " Remember the original values of these options. let mp_save = &makeprg let efm_save = &errorformat try " Temporarily change the options. let &makeprg = compiler_name let &errorformat = error_format let winnr = winnr() let filename = expand('%:t') execute 'lgetfile' fnameescape(errorfile) lwindow if winnr() != winnr let message = ['Syntax errors reported by', compiler_name, compiler_args, filename] let w:quickfix_title = join(message) execute winnr . 'wincmd w' endif call s:highlighterrors() finally " Restore the options. let &makeprg = mp_save let &errorformat = efm_save " Cleanup the file with errors. call delete(errorfile) endtry return 0 endfunction function! s:highlighterrors() let hlgroup = 'luaCompilerError' if !hlexists(hlgroup) execute 'highlight def link' hlgroup 'Error' else call clearmatches() endif let pattern = '^\%%%il.*\n\?' for entry in getqflist() call matchadd(hlgroup, '\%' . min([entry.lnum, line('$')]) . 'l') call xolox#misc#msg#warn("lua.vim %s: Syntax error on line %i: %s", g:xolox#lua#version, entry.lnum, entry.text) endfor endfunction function! xolox#lua#checkglobals(verbose) " {{{1 let curfile = expand('%') call xolox#misc#msg#debug("lua.vim %s: Checking for undefined globals in '%s' using '%s' ..", g:xolox#lua#version, curfile, s:globals_script) let compiler = xolox#misc#option#get('lua_compiler_name', 'luac') let output = xolox#lua#dofile(s:globals_script, [compiler, curfile, a:verbose]) call setqflist(eval('[' . join(output, ',') . ']'), 'r') cwindow endfunction function! xolox#lua#help() " {{{1 " Get the expression under the cursor. let cword = '' try let isk_save = &isk set iskeyword+=.,: let cword = expand('') finally let &isk = isk_save endtry if cword != '' try call s:lookupmethod(cword, 'lrv-string.', '\v<(byte|char|dump|g?find|format|len|lower|g?match|rep|reverse|g?sub|upper)>') call s:lookupmethod(cword, 'lrv-file:', '\v<(close|flush|lines|read|seek|setvbuf|write)>') call s:lookupmethod(cword, '', '\v:\w+>') call s:lookuptopic('lrv-' . cword) call s:lookuptopic(cword) call s:lookuptopic('luarefvim.txt') help catch /^done$/ return endtry endif help endfunction function! s:lookupmethod(cword, prefix, pattern) let method = matchstr(a:cword, a:pattern) if method != '' let identifier = a:prefix . method call xolox#misc#msg#debug("lua.vim %s: Translating '%s' -> '%s'", g:xolox#lua#version, a:cword, identifier) call s:lookuptopic(identifier) endif endfunction function! s:lookuptopic(topic) try " Lookup the given topic in Vim's help files. execute 'help' escape(a:topic, ' []*?') " Abuse exceptions for non local jumping. throw 'done' catch /^Vim\%((\a\+)\)\=:E149/ " Ignore E149: Sorry, no help for . return endtry endfunction function! xolox#lua#jumpblock(forward) " {{{1 let start = '\<\%(for\|function\|if\|repeat\|while\)\>' let middle = '\<\%(elseif\|else\)\>' let end = '\<\%(end\|until\)\>' let flags = a:forward ? '' : 'b' return searchpair(start, middle, end, flags, '!xolox#lua#tokeniscode()') endfunction function! s:getfunscope() let firstpos = [0, 1, 1, 0] let lastpos = getpos('$') while search('\', 'bW') if xolox#lua#tokeniscode() let firstpos = getpos('.') break endif endwhile if xolox#lua#jumpblock(1) let lastpos = getpos('.') endif return [firstpos, lastpos] endfunction function! xolox#lua#jumpthisfunc(forward) " {{{1 let cpos = [line('.'), col('.')] let fpos = [1, 1] let lpos = [line('$'), 1] while search('\', a:forward ? 'W' : 'bW') if xolox#lua#tokeniscode() break endif endwhile let cursorline = line('.') let [firstpos, lastpos] = s:getfunscope() if cursorline == (a:forward ? lastpos : firstpos)[1] " make the mapping repeatable (line wise at least) execute a:forward ? (lastpos[1] + 1) : (firstpos[1] - 1) let [firstpos, lastpos] = s:getfunscope() endif call setpos('.', a:forward ? lastpos : firstpos) endfunction function! xolox#lua#jumpotherfunc(forward) " {{{1 let view = winsaveview() " jump to the start/end of the function call xolox#lua#jumpthisfunc(a:forward) " search for the previous/next function while search('\', a:forward ? 'W' : 'bW') " ignore strings and comments containing 'function' if xolox#lua#tokeniscode() return 1 endif endwhile call winrestview(view) endfunction function! xolox#lua#tokeniscode() " {{{1 return s:getsynid(0) !~? 'string\|comment' endfunction function! s:getsynid(transparent) let id = synID(line('.'), col('.') - 1, 1) if a:transparent let id = synIDtrans(id) endif return synIDattr(id, 'name') endfunction if exists('loaded_matchit') function! xolox#lua#matchit() " {{{1 let cword = expand('') if cword == 'end' let s = ['function', 'if', 'for', 'while'] let e = ['end'] unlet! b:match_skip elseif cword =~ '^\(function\|return\|yield\)$' let s = ['function'] let m = ['return', 'yield'] let e = ['end'] let b:match_skip = "xolox#lua#matchit_ignore('^luaCond$')" let b:match_skip .= " || (expand('') == 'end' && xolox#lua#matchit_ignore('^luaStatement$'))" elseif cword =~ '^\(for\|in\|while\|do\|repeat\|until\|break\)$' let s = ['for', 'repeat', 'while'] let m = ['break'] let e = ['end', 'until'] let b:match_skip = "xolox#lua#matchit_ignore('^\\(luaCond\\|luaFunction\\)$')" elseif cword =~ '\(if\|then\|elseif\|else\)$' let s = ['if'] let m = ['elseif', 'else'] let e = ['end'] let b:match_skip = "xolox#lua#matchit_ignore('^\\(luaFunction\\|luaStatement\\)$')" else let s = ['for', 'function', 'if', 'repeat', 'while'] let m = ['break', 'elseif', 'else', 'return'] let e = ['eend', 'until'] unlet! b:match_skip endif let p = '\<\(' . join(s, '\|') . '\)\>' if exists('m') let p .= ':\<\(' . join(m, '\|') . '\)\>' endif return p . ':\<\(' . join(e, '\|') . '\)\>' endfunction function! xolox#lua#matchit_ignore(ignored) " {{{1 let word = expand('') let type = s:getsynid(0) return type =~? a:ignored || type =~? 'string\|comment' endfunction endif function! xolox#lua#completefunc(init, base) " {{{1 if a:init return s:getcompletionprefix() endif let items = [] if xolox#misc#option#get('lua_complete_keywords', 1) call extend(items, g:xolox#lua_data#keywords) endif if xolox#misc#option#get('lua_complete_globals', 1) call extend(items, g:xolox#lua_data#globals) endif if xolox#misc#option#get('lua_complete_library', 1) call extend(items, g:xolox#lua_data#library) endif let pattern = '^' . xolox#misc#escape#pattern(a:base) call filter(items, 'v:val.word =~ pattern') return s:addsignatures(items) endfunction function! s:getcompletionprefix() let text_before_cursor = strpart(getline('.'), 0, col('.') - 1) let completion_prefix = matchstr(text_before_cursor, '\w\+\.\?\w*$') call xolox#misc#msg#debug("lua.vim %s: Matched completion prefix %s.", g:xolox#lua#version, string(completion_prefix)) return col('.') - len(completion_prefix) - 1 endfunction function! s:addsignatures(entries) for entry in a:entries let signature = xolox#lua#getsignature(entry.word) if !empty(signature) && signature != entry.word let entry.menu = signature endif endfor return a:entries endfunction function! xolox#lua#getsignature(identifier) " {{{1 let identifier = substitute(a:identifier, '()$', '', '') let signature = get(g:xolox#lua_data#signatures, identifier, '') if empty(signature) let signature = get(g:xolox#lua_data#signatures, 'string.' . identifier, '') endif if empty(signature) let signature = get(g:xolox#lua_data#signatures, 'file:' . identifier, '') endif return signature endfunction function! xolox#lua#omnifunc(init, base) " {{{1 if a:init return s:getcompletionprefix() elseif !xolox#misc#option#get('lua_complete_omni', 0) throw printf("lua.vim %s: omni completion needs to be explicitly enabled, see the readme!", g:xolox#lua#version) endif if !exists('s:omnifunc_modules') let s:omnifunc_modules = xolox#lua#getomnimodules() endif if !exists('s:omnifunc_variables') let s:omnifunc_variables = xolox#lua#getomnivariables(s:omnifunc_modules) call s:addsignatures(s:omnifunc_variables) endif " FIXME When you type "require'" without a space in between " the getline('.') call below returns an empty string?! let pattern = '^' . xolox#misc#escape#pattern(a:base) if getline('.') =~ 'require[^''"]*[''"]' let candidates = filter(copy(s:omnifunc_modules), 'v:val =~ pattern') call xolox#misc#msg#debug("lua.vim %s: Completing %i module name(s).", g:xolox#lua#version, len(candidates)) elseif a:base == '' let candidates = s:omnifunc_variables call xolox#misc#msg#debug("lua.vim %s: Completing all %i omni variable(s).", g:xolox#lua#version, len(candidates)) else let candidates = filter(copy(s:omnifunc_variables), 'v:val.word =~ pattern') call xolox#misc#msg#debug("lua.vim %s: Completing %i omni variable(s) matching filter.", g:xolox#lua#version, len(candidates)) endif return candidates endfunction function! xolox#lua#getomnimodules() " {{{1 let starttime = xolox#misc#timer#start() " Find all source & binary modules available on the module search path. let modulemap = {} let luapath = xolox#lua#getsearchpath('$LUA_PATH', 'package.path') let luacpath = xolox#lua#getsearchpath('$LUA_CPATH', 'package.cpath') for searchpath in [luapath, luacpath] call s:expandsearchpath(searchpath, modulemap) endfor let modules = keys(modulemap) " Always include the standard library modules. call extend(modules, ['bit32', 'coroutine', 'debug', 'io', 'math', 'os', 'package', 'string', 'table']) call sort(modules, 1) let blacklist = xolox#misc#option#get('lua_omni_blacklist', []) let pattern = printf('^\(%s\)$', join(blacklist, '\|')) call filter(modules, 'v:val !~ pattern') let msg = "lua.vim %s: Collected %i module names for omni completion in %s." call xolox#misc#timer#stop(msg, g:xolox#lua#version, len(modules), starttime) if xolox#misc#option#get('lua_safe_omni_modules', 0) == 1 call xolox#misc#msg#debug("lua.vim %s: Loading Lua standard library modules only because g:lua_safe_omni_modules is set.", g:xolox#lua#version) call xolox#misc#msg#debug("lua.vim %s: Would have loaded the following modules: %s", g:xolox#lua#version, join(modules, ' ')) return ['bit32', 'coroutine', 'debug', 'io', 'math', 'os', 'package', 'string', 'table'] endif return modules endfunction function! s:expandsearchpath(searchpath, modules) " Collect the names of all installed modules by traversing the search paths. for template in a:searchpath let components = split(template, '?') if len(components) != 2 let msg = "lua.vim %s: Failed to parse search path entry: %s" call xolox#misc#msg#debug(msg, g:xolox#lua#version, template) continue endif let [prefix, suffix] = components " XXX Never recursively search current working directory because " it might be arbitrarily deep, e.g. when working directory is / if prefix =~ '^.[\\/]$' let msg = "lua.vim %s: Refusing to expand dangerous search path entry: %s" call xolox#misc#msg#debug(msg, g:xolox#lua#version, template) continue endif let pattern = substitute(template, '?', '**/*', 'g') call xolox#misc#msg#debug("lua.vim %s: Transformed %s -> %s", g:xolox#lua#version, template, pattern) let msg = "lua.vim %s: Failed to convert pathname to module name, %s doesn't match! (%s: '%s', pathname: '%s')" for pathname in split(glob(pattern), "\n") if pathname[0 : len(prefix)-1] != prefix " Validate prefix of resulting pathname. call xolox#misc#msg#warn(msg, g:xolox#lua#version, 'prefix', 'prefix', prefix, pathname) elseif pathname[-len(suffix) : -1] != suffix " Validate suffix of resulting pathname. call xolox#misc#msg#warn(msg, g:xolox#lua#version, 'suffix', 'suffix', suffix, pathname) elseif pathname !~ 'test' let relative = pathname[len(prefix) : -len(suffix)-1] let modulename = substitute(relative, '[\\/]\+', '.', 'g') let a:modules[modulename] = 1 call xolox#misc#msg#debug("lua.vim %s: Transformed '%s' -> '%s'", g:xolox#lua#version, pathname, modulename) endif endfor endfor endfunction function! xolox#lua#getomnivariables(modules) " {{{1 let starttime = xolox#misc#timer#start() let output = xolox#lua#dofile(s:omnicomplete_script, a:modules) let variables = eval('[' . join(output, ',') . ']') call sort(variables, 1) let msg = "lua.vim %s: Collected %i variables for omni completion in %s." call xolox#misc#timer#stop(msg, g:xolox#lua#version, len(variables), starttime) return variables endfunction function! xolox#lua#completedynamic(type) " {{{1 if xolox#misc#option#get('lua_complete_dynamic', 1) && s:getsynid(1) !~? 'string\|comment\|keyword' if (a:type == "'" || a:type == '"') let prefix = strpart(getline('.'), 0, col('.') - 1) if xolox#misc#option#get('lua_complete_omni', 0) && prefix =~ '\\" elseif prefix =~ '\<\(dofile\|loadfile\|io\.open\|io\.lines\|os\.remove\)\s*(\?\s*$' return a:type . "\\" endif elseif a:type == '.' let column = col('.') - 1 " Gotcha: even though '.' is remapped it counts as a column? if column && getline('.')[column - 1] =~ '\w' " This results in "Pattern not found" when no completion candidates " are available, which is kind of annoying. But I don't know of an " alternative to :silent that can be used inside of " mappings?! if xolox#misc#option#get('lua_complete_omni', 0) return a:type . "\\" else return a:type . "\\" endif endif endif endif return a:type endfunction function! xolox#lua#tweakoptions() " {{{1 if &filetype == 'lua' let s:completeopt_save = &cot set completeopt+=longest elseif exists('s:completeopt_save') let &completeopt = s:completeopt_save endif endfunction function! xolox#lua#dofile(pathname, arguments) " {{{1 if xolox#misc#option#get('lua_internal', has('lua')) " Use the Lua Interface for Vim. call xolox#misc#msg#debug("lua.vim %s: Running '%s' using Lua Interface for Vim ..", g:xolox#lua#version, a:pathname) redir => output silent lua << EOL local script = vim.eval('a:pathname') local arguments = vim.eval('a:arguments') if type(arguments) == 'userdata' then -- At some point the Lua Interface for Vim started using userdata proxy -- objects for Vim lists and dictionaries (refer to :help lua-list). -- The Lua file type plug-in for Vim wasn't expecting this so broke -- with errors like: -- -- * bad argument #1 to 'insert' (table expected, got userdata) -- * bad argument #1 to 'ipairs' (table expected, got userdata) -- -- The switch to userdata makes sense but these userdata objects don't -- behave like Lua tables at all (they're not intended to) which is bad -- for us, so we translate the userdata objects back into proper Lua -- tables (e.g. with one based indices). local arguments_as_lua_table = {} -- Userdata proxies for Vim lists start at index zero. for i = 0, #arguments - 1 do table.insert(arguments_as_lua_table, arguments[i]) end arguments = arguments_as_lua_table end arguments[0] = script arg = arguments dofile(script) EOL redir END return split(output, "\n") else " Use the command line Lua interpreter. call xolox#misc#msg#debug("lua.vim %s: Running '%s' using command line Lua interpreter ..", g:xolox#lua#version, a:pathname) let interpreter = xolox#misc#escape#shell(xolox#misc#option#get('lua_interpreter_path', 'lua')) let pathname = xolox#misc#escape#shell(a:pathname) let arguments = join(map(a:arguments, 'xolox#misc#escape#shell(v:val)')) let command = printf('%s %s %s', interpreter, pathname, arguments) return xolox#misc#os#exec({'command': command})['stdout'] endif endfunction " vim: ts=2 sw=2 et ================================================ FILE: autoload/xolox/lua_data.vim ================================================ " Vim auto-load script " Author: Peter Odding " Last Change: July 6, 2014 " URL: http://peterodding.com/code/vim/lua-ftplugin " This script contains static user completion data based on the Lua 5.2 " reference manual and implementation. " Enable line continuation. let s:cpo_save = &cpo set cpoptions-=C " Keywords. {{{1 let g:xolox#lua_data#keywords = [ \ { 'word': 'and', 'kind': 'k' }, \ { 'word': 'break', 'kind': 'k' }, \ { 'word': 'do', 'kind': 'k' }, \ { 'word': 'else', 'kind': 'k' }, \ { 'word': 'elseif', 'kind': 'k' }, \ { 'word': 'end', 'kind': 'k' }, \ { 'word': 'false', 'kind': 'k' }, \ { 'word': 'for', 'kind': 'k' }, \ { 'word': 'function', 'kind': 'k' }, \ { 'word': 'goto', 'kind': 'k' }, \ { 'word': 'if', 'kind': 'k' }, \ { 'word': 'in', 'kind': 'k' }, \ { 'word': 'local', 'kind': 'k' }, \ { 'word': 'nil', 'kind': 'k' }, \ { 'word': 'not', 'kind': 'k' }, \ { 'word': 'or', 'kind': 'k' }, \ { 'word': 'repeat', 'kind': 'k' }, \ { 'word': 'return', 'kind': 'k' }, \ { 'word': 'then', 'kind': 'k' }, \ { 'word': 'true', 'kind': 'k' }, \ { 'word': 'until', 'kind': 'k' }, \ { 'word': 'while', 'kind': 'k' }, \ ] " Global variables. {{{1 let g:xolox#lua_data#globals = [ \ { 'word': '_G', 'kind': 'v' }, \ { 'word': '_ENV', 'kind': 'v' }, \ { 'word': '_VERSION', 'kind': 'v' }, \ { 'word': 'arg', 'kind': 'v' }, \ { 'word': 'assert()', 'kind': 'f' }, \ { 'word': 'bit32', 'kind': 'v' }, \ { 'word': 'collectgarbage()', 'kind': 'f' }, \ { 'word': 'coroutine', 'kind': 'v' }, \ { 'word': 'debug', 'kind': 'v' }, \ { 'word': 'dofile()', 'kind': 'f' }, \ { 'word': 'error()', 'kind': 'f' }, \ { 'word': 'getmetatable()', 'kind': 'f' }, \ { 'word': 'io', 'kind': 'v' }, \ { 'word': 'ipairs()', 'kind': 'f' }, \ { 'word': 'load()', 'kind': 'f' }, \ { 'word': 'loadfile()', 'kind': 'f' }, \ { 'word': 'math', 'kind': 'v' }, \ { 'word': 'next()', 'kind': 'f' }, \ { 'word': 'os', 'kind': 'v' }, \ { 'word': 'package', 'kind': 'v' }, \ { 'word': 'pairs()', 'kind': 'f' }, \ { 'word': 'pcall()', 'kind': 'f' }, \ { 'word': 'print()', 'kind': 'f' }, \ { 'word': 'rawequal()', 'kind': 'f' }, \ { 'word': 'rawget()', 'kind': 'f' }, \ { 'word': 'rawlen()', 'kind': 'f' }, \ { 'word': 'rawset()', 'kind': 'f' }, \ { 'word': 'require()', 'kind': 'f' }, \ { 'word': 'select()', 'kind': 'f' }, \ { 'word': 'setmetatable()', 'kind': 'f' }, \ { 'word': 'string', 'kind': 'v' }, \ { 'word': 'table', 'kind': 'v' }, \ { 'word': 'tonumber()', 'kind': 'f' }, \ { 'word': 'tostring()', 'kind': 'f' }, \ { 'word': 'type()', 'kind': 'f' }, \ { 'word': 'xpcall()', 'kind': 'f' }, \ ] " Standard library identifiers. {{{1 let g:xolox#lua_data#library = [ \ { 'word': 'bit32.arshift()', 'kind': 'f'}, \ { 'word': 'bit32.band()', 'kind': 'f' }, \ { 'word': 'bit32.bnot()', 'kind': 'f' }, \ { 'word': 'bit32.bor()', 'kind': 'f' }, \ { 'word': 'bit32.btest()', 'kind': 'f' }, \ { 'word': 'bit32.bxor()', 'kind': 'f' }, \ { 'word': 'bit32.extract()', 'kind': 'f' }, \ { 'word': 'bit32.replace()', 'kind': 'f' }, \ { 'word': 'bit32.lrotate()', 'kind': 'f' }, \ { 'word': 'bit32.lshift()', 'kind': 'f' }, \ { 'word': 'bit32.rrotate()', 'kind': 'f' }, \ { 'word': 'bit32.rshift()', 'kind': 'f' }, \ { 'word': 'coroutine.create()', 'kind': 'f' }, \ { 'word': 'coroutine.resume()', 'kind': 'f' }, \ { 'word': 'coroutine.running()', 'kind': 'f' }, \ { 'word': 'coroutine.status()', 'kind': 'f' }, \ { 'word': 'coroutine.wrap()', 'kind': 'f' }, \ { 'word': 'coroutine.yield()', 'kind': 'f' }, \ { 'word': 'debug.debug()', 'kind': 'f' }, \ { 'word': 'debug.gethook()', 'kind': 'f' }, \ { 'word': 'debug.getinfo()', 'kind': 'f' }, \ { 'word': 'debug.getlocal()', 'kind': 'f' }, \ { 'word': 'debug.getmetatable()', 'kind': 'f' }, \ { 'word': 'debug.getregistry()', 'kind': 'f' }, \ { 'word': 'debug.getupvalue()', 'kind': 'f' }, \ { 'word': 'debug.getuservalue()', 'kind': 'f' }, \ { 'word': 'debug.sethook()', 'kind': 'f' }, \ { 'word': 'debug.setlocal()', 'kind': 'f' }, \ { 'word': 'debug.setmetatable()', 'kind': 'f' }, \ { 'word': 'debug.setupvalue()', 'kind': 'f' }, \ { 'word': 'debug.setuservalue()', 'kind': 'f' }, \ { 'word': 'debug.traceback()', 'kind': 'f' }, \ { 'word': 'debug.upvalueid()', 'kind': 'f' }, \ { 'word': 'debug.upvaluejoin()', 'kind': 'f' }, \ { 'word': 'io.close()', 'kind': 'f' }, \ { 'word': 'io.flush()', 'kind': 'f' }, \ { 'word': 'io.input()', 'kind': 'f' }, \ { 'word': 'io.lines()', 'kind': 'f' }, \ { 'word': 'io.open()', 'kind': 'f' }, \ { 'word': 'io.output()', 'kind': 'f' }, \ { 'word': 'io.popen()', 'kind': 'f' }, \ { 'word': 'io.read()', 'kind': 'f' }, \ { 'word': 'io.stderr', 'kind': 'm' }, \ { 'word': 'io.stdin', 'kind': 'm' }, \ { 'word': 'io.stdout', 'kind': 'm' }, \ { 'word': 'io.tmpfile()', 'kind': 'f' }, \ { 'word': 'io.type()', 'kind': 'f' }, \ { 'word': 'io.write()', 'kind': 'f' }, \ { 'word': 'math.abs()', 'kind': 'f' }, \ { 'word': 'math.acos()', 'kind': 'f' }, \ { 'word': 'math.asin()', 'kind': 'f' }, \ { 'word': 'math.atan()', 'kind': 'f' }, \ { 'word': 'math.atan2()', 'kind': 'f' }, \ { 'word': 'math.ceil()', 'kind': 'f' }, \ { 'word': 'math.cos()', 'kind': 'f' }, \ { 'word': 'math.cosh()', 'kind': 'f' }, \ { 'word': 'math.deg()', 'kind': 'f' }, \ { 'word': 'math.exp()', 'kind': 'f' }, \ { 'word': 'math.floor()', 'kind': 'f' }, \ { 'word': 'math.fmod()', 'kind': 'f' }, \ { 'word': 'math.frexp()', 'kind': 'f' }, \ { 'word': 'math.huge', 'kind': 'm' }, \ { 'word': 'math.ldexp()', 'kind': 'f' }, \ { 'word': 'math.log()', 'kind': 'f' }, \ { 'word': 'math.max()', 'kind': 'f' }, \ { 'word': 'math.min()', 'kind': 'f' }, \ { 'word': 'math.modf()', 'kind': 'f' }, \ { 'word': 'math.pi', 'kind': 'm' }, \ { 'word': 'math.pow()', 'kind': 'f' }, \ { 'word': 'math.rad()', 'kind': 'f' }, \ { 'word': 'math.random()', 'kind': 'f' }, \ { 'word': 'math.randomseed()', 'kind': 'f' }, \ { 'word': 'math.sin()', 'kind': 'f' }, \ { 'word': 'math.sinh()', 'kind': 'f' }, \ { 'word': 'math.sqrt()', 'kind': 'f' }, \ { 'word': 'math.tan()', 'kind': 'f' }, \ { 'word': 'math.tanh()', 'kind': 'f' }, \ { 'word': 'os.clock()', 'kind': 'f' }, \ { 'word': 'os.date()', 'kind': 'f' }, \ { 'word': 'os.difftime()', 'kind': 'f' }, \ { 'word': 'os.execute()', 'kind': 'f' }, \ { 'word': 'os.exit()', 'kind': 'f' }, \ { 'word': 'os.getenv()', 'kind': 'f' }, \ { 'word': 'os.remove()', 'kind': 'f' }, \ { 'word': 'os.rename()', 'kind': 'f' }, \ { 'word': 'os.setlocale()', 'kind': 'f' }, \ { 'word': 'os.time()', 'kind': 'f' }, \ { 'word': 'os.tmpname()', 'kind': 'f' }, \ { 'word': 'package.config', 'kind': 'm' }, \ { 'word': 'package.cpath', 'kind': 'm' }, \ { 'word': 'package.loaded', 'kind': 'm' }, \ { 'word': 'package.loadlib()', 'kind': 'f' }, \ { 'word': 'package.path', 'kind': 'm' }, \ { 'word': 'package.preload', 'kind': 'm' }, \ { 'word': 'package.searchers', 'kind': 'm' }, \ { 'word': 'package.searchpath()', 'kind': 'f' }, \ { 'word': 'string.byte()', 'kind': 'f' }, \ { 'word': 'string.char()', 'kind': 'f' }, \ { 'word': 'string.dump()', 'kind': 'f' }, \ { 'word': 'string.find()', 'kind': 'f' }, \ { 'word': 'string.format()', 'kind': 'f' }, \ { 'word': 'string.gmatch()', 'kind': 'f' }, \ { 'word': 'string.gsub()', 'kind': 'f' }, \ { 'word': 'string.len()', 'kind': 'f' }, \ { 'word': 'string.lower()', 'kind': 'f' }, \ { 'word': 'string.match()', 'kind': 'f' }, \ { 'word': 'string.rep()', 'kind': 'f' }, \ { 'word': 'string.reverse()', 'kind': 'f' }, \ { 'word': 'string.sub()', 'kind': 'f' }, \ { 'word': 'string.upper()', 'kind': 'f' }, \ { 'word': 'table.concat()', 'kind': 'f' }, \ { 'word': 'table.insert()', 'kind': 'f' }, \ { 'word': 'table.pack()', 'kind': 'f' }, \ { 'word': 'table.remove()', 'kind': 'f' }, \ { 'word': 'table.sort()', 'kind': 'f' }, \ { 'word': 'table.unpack()', 'kind': 'f' }, \ ] " Function signatures. {{{1 " Sources: " - http://www.lua.org/manual/5.2/manual.html#6 " - http://smherwig.org/lua/proc/index.html " - http://w3.impa.br/~diego/software/luasocket/reference.html let g:xolox#lua_data#signatures = { \ 'assert': 'assert(v [, message])', \ 'collectgarbage': 'collectgarbage([opt [, arg]])', \ 'dofile': 'dofile([filename])', \ 'error': 'error(message [, level])', \ 'getmetatable': 'getmetatable(object)', \ 'ipairs': 'ipairs(t)', \ 'load': 'load(ld [, source [, mode [, env]]])', \ 'loadfile': 'loadfile([filename [, mode [, env]]])', \ 'next': 'next(table [, index])', \ 'pairs': 'pairs(t)', \ 'pcall': 'pcall(f [, arg1, ...])', \ 'print': 'print(...)', \ 'rawequal': 'rawequal(v1, v2)', \ 'rawget': 'rawget(table, index)', \ 'rawlen': 'rawlen(v)', \ 'rawset': 'rawset(table, index, value)', \ 'select': 'select(index, ...)', \ 'setmetatable': 'setmetatable(table, metatable)', \ 'tonumber': 'tonumber(e [, base])', \ 'tostring': 'tostring(v)', \ 'type': 'type(v)', \ 'xpcall': 'xpcall(f, msgh [, arg1, ...])', \ 'coroutine.create': 'coroutine.create(f)', \ 'coroutine.resume': 'coroutine.resume(co [, val1, ...])', \ 'coroutine.running': 'coroutine.running()', \ 'coroutine.status': 'coroutine.status(co)', \ 'coroutine.wrap': 'coroutine.wrap(f)', \ 'coroutine.yield': 'coroutine.yield(...)', \ 'require': 'require(modname)', \ 'package.loadlib': 'package.loadlib(libname, funcname)', \ 'package.searchpath': 'package.searchpath(name, path [, sep [, rep]])', \ 'string.byte': 'string.byte(s [, i [, j]])', \ 'string.char': 'string.char(...)', \ 'string.dump': 'string.dump(function)', \ 'string.find': 'string.find(s, pattern [, init [, plain]])', \ 'string.format': 'string.format(formatstring, ...)', \ 'string.gmatch': 'string.gmatch(s, pattern)', \ 'string.gsub': 'string.gsub(s, pattern, repl [, n])', \ 'string.len': 'string.len(s)', \ 'string.lower': 'string.lower(s)', \ 'string.match': 'string.match(s, pattern [, init])', \ 'string.rep': 'string.rep(s, n [, sep])', \ 'string.reverse': 'string.reverse(s)', \ 'string.sub': 'string.sub(s, i [, j])', \ 'string.upper': 'string.upper(s)', \ 'table.concat': 'table.concat(table [, sep [, i [, j]]])', \ 'table.insert': 'table.insert(table, [pos,] value)', \ 'table.pack': 'table.pack(...)', \ 'table.remove': 'table.remove(table [, pos])', \ 'table.sort': 'table.sort(table [, comp])', \ 'table.unpack': 'table.unpack(list [, i [, j]])', \ 'math.abs': 'math.abs(x)', \ 'math.acos': 'math.acos(x)', \ 'math.asin': 'math.asin(x)', \ 'math.atan': 'math.atan(x)', \ 'math.atan2': 'math.atan2(y, x)', \ 'math.ceil': 'math.ceil(x)', \ 'math.cos': 'math.cos(x)', \ 'math.cosh': 'math.cosh(x)', \ 'math.deg': 'math.deg(x)', \ 'math.exp': 'math.exp(x)', \ 'math.floor': 'math.floor(x)', \ 'math.fmod': 'math.fmod(x, y)', \ 'math.frexp': 'math.frexp(x)', \ 'math.ldexp': 'math.ldexp(m, e)', \ 'math.log': 'math.log(x [, base])', \ 'math.max': 'math.max(x, ...)', \ 'math.min': 'math.min(x, ...)', \ 'math.modf': 'math.modf(x)', \ 'math.pow': 'math.pow(x, y)', \ 'math.rad': 'math.rad(x)', \ 'math.random': 'math.random([m [, n]])', \ 'math.randomseed': 'math.randomseed(x)', \ 'math.sin': 'math.sin(x)', \ 'math.sinh': 'math.sinh(x)', \ 'math.sqrt': 'math.sqrt(x)', \ 'math.tan': 'math.tan(x)', \ 'math.tanh': 'math.tanh(x)', \ 'bit32.arshift': 'bit32.arshift(x, disp)', \ 'bit32.band': 'bit32.band(expr)', \ 'bit32.bnot': 'bit32.bnot(x)', \ 'bit32.bor': 'bit32.bor(expr)', \ 'bit32.btest': 'bit32.btest(expr)', \ 'bit32.bxor': 'bit32.bxor(expr)', \ 'bit32.extract': 'bit32.extract(n, field [, width])', \ 'bit32.replace': 'bit32.replace(n, v, field [, width])', \ 'bit32.lrotate': 'bit32.lrotate(x, disp)', \ 'bit32.lshift': 'bit32.lshift(x, disp)', \ 'bit32.rrotate': 'bit32.rrotate(x, disp)', \ 'bit32.rshift': 'bit32.rshift(x, disp)', \ 'io.close': 'io.close([file])', \ 'io.flush': 'io.flush()', \ 'io.input': 'io.input([file])', \ 'io.lines': 'io.lines([filename ...])', \ 'io.open': 'io.open(filename [, mode])', \ 'io.output': 'io.output([file])', \ 'io.popen': 'io.popen(prog [, mode])', \ 'io.read': 'io.read(...)', \ 'io.tmpfile': 'io.tmpfile()', \ 'io.type': 'io.type(obj)', \ 'io.write': 'io.write(...)', \ 'file:close': 'file:close()', \ 'file:flush': 'file:flush()', \ 'file:lines': 'file:lines(...)', \ 'file:read': 'file:read(...)', \ 'file:seek': 'file:seek([whence [, offset]])', \ 'file:setvbuf': 'file:setvbuf(mode [, size])', \ 'file:write': 'file:write(...)', \ 'os.clock': 'os.clock()', \ 'os.date': 'os.date([format [, time]])', \ 'os.difftime': 'os.difftime(t2, t1)', \ 'os.execute': 'os.execute([command])', \ 'os.exit': 'os.exit([code [, close])', \ 'os.getenv': 'os.getenv(varname)', \ 'os.remove': 'os.remove(filename)', \ 'os.rename': 'os.rename(oldname, newname)', \ 'os.setlocale': 'os.setlocale(locale [, category])', \ 'os.time': 'os.time([table])', \ 'os.tmpname': 'os.tmpname()', \ 'debug.debug': 'debug.debug()', \ 'debug.gethook': 'debug.gethook([thread])', \ 'debug.getinfo': 'debug.getinfo([thread,] f [, what])', \ 'debug.getlocal': 'debug.getlocal([thread,] f, local)', \ 'debug.getmetatable': 'debug.getmetatable(value)', \ 'debug.getregistry': 'debug.getregistry()', \ 'debug.getupvalue': 'debug.getupvalue(f, up)', \ 'debug.getuservalue': 'debug.getuservalue(u)', \ 'debug.sethook': 'debug.sethook([thread,] hook, mask [, count])', \ 'debug.setlocal': 'debug.setlocal([thread,] level, local, value)', \ 'debug.setmetatable': 'debug.setmetatable(value, table)', \ 'debug.setupvalue': 'debug.setupvalue(f, up, value)', \ 'debug.setuservalue': 'debug.setuservalue(udata, value)', \ 'debug.traceback': 'debug.traceback([thread,] [message [, level]])', \ 'debug.upvalueid': 'debug.upvalueid(f, n)', \ 'debug.upvaluejoin': 'debug.upvaluejoin(f1, n1, f2, n2)', \ \ 'proc.kill': 'proc.kill(pid, [signal])', \ 'proc.killall': 'proc.killall(name, [signal])', \ 'proc.list': 'proc.list()', \ 'proc.pidof': 'proc.pidof(name)', \ \ 'ftp.get': 'ftp.get(url)', \ 'ftp.put': 'ftp.put(url, content)', \ 'http.request': 'http.request(url [, body])', \ 'ltn12.filter.chain': 'ltn12.filter.chain(filter1, filter2 [, ... filterN])', \ 'ltn12.filter.cycle': 'ltn12.filter.cycle(low [, ctx, extra])', \ 'ltn12.pump.all': 'ltn12.pump.all(source, sink)', \ 'ltn12.pump.step': 'ltn12.pump.step(source, sink)', \ 'ltn12.sink.chain': 'ltn12.sink.chain(filter, sink)', \ 'ltn12.sink.error': 'ltn12.sink.error(message)', \ 'ltn12.sink.file': 'ltn12.sink.file(handle, message)', \ 'ltn12.sink.simplify': 'ltn12.sink.simplify(sink)', \ 'ltn12.sink.table': 'ltn12.sink.table([table])', \ 'ltn12.source.cat': 'ltn12.source.cat(source1 [, source2, ..., sourceN])', \ 'ltn12.source.chain': 'ltn12.source.chain(source, filter)', \ 'ltn12.source.empty': 'ltn12.source.empty()', \ 'ltn12.source.error': 'ltn12.source.error(message)', \ 'ltn12.source.file': 'ltn12.source.file(handle, message)', \ 'ltn12.source.simplify': 'ltn12.source.simplify(source)', \ 'ltn12.source.string': 'ltn12.source.string(string)', \ 'mime.decode': "mime.decode('base64' or 'quoted-printable')", \ 'mime.encode': "mime.encode('base64' or 'quoted-printable' [, mode])", \ 'mime.normalize': 'mime.normalize([marker])', \ 'mime.wrap': "mime.wrap('base64' or 'quoted-printable' or 'text' [, length])", \ 'smtp.message': 'smtp.message(mesgt)', \ 'socket.bind': 'socket.bind(address, port [, backlog])', \ 'socket.connect': 'socket.connect(address, port [, locaddr, locport])', \ 'socket.newtry': 'socket.newtry(finalizer)', \ 'socket.protect': 'socket.protect(func)', \ 'socket.select': 'socket.select(recvt, sendt [, timeout])', \ 'socket.sink': 'socket.sink(mode, socket)', \ 'socket.skip': 'socket.skip(d [, ret1, ret2 ... retN])', \ 'socket.sleep': 'socket.sleep(time)', \ 'socket.source': 'socket.source(mode, socket [, length])', \ 'socket.gettime': 'socket.gettime()', \ 'socket.dns.gethostname': 'socket.dns.gethostname()', \ 'socket.dns.tohostname': 'socket.dns.tohostname(address)', \ 'socket.dns.toip': 'socket.dns.toip(address)', \ 'socket.try': 'socket.try(ret1 [, ret2 ... retN])', \ 'url.absolute': 'url.absolute(base, relative)', \ 'url.build': 'url.build(parsed_url)', \ 'url.build_path': 'url.build_path(segments, unsafe)', \ 'url.escape': 'url.escape(content)', \ 'url.parse': 'url.parse(url, default)', \ 'url.parse_path': 'url.parse_path(path)', \ 'url.unescape': 'url.unescape(content)' } " }}} " Restore compatibility options. let &cpo = s:cpo_save unlet s:cpo_save " vim: ts=2 sw=2 et ================================================ FILE: doc/ft_lua.txt ================================================ *ft_lua.txt* Lua file type plug-in for the Vim text editor =============================================================================== Contents ~ 1. Introduction |ft_lua-introduction| 2. Installation |ft_lua-installation| 3. Options |ft_lua-options| 1. The |lua_path| option 2. The |lua_check_syntax| option 3. The |lua_check_globals| option 4. The |lua_interpreter_path| option 5. The |lua_internal| option 6. The |lua_compiler_name| option 7. The |lua_compiler_args| option 8. The |lua_error_format| option 9. The |lua_complete_keywords| option 10. The |lua_complete_globals| option 11. The |lua_complete_library| option 12. The |lua_complete_dynamic| option 13. The |lua_complete_omni| option 14. The |lua_omni_blacklist| option 15. The |lua_safe_omni_modules| option 16. The |lua_define_completefunc| option 17. The |lua_define_omnifunc| option 18. The |lua_define_completion_mappings| option 4. Commands |ft_lua-commands| 1. The |:LuaCheckSyntax| command 2. The |:LuaCheckGlobals| command 5. Contact |ft_lua-contact| 6. License |ft_lua-license| 7. References |ft_lua-references| =============================================================================== *ft_lua-introduction* Introduction ~ The Lua [1] file type plug-in for Vim makes it easier to work with Lua source code in Vim by providing the following features: - The |'includeexpr'| option is set so that the |gf| (go to file) mapping knows how to resolve Lua module names using package.path [2] - The |'include'| option is set so that Vim follows dofile() [3], loadfile() [4] and require() [5] calls when looking for identifiers in included files (this works together with the |'includeexpr'| option) - An automatic command is installed that runs 'luac -p' when you save your Lua scripts. If 'luac' reports any errors they are shown in the quick-fix list and Vim jumps to the line of the first error. If 'luac -p' doesn't report any errors a check for undefined global variables is performed by parsing the output of 'luac -p -l' - 'K' (normal mode) and '' (insert mode) on a Lua function or 'method' call will try to open the relevant documentation in the Lua Reference for Vim [6] - The |'completefunc'| option is set to allow completion of Lua 5.2 keywords, global variables and library members using Control-X Control-U - The |'omnifunc'| option is set to allow dynamic completion of the variables defined in all modules installed on the system using Control-X Control-O, however it needs to be explicitly enabled by setting the |lua_complete_omni| option because this functionality may have undesired side effects! When you invoke omni completion after typing "require '" or "require('" you get completion of module names Image: Screenshot of omni completion (see reference [7]) - Several |text-objects| are defined so you can jump between blocks and functions - A pretty nifty hack of the matchit plug-in (see |matchit-install|) is included: When the cursor is on a 'function' or 'return' keyword the '%' mapping cycles between the relevant keywords ('function', 'return', 'end'), this also works for branching statements ('if', 'elseif', 'else', 'end') and looping statements ('for', 'while', 'repeat', 'until', 'end') =============================================================================== *ft_lua-installation* Installation ~ _Please note that the vim-lua-ftplugin plug-in requires my vim-misc plug-in which is separately distributed._ Unzip the most recent ZIP archives of the vim-lua-ftplugin [8] and vim-misc [9] plug-ins inside your Vim profile directory (usually this is '~/.vim' on UNIX and '%USERPROFILE%\vimfiles' on Windows), restart Vim and execute the command ':helptags ~/.vim/doc' (use ':helptags ~\vimfiles\doc' instead on Windows). If you prefer you can also use Pathogen [10], Vundle [11] or a similar tool to install & update the vim-lua-ftplugin [12] and vim-misc [13] plug-ins using a local clone of the git repository. Now try it out: Edit a Lua script and try any of the features documented above. Note that on Windows a command prompt window pops up whenever Lua is run as an external process. If this bothers you then you can install my shell.vim [14] plug-in which includes a DLL [15] that works around this issue. Once you've installed both plug-ins it should work out of the box! =============================================================================== *ft_lua-options* Options ~ The Lua file type plug-in handles options as follows: First it looks at buffer local variables, then it looks at global variables and if neither exists a default is chosen. This means you can change how the plug-in works for individual buffers. For example to change the location of the Lua compiler used to check the syntax: > " This sets the default value for all buffers. :let g:lua_compiler_name = '/usr/local/bin/luac' " This is how you change the value for one buffer. :let b:lua_compiler_name = '/usr/local/bin/lualint' < ------------------------------------------------------------------------------- The *lua_path* option This option contains the value of 'package.path' as a string. You shouldn't need to change this because the plug-in is aware of $LUA_PATH [2] and if that isn't set the plug-in will run a Lua interpreter to get the value of package.path [2]. ------------------------------------------------------------------------------- The *lua_check_syntax* option When you write a Lua script to disk the plug-in automatically runs the Lua compiler to check for syntax errors. To disable this behavior you can set this option to false (0): > let g:lua_check_syntax = 0 < You can manually check the syntax using the ':CheckSyntax' command. ------------------------------------------------------------------------------- The *lua_check_globals* option When you write a Lua script to disk the plug-in automatically runs the Lua compiler to check for undefined global variables. To disable this behavior you can set this option to false (0): > let g:lua_check_globals = 0 < You can manually check the globals using the ':CheckGlobals' command. ------------------------------------------------------------------------------- The *lua_interpreter_path* option The name or path of the Lua interpreter used to evaluate Lua scripts used by the plug-in (for example the script that checks for undefined global variables, see |:LuaCheckGlobals|). ------------------------------------------------------------------------------- The *lua_internal* option If you're running a version of Vim that supports the Lua Interface for Vim (see |if_lua.txt|) then all Lua code evaluated by the Lua file type plug-in is evaluated using the Lua Interface for Vim. If the Lua Interface for Vim is not available the plug-in falls back to using an external Lua interpreter. You can set this to false (0) to force the plug-in to use an external Lua interpreter. ------------------------------------------------------------------------------- The *lua_compiler_name* option The name or path of the Lua compiler used to check for syntax errors (defaults to 'luac'). You can set this option to run the Lua compiler from a non-standard location or to run a dedicated syntax checker like lualint [16]. ------------------------------------------------------------------------------- The *lua_compiler_args* option The argument(s) required by the compiler or syntax checker (defaults to '-p'). ------------------------------------------------------------------------------- The *lua_error_format* option If you use a dedicated syntax checker you may need to change this option to reflect the format of the messages printed by the syntax checker. ------------------------------------------------------------------------------- The *lua_complete_keywords* option To disable completion of keywords you can set this option to false (0). ------------------------------------------------------------------------------- The *lua_complete_globals* option To disable completion of global functions you can set this option to false (0). ------------------------------------------------------------------------------- The *lua_complete_library* option To disable completion of library functions you can set this option to false (0). ------------------------------------------------------------------------------- The *lua_complete_dynamic* option When you type a dot after a word the Lua file type plug-in will automatically start completion. To disable this behavior you can set this option to false (0). ------------------------------------------------------------------------------- The *lua_complete_omni* option This option is disabled by default for two reasons: - The omni completion support works by enumerating and loading all installed modules. **If module loading has side effects this can have unintended consequences!** - Because all modules installed on the system are loaded, collecting the completion candidates can be slow. After the first run the completion candidates are cached so this will only bother you once (until you restart Vim). If you want to use the omni completion despite the warnings above, execute the following command: > :let g:lua_complete_omni = 1 < Now when you type Control-X Control-O Vim will hang for a moment, after which you should be presented with an enormous list of completion candidates :-) ------------------------------------------------------------------------------- The *lua_omni_blacklist* option If you like the omni completion mode but certain modules are giving you trouble (for example crashing Vim) you can exclude such modules from being loaded by the omni completion. You can do so by setting |lua_omni_blacklist| to a list of strings containing Vim regular expression patterns. The patterns are combined as follows: > " Here's the black list: let g:lua_omni_blacklist = ['pl\.strict', 'lgi\..'] " Here's the resulting regular expression pattern: '^\(pl\.strict\|lgi\..\)$' < The example above prevents the module 'pl.strict' and all modules with the prefix 'lgi.' from being loaded. ------------------------------------------------------------------------------- The *lua_safe_omni_modules* option To track down modules that cause side effects while loading, setting > :let g:lua_safe_omni_modules = 1 < restricts the modules to be loaded to the standard Lua modules - which should be safe to load - and provides a list of modules that would have been loaded if this option was not set via the ':messages' command. With this list, the |lua_omni_blacklist| can be iteratively refined to exclude offending modules from omni completion module loading. Note that the |'verbose'| option has to be set to 1 or higher for the list to be recorded. ------------------------------------------------------------------------------- The *lua_define_completefunc* option By default the Lua file type plug-in sets the |'completefunc'| option so that Vim can complete Lua keywords, global variables and library members using Control-X Control-U. If you don't want the 'completefunc' option to be changed by the plug-in, you can set this option to zero (false) in your |vimrc| script: > :let g:lua_define_completefunc = 0 < ------------------------------------------------------------------------------- The *lua_define_omnifunc* option By default the Lua file type plug-in sets the |'omnifunc'| option so that Vim can complete the names of all Lua modules installed on the local system. If you don't want the 'omnifunc' option to be changed by the plug-in, you can set this option to zero (false) in your |vimrc| script: > :let g:lua_define_omnifunc = 0 < ------------------------------------------------------------------------------- The *lua_define_completion_mappings* option By default the Lua file type plug-in defines insert mode mappings so that the plug-in is called whenever you type a single quote, double quote or a dot inside a Lua buffer. This enables context sensitive completion. If you don't like these mappings you can set this option to zero (false). In that case the mappings will not be defined. =============================================================================== *ft_lua-commands* Commands ~ ------------------------------------------------------------------------------- The *:LuaCheckSyntax* command Check the current file for syntax errors using the Lua compiler. This command is executed automatically when you write a Lua script to disk (i.e. when you save your changes) unless |lua_check_syntax| is false. ------------------------------------------------------------------------------- The *:LuaCheckGlobals* command Check the current file for undefined global variables. This command is executed automatically when you write a Lua script to disk (i.e. when you save your changes) unless |lua_check_globals| is false or syntax errors were detected. =============================================================================== *ft_lua-contact* Contact ~ If you have questions, bug reports, suggestions, etc. the author can be contacted at peter@peterodding.com. The latest version is available at http://peterodding.com/code/vim/lua-ftplugin and http://github.com/xolox/vim- lua-ftplugin. If you like this plug-in please vote for it on Vim Online [17]. =============================================================================== *ft_lua-license* License ~ This software is licensed under the MIT license [18]. Š 2014 Peter Odding . Thanks go out to everyone who has helped to improve the Lua file type plug-in for Vim (whether through pull requests, bug reports or personal e-mails). =============================================================================== *ft_lua-references* References ~ [1] http://www.lua.org/ [2] http://www.lua.org/manual/5.2/manual.html#pdf-package.path [3] http://www.lua.org/manual/5.2/manual.html#pdf-dofile [4] http://www.lua.org/manual/5.2/manual.html#pdf-loadfile [5] http://www.lua.org/manual/5.2/manual.html#pdf-require [6] http://www.vim.org/scripts/script.php?script_id=1291 [7] http://peterodding.com/code/vim/lua-ftplugin/screenshots/omni-completion.png [8] http://peterodding.com/code/vim/downloads/lua-ftplugin.zip [9] http://peterodding.com/code/vim/downloads/misc.zip [10] http://www.vim.org/scripts/script.php?script_id=2332 [11] https://github.com/gmarik/vundle [12] http://github.com/xolox/vim-lua-ftplugin [13] http://github.com/xolox/vim-misc [14] http://peterodding.com/code/vim/shell/ [15] http://en.wikipedia.org/wiki/Dynamic-link_library [16] http://lua-users.org/wiki/LuaLint [17] http://www.vim.org/scripts/script.php?script_id=3625 [18] http://en.wikipedia.org/wiki/MIT_License vim: ft=help ================================================ FILE: ftplugin/lua.vim ================================================ " Vim file type plug-in " Language: Lua 5.2 " Author: Peter Odding " Last Change: June 17, 2014 " URL: http://peterodding.com/code/vim/lua-ftplugin if exists('b:did_ftplugin') finish else let b:did_ftplugin = 1 endif " A list of commands that undo buffer local changes made below. let s:undo_ftplugin = [] " Set comment (formatting) related options. {{{1 setlocal fo-=t fo+=c fo+=r fo+=o fo+=q fo+=l setlocal cms=--%s com=s:--[[,m:\ ,e:]],:-- call add(s:undo_ftplugin, 'setlocal fo< cms< com<') " Tell Vim how to follow dofile(), loadfile() and require() calls. {{{1 let &l:include = '\v<((do|load)file|require)[^''"]*[''"]\zs[^''"]+' let &l:includeexpr = 'xolox#lua#includeexpr(v:fname)' call add(s:undo_ftplugin, 'setlocal inc< inex<') " Enable completion of Lua keywords, globals and library members. {{{1 if xolox#misc#option#get('lua_define_completefunc', 1) setlocal completefunc=xolox#lua#completefunc call add(s:undo_ftplugin, 'setlocal completefunc<') endif " Enable dynamic completion by searching "package.path" and "package.cpath". {{{1 if xolox#misc#option#get('lua_define_omnifunc', 1) setlocal omnifunc=xolox#lua#omnifunc call add(s:undo_ftplugin, 'setlocal omnifunc<') endif " Set a filename filter for the Windows file open/save dialogs. {{{1 if has('gui_win32') && !exists('b:browsefilter') let b:browsefilter = "Lua Files (*.lua)\t*.lua\nAll Files (*.*)\t*.*\n" call add(s:undo_ftplugin, 'unlet! b:browsefilter') endif " Define a buffer local command to manually check the syntax. command! -bar -buffer CheckSyntax call xolox#lua#checksyntax() call add(s:undo_ftplugin, 'delcommand CheckSyntax') " Define a buffer local command to manually check for global variables. command! -bar -bang -buffer CheckGlobals call xolox#lua#checkglobals( == '!') call add(s:undo_ftplugin, 'delcommand CheckGlobals') " Define mappings for context-sensitive help using Lua Reference for Vim. {{{1 imap :call xolox#lua#help() nmap :call xolox#lua#help() nmap K :call xolox#lua#help() call add(s:undo_ftplugin, 'iunmap ') call add(s:undo_ftplugin, 'nunmap ') call add(s:undo_ftplugin, 'nunmap K') " Define custom text objects to navigate Lua source code. {{{1 noremap [{ m':call xolox#lua#jumpblock(0) noremap ]} m':call xolox#lua#jumpblock(1) noremap [[ m':call xolox#lua#jumpthisfunc(0) noremap ][ m':call xolox#lua#jumpthisfunc(1) noremap [] m':call xolox#lua#jumpotherfunc(0) noremap ]] m':call xolox#lua#jumpotherfunc(1) call add(s:undo_ftplugin, 'unmap [{') call add(s:undo_ftplugin, 'unmap ]}') call add(s:undo_ftplugin, 'unmap [[') call add(s:undo_ftplugin, 'unmap ][') call add(s:undo_ftplugin, 'unmap []') call add(s:undo_ftplugin, 'unmap ]]') " Enable extended matching with "%" using the "matchit" plug-in. {{{1 if exists('loaded_matchit') let b:match_ignorecase = 0 let b:match_words = 'xolox#lua#matchit()' call add(s:undo_ftplugin, 'unlet! b:match_ignorecase b:match_words b:match_skip') endif " Enable dynamic completion on typing "require('" or "variable."? {{{1 if xolox#misc#option#get('lua_define_completion_mappings', 1) inoremap . xolox#lua#completedynamic('.') call add(s:undo_ftplugin, 'iunmap .') inoremap ' xolox#lua#completedynamic("'") call add(s:undo_ftplugin, "iunmap '") inoremap " xolox#lua#completedynamic('"') call add(s:undo_ftplugin, 'iunmap "') endif " Enable tool tips with function signatures? {{{1 if has('balloon_eval') setlocal ballooneval balloonexpr=xolox#lua#getsignature(v:beval_text) call add(s:undo_ftplugin, 'setlocal ballooneval< balloonexpr<') endif " }}}1 " Let Vim know how to disable the plug-in. call map(s:undo_ftplugin, "'execute ' . string(v:val)") let b:undo_ftplugin = join(s:undo_ftplugin, ' | ') unlet s:undo_ftplugin " vim: ts=2 sw=2 et ================================================ FILE: misc/lua-ftplugin/complete.lua ================================================ #!/usr/bin/env lua --[[ Author: Peter Odding Last Change: July 6, 2014 URL: http://peterodding.com/code/vim/lua-ftplugin This Lua script prints a few hundred lines of Vim script to standard output. These lines are used by my Lua file type plug-in for the Vim text editor to provide completion of Lua keywords, globals and library identifiers. ]] local indent = ' \\ ' local function sorted(input) local keys = {} for key in pairs(input) do table.insert(keys, key) end table.sort(keys) local index = 1 return function() local key = keys[index] index = index + 1 return key, input[key] end end local keywords = { ['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, } io.write '" Keywords. {{{1\n' io.write 'let g:xolox#lua_data#keywords = [\n' for keyword in sorted(keywords) do io.write(indent, ("{ 'word': '%s', 'kind': 'k' },\n"):format(keyword)) end io.write(indent, ']\n\n') local function identifier(value) -- TODO This pattern does *not* match identifiers outside of the C locale local pattern = '^[A-Za-z_][A-Za-z_0-9]*$' return type(value) == 'string' and value:find(pattern) and not keywords[value] end local globals = {} local libraries = {} for global, value in pairs(_G) do if identifier(global) then globals[global .. (type(value) == 'function' and '()' or '')] = type(value) == 'function' and 'f' or 'v' if type(value) == 'table' and value ~= _G then for member, value in pairs(value) do if identifier(member) then member = global .. '.' .. member libraries[member .. (type(value) == 'function' and '()' or '')] = type(value) == 'function' and 'f' or 'm' end end end end end io.write '" Global variables. {{{1\n' io.write 'let g:xolox#lua_data#globals = [\n' for global, kind in sorted(globals) do io.write(indent, ("{ 'word': '%s', 'kind': '%s' },\n"):format(global, kind)) end io.write(indent, ']\n\n') io.write '" Standard library identifiers. {{{1\n' io.write 'let g:xolox#lua_data#library = [\n' for member, kind in sorted(libraries) do io.write(indent, ("{ 'word': '%s', 'kind': '%s' },\n"):format(member, kind)) end io.write(indent, ']\n') -- vim: ts=2 sw=2 et ================================================ FILE: misc/lua-ftplugin/getsignatures.lua ================================================ #!/usr/bin/env lua local http = require 'socket.http' local webpage = http.request 'http://www.lua.org/manual/5.2/manual.html' local matches = {} for anchor, signature in webpage:gmatch '

%s*%s*%s*(.-)%s*%s*%s*

' do if anchor ~= signature then signature = signature:gsub('·', '.') signature = signature:gsub('%s+%(', '(') table.insert(matches, string.format("'%s': '%s'", anchor, signature)) end end local newline = '\n \\ ' print(string.format('let g:xolox#lua_data#signatures = {%s%s }', newline, table.concat(matches, ',' .. newline))) ================================================ FILE: misc/lua-ftplugin/globals.lua ================================================ #!/usr/bin/env lua -- Unpack arguments from Vim. local compiler = arg[1] local filename = arg[2] local verbose = tonumber(arg[3]) ~= 0 local function quote(s) return string.format('"%s"', (s:gsub('["\\]', '\\%0'))) end -- Parse output of "luac -l" for GETGLOBAL/SETGLOBAL instructions. local command = string.format('%s -p -l %s', quote(compiler), quote(filename)) local compiler = io.popen(command) local matches = {} for line in compiler:lines() do local inst = line:match '%]%s+([GS]ETGLOBAL)' if inst then local lnum = tonumber(line:match '%[(%d+)%]') or 0 local varname = line:match '(%S+)$' or '' if lnum > 0 and varname ~= '' then matches[#matches + 1] = {inst=inst, lnum=lnum, varname=varname} end end end -- Sort matched globals by ascending line numbers. table.sort(matches, function(a, b) return a.lnum < b.lnum end) -- Pass results to vim. local template = "{'filename': '%s', 'lnum': %i, 'text': '%s %s global %s', 'type': '%s'}" for _, match in ipairs(matches) do local read = match.inst == 'GETGLOBAL' local operation = read and 'Read of' or 'Write to' local status, severity = 'known', 'I' local varname = match.varname local value = _G[varname] if value == nil then status = 'unknown' severity = read and 'E' or 'W' elseif type(value) == 'function' then varname = varname .. '()' end if severity == 'E' or severity == 'W' or verbose then print(template:format(arg[1], match.lnum, operation, status, varname, severity)) end end ================================================ FILE: misc/lua-ftplugin/omnicomplete.lua ================================================ #!/usr/bin/env lua --[[ Author: Peter Odding Last Change: July 12, 2014 URL: http://peterodding.com/code/vim/lua-ftplugin This Lua script is executed by the Lua file type plug-in for Vim to provide dynamic completion of function names defined by installed Lua modules. This works by expanding package.path and package.cpath in Vim script, loading every module found on the search path into this Lua script and then dumping the global state. ]] local keywords = { ['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 isident(s) return type(s) == 'string' and s:find('^[A-Za-z_][A-Za-z_0-9]*$') and not keywords[s] end local function addmatch(word, kind, desc) if not desc then print(string.format("{'word':'%s','kind':'%s'}", word, kind)) else -- Make sure we generate valid Vim script expressions (this is probably -- still not right). desc = desc:gsub('\n', '\\n') :gsub('\r', '\\r') :gsub("'", "''") print(string.format("{'word':'%s','kind':'%s','menu':'%s'}", word, kind, desc)) end end local function dump(table, path, cache) local printed = false for key, value in pairs(table) do if isident(key) then local path = path and (path .. '.' .. key) or key local vtype = type(value) if vtype == 'function' then printed = true addmatch(path, 'f', path .. '()') elseif vtype ~= 'table' then printed = true if vtype == 'boolean' or vtype == 'number' then addmatch(path, 'v', tostring(value)) elseif vtype == 'string' then if #value > 40 then value = value:sub(1, 40) .. '..' end addmatch(path, 'v', value) else addmatch(path, 'v', nil) end elseif not cache[value] then cache[value] = true if dump(value, path, cache) then printed = true else addmatch(path, 't', path .. '[]') end end end end return printed end -- Add keywords to completion candidates. for kw, _ in pairs(keywords) do addmatch(kw, 'k', nil) end local function global_exists(name) -- Don't crash on strict.lua. return pcall(function() if not _G[name] then -- Simulate strict.lua when it isn't active so that we can stick to a -- single code path. error("variable " .. name .. " is not declared") end end) end -- Load installed modules. -- XXX What if module loading has side effects? It shouldn't, but still... for i = 1, #arg do local modulename = arg[i] local status, module = pcall(require, modulename) if status and module and not global_exists(modulename) then _G[modulename] = module end end -- Generate completion candidates from global state. local cache = { [_G] = true, [package.loaded] = true } local output = {} dump(_G, nil, cache, output) ================================================ FILE: plugin/lua-ftplugin.vim ================================================ " Vim file type plug-in " Language: Lua 5.2 " Author: Peter Odding " Last Change: August 19, 2013 " URL: http://peterodding.com/code/vim/lua-ftplugin " Support for automatic update using the GLVS plug-in. " GetLatestVimScripts: 3625 1 :AutoInstall: lua.zip " Don't source the plug-in when it's already been loaded or &compatible is set. if &cp || exists('g:loaded_lua_ftplugin') finish endif " Make sure vim-misc is installed. try " The point of this code is to do something completely innocent while making " sure the vim-misc plug-in is installed. We specifically don't use Vim's " exists() function because it doesn't load auto-load scripts that haven't " already been loaded yet (last tested on Vim 7.3). call type(g:xolox#misc#version) catch echomsg "Warning: The vim-lua-ftplugin plug-in requires the vim-misc plug-in which seems not to be installed! For more information please review the installation instructions in the readme (also available on the homepage and on GitHub). The vim-lua-ftplugin plug-in will now be disabled." let g:loaded_lua_ftplugin = 1 finish endtry " Commands to manually check for syntax errors and undefined globals. command! -bar LuaCheckSyntax call xolox#lua#checksyntax() command! -bar -bang LuaCheckGlobals call xolox#lua#checkglobals( == '!') " Automatic commands to check for syntax errors and/or undefined globals " and change Vim's "completeopt" setting on the fly for Lua buffers. augroup PluginFileTypeLua autocmd! autocmd WinEnter * call xolox#lua#tweakoptions() autocmd BufWritePost * call xolox#lua#autocheck() augroup END " Make sure the plug-in is only loaded once. let g:loaded_lua_ftplugin = 1 " vim: ts=2 sw=2 et