├── .gitattributes ├── README.ja.md ├── README.md ├── doc ├── nvim-lua-guide.jax └── nvim-lua-guide.txt └── scripts ├── docgen.sh ├── sections_tags.awk ├── to_vimdoc.sed └── to_vimdocja.sed /.gitattributes: -------------------------------------------------------------------------------- 1 | scripts/* -linguist-detectable 2 | -------------------------------------------------------------------------------- /README.ja.md: -------------------------------------------------------------------------------- 1 | :arrow_upper_left: (迷子になった? GitHub TOCを使いましょう!) 2 | 3 | **:warning: :warning: :warning: このガイドの最新版は、Neovimのドキュメントにあります。 [`:help lua-guide`](https://neovim.io/doc/user/lua-guide.html#lua-guide)を参照してください。 :warning: :warning: :warning:** 4 | 5 | 日本語はこちら→https://github.com/willelz/neovimdoc-ja/blob/main/doc/lua-guide.jax 6 | 7 | # Getting started using Lua in Neovim 8 | 9 | ## はじめに 10 | 11 | Neovimの[ファーストクラス言語](https://github.com/neovim/neovim/wiki/FAQ#why-embed-lua-instead-of-x)としての[Lua](https://www.youtube.com/watch?v=IP3J56sKtn0)はキラー機能の1つになりつつあります。 12 | しかし、Luaでプラグインを書くための教材はVim script程多くありません。これは、Luaを始めるための基本的な情報を提供する試みです。 13 | 14 | このガイドは少なくともNeovim 0.5を使用していることを前提としています。 15 | 16 | ### Luaを学ぶ 17 | 18 | まだLuaについて詳しくない場合、学ぶためのリソースはたくさんあります。: 19 | 20 | - [Learn X in Y minutes page about Lua](https://learnxinyminutes.com/docs/lua/)は基本的な概要を説明します。 21 | - [このガイド](https://github.com/medwatt/Notes/blob/main/Lua/Lua_Quick_Guide.ipynb)も素早く始めるのに良いチュートリアルです。 22 | - 動画が好きなら、Derek Banasの動画があります。[1-hour tutorial on the language](https://www.youtube.com/watch?v=iMacxZQMPXs) 23 | - 実行できるサンプルを使い、対話的に学びたいですか?[LuaScript tutorial](https://www.luascript.dev/learn)を試してみてください。 24 | - [lua-users wiki](http://lua-users.org/wiki/LuaDirectory)にはLua関連のトピックごとの便利な情報がたくさんあります。 25 | - [official reference manual for Lua](https://www.lua.org/manual/5.1/)には最も包括的な情報があります。(エディタで快適に読みたいなら、Vimdocプラグインがあります。:[milisims/nvim-luaref](https://github.com/milisims/nvim-luaref)) 26 | 27 | Luaはとてもクリーンでシンプルな言語であることに注意してください。JavaScriptのようなスクリプト言語の経験があれば、学ぶことは簡単です。あなたはもう自分で思っているよりLuaについて知っているかもしれません! 28 | 29 | Note: Neovimに埋め込まれているLuaは[LuaJIT](https://staff.fnwi.uva.nl/h.vandermeer/docs/lua/luajit/luajit_intro.html) 2.1.0でLua 5.1と互換性を維持しています。 30 | 31 | ### Luaを書くための既存のチュートリアル 32 | 33 | Luaでプラグインを書くためのチュートリアルが既にいくつかあります。それらはこのガイドを書くのに役に立ちました。筆者に感謝します。 34 | 35 | - [teukka.tech - init.vimからinit.luaへ](https://teukka.tech/luanvim.html) 36 | - [dev.to - プラグインをLuaで書く方法](https://dev.to/2nit/how-to-write-neovim-plugins-in-lua-5cca) 37 | - [dev.to - プラグインのUIをLuaで作る方法](https://dev.to/2nit/how-to-make-ui-for-neovim-plugins-in-lua-3b6e) 38 | - [ms-jpq - Neovim Async Tutorial](https://github.com/ms-jpq/neovim-async-tutorial) 39 | - [oroques.dev - Neovim 0.5の機能とinit.luaへの切り替え](https://oroques.dev/notes/neovim-init/) 40 | - [ゼロからステータスラインを作る - jdhao's blog](https://jdhao.github.io/2019/11/03/vim_custom_statusline/) 41 | - [LuaでNeovimを設定する](https://icyphox.sh/blog/nvim-lua/) 42 | - [Devlog | Luaで設定するために知る必要のあること](https://vonheikemen.github.io/devlog/tools/configuring-neovim-using-lua/) 43 | 44 | ### 関連するプラグイン 45 | 46 | - [Vimpeccable](https://github.com/svermeulen/vimpeccable) - .vimrc内でLuaを書くのに役に立つプラグイン 47 | - [plenary.nvim](https://github.com/nvim-lua/plenary.nvim) - 二度書きたくないLua関数のすべて 48 | - [popup.nvim](https://github.com/nvim-lua/popup.nvim) - vimのPopup APIのNeovimでの実装 49 | - [nvim_utils](https://github.com/norcalli/nvim_utils) 50 | - [nvim-luadev](https://github.com/bfredl/nvim-luadev) - REPL/debugコンソール 51 | - [nvim-luapad](https://github.com/rafcamlet/nvim-luapad) - 組込みLuaエンジンのインタラクティブなリアルタイムスクラッチパッド 52 | - [nlua.nvim](https://github.com/tjdevries/nlua.nvim) - NeovimのLua開発 53 | - [BetterLua.vim](https://github.com/euclidianAce/BetterLua.vim) - Vim/Neovimより良いシンタックスハイライト 54 | 55 | ## Luaファイルを置く場所 56 | 57 | ### init.lua 58 | 59 | Neovimは、`init.vim`の代わりに設定ファイルとして`init.lua`を読み込むことをサポートしています。 60 | 61 | Note: `init.lua`は _完全に_ オプションです。`init.vim`は廃止されず、設定として有効です。 62 | いくつかの機能は、まだ100%Luaに公開されていないので注意してください。 63 | 64 | 参照: 65 | - [`:help config`](https://neovim.io/doc/user/starting.html#config) 66 | 67 | ### モジュール 68 | 69 | Luaモジュールは、`runtimepath`内の`lua/`フォルダにあります(ほとんどの場合、\*nixでは`~/.config/nvim/lua`、Windowsでは`~/AppData/Local/nvim/lua`を意味します)。 70 | このフォルダにあるファイルをLuaモジュールとして`require()`できます。 71 | 72 | 例として次のフォルダ構造を取り上げましょう。: 73 | 74 | ```text 75 | 📂 ~/.config/nvim 76 | ├── 📁 after 77 | ├── 📁 ftplugin 78 | ├── 📂 lua 79 | │ ├── 🌑 myluamodule.lua 80 | │ └── 📂 other_modules 81 | │ ├── 🌑 anothermodule.lua 82 | │ └── 🌑 init.lua 83 | ├── 📁 pack 84 | ├── 📁 plugin 85 | ├── 📁 syntax 86 | └── 🇻 init.vim 87 | ``` 88 | 89 | 次のLuaコードは`myluamodule.lua`をロードします。: 90 | 91 | ```lua 92 | require('myluamodule') 93 | ``` 94 | 95 | `.lua`拡張子がないことに注意してください。 96 | 97 | 同様に、`other_modules/anothermodule.lua` のロードは次のように行います。: 98 | 99 | ```lua 100 | require('other_modules.anothermodule') 101 | -- or 102 | require('other_modules/anothermodule') 103 | ``` 104 | 105 | パスの区切りはドット`.`またはスラッシュ`/`で示されます。 106 | 107 | フォルダに`init.lua`が含まれている場合、ファイル名を指定せずにロードできます。 108 | 109 | ```lua 110 | require('other_modules') -- other_modules/init.luaをロード 111 | ``` 112 | 113 | 存在しないモジュール、構文エラーを含むモジュールをrequireすると実行中のスクリプトは停止します。 114 | エラーを防ぐために、`pcall()`を使用できます。 115 | 116 | ```lua 117 | local ok, _ = pcall(require, 'module_with_error') 118 | if not ok then 119 | -- not loaded 120 | end 121 | ``` 122 | 123 | 参照: 124 | - [`:help lua-require`](https://neovim.io/doc/user/lua.html#lua-require) 125 | 126 | #### Tips 127 | 128 | いくつかのLuaプラグインは`lua/`フォルダ内に同じ名前のファイルがあるかもしれません。これにより、名前空間の衝突を起こす可能性があります。 129 | 130 | 異なる2つのプラグインに`lua/main.lua`がある場合、`require('main')`は曖昧です。: どのファイルを読み込みますか? 131 | 132 | トップレベルのフォルダで名前空間をつけることをお勧めします。: `lua/plugin_name/main.lua` 133 | 134 | #### Runtime files 135 | 136 | Vim scriptと同様に、`runtimepath`内にある特定のフォルダからLuaファイルを自動的に読み込めます。 137 | 現在、次のフォルダがサポートされています。: 138 | 139 | - `colors/` 140 | - `compiler/` 141 | - `ftplugin/` 142 | - `ftdetect/` 143 | - `indent/` 144 | - `plugin/` 145 | - `syntax/` 146 | 147 | Note: runtimeデイレクトリでは、すべての`*.vim`ファイルは`*.lua`ファイルの前に読み込まれます。 148 | 149 | 150 | 参照: 151 | - [`:help 'runtimepath'`](https://neovim.io/doc/user/options.html#'runtimepath') 152 | - [`:help load-plugins`](https://neovim.io/doc/user/starting.html#load-plugins) 153 | 154 | #### Tips 155 | 156 | ランタイムファイルはLuaのモジュールシステムをベースとしていないため、2つのプラグインは`plugin/main.lua`を問題なく持つことができます。 157 | 158 | ## Vim scriptからLuaを使用する 159 | 160 | ### :lua 161 | 162 | Luaのチャンクを実行します。 163 | 164 | ```vim 165 | :lua require('myluamodule') 166 | ``` 167 | 168 | ヒアドキュメント構文を使用すると複数行に書くことができます。: 169 | 170 | ```vim 171 | echo "Here's a bigger chunk of Lua code" 172 | 173 | lua << EOF 174 | local mod = require('mymodule') 175 | local tbl = {1, 2, 3} 176 | 177 | for k, v in ipairs(tbl) do 178 | mod.method(v) 179 | end 180 | 181 | print(tbl) 182 | EOF 183 | ``` 184 | 185 | Note: 各`:lua`コマンドは独自のスコープを持っており、`local`を付けた変数はコマンドの外からアクセスできません。 186 | 次の例は動作しません。: 187 | 188 | ```vim 189 | :lua local foo = 1 190 | :lua print(foo) 191 | " '1'ではなく'nil'が出力されます。 192 | ``` 193 | 194 | Note 2: Luaの`print()`は`:echomsg`と同じように動作します。出力はメッセージ履歴に保存されます。また、`:silent`で抑制できます。 195 | 196 | 参照: 197 | 198 | - [`:help :lua`](https://neovim.io/doc/user/lua.html#Lua) 199 | - [`:help :lua-heredoc`](https://neovim.io/doc/user/lua.html#:lua-heredoc) 200 | 201 | ### :luado 202 | 203 | このコマンドはカレントバッファの範囲行にLuaチャンクを実行します。範囲を指定しない場合、バッファ全体に作用します。 204 | チャンクから`return`された文字列は、各行を置き換えるために使用されます。 205 | 206 | 次のコマンドは、カレントバッファのすべての行を`hello world`に置き換えます。: 207 | 208 | ```vim 209 | :luado return 'hello world' 210 | ``` 211 | 212 | 2つの暗黙的な変数`line`と`liner`が提供されます。`line`は対象行のテキストで、`liner`はその行数です。 213 | 次のコマンドは、すべての偶数行のテキストを大文字にします。 214 | 215 | ```vim 216 | :luado if linenr % 2 == 0 then return line:upper() end 217 | ``` 218 | 219 | 参照: 220 | 221 | - [`:help :luado`](https://neovim.io/doc/user/lua.html#:luado) 222 | 223 | ### Luaファイルの読み込み 224 | 225 | NeovimはLuaファイルを読み込むためのEXコマンドを3つ提供しています。 226 | 227 | - `:luafile` 228 | - `:source` 229 | - `:runtime` 230 | 231 | `:luafile`と`:source`はとてもよく似ています。: 232 | 233 | ```vim 234 | :luafile ~/foo/bar/baz/myluafile.lua 235 | :luafile % 236 | :source ~/foo/bar/baz/myluafile.lua 237 | :source % 238 | ``` 239 | 240 | `:source`は範囲指定もサポートしており、スクリプトの一部を実行するのに役立ちます。: 241 | 242 | ```vim 243 | :1,10source 244 | ``` 245 | 246 | `:runtime`は少し異なります。: `'runtimepath'`オプションで読み込むファイルを指定します。 247 | 詳細は[`:help :runtime`](https://neovim.io/doc/user/repeat.html#:runtime)を参照してください。 248 | 249 | 参照: 250 | 251 | - [`:help :luafile`](https://neovim.io/doc/user/lua.html#:luafile) 252 | - [`:help :source`](https://neovim.io/doc/user/repeat.html#:source) 253 | - [`:help :runtime`](https://neovim.io/doc/user/repeat.html#:runtime) 254 | 255 | #### Sourcing a lua file vs calling require(): 256 | 257 | `require()`関数を呼ぶこととLuaファイルの読み込みの違いは何か、どちらを使うべきかを疑問に思うかもしれません。 258 | それらには異なるユースケースがあります。: 259 | 260 | - `require()`: 261 | - Luaの組込み関数です。Luaのモジュールを読み込むのに使用します。 262 | - `'runtimepath'`内にある`lua/`フォルダからモジュールを探します。 263 | - どのモジュールをロードしたかを記憶し、多重に実行されるのを防ぎます。Neovim実行中に、モジュールに含まれるコードを変更し、もう一度`require()`を実行してもモジュールは更新されません。 264 | - `:luafile`, `:source`, `runtime`: 265 | - Exコマンドです。モジュールには対応していません。 266 | - 以前に実行されたかどうかに関わらず実行されます。 267 | - `:luafile`と`:source`は現在のウィンドウのディレクトリに対して相対パス・絶対パスを取ります。 268 | - `runtime`は、`'rutimepath'`オプションを使用してファイルを探します。 269 | 270 | `:source`や`:runtime`、ランタイムディレクトリから自動的に読み込まれたファイルも`scriptnames`と`--startuptime`に表示されます。 271 | 272 | ### luaeval() 273 | 274 | Vim scriptの組込み関数です。文字列のLua式を評価して返します。 275 | Luaの型は自動的にVim scriptの型に変換されます。(その逆も同様です。) 276 | 277 | ```vim 278 | " 変数に結果を代入することができます。 279 | let variable = luaeval('1 + 1') 280 | echo variable 281 | " 2 282 | let concat = luaeval('"Lua".." is ".."awesome"') 283 | echo concat 284 | " 'Lua is awesome' 285 | 286 | " リストのようなテーブルはVimのリストに変換されます。 287 | let list = luaeval('{1, 2, 3, 4}') 288 | echo list[0] 289 | " 1 290 | echo list[1] 291 | " 2 292 | " 注意 Luaのテーブルと違い、Vimのリストは0インデックスです。 293 | 294 | " 辞書のようなテーブルはVimの辞書に変換されます。 295 | let dict = luaeval('{foo = "bar", baz = "qux"}') 296 | echo dict.foo 297 | " 'bar' 298 | 299 | " bool値とnilも同様です。 300 | echo luaeval('true') 301 | " v:true 302 | echo luaeval('nil') 303 | " v:null 304 | 305 | " Lua関数のエイリアスをVim scriptで作ることができます。 306 | let LuaMathPow = luaeval('math.pow') 307 | echo LuaMathPow(2, 2) 308 | " 4 309 | let LuaModuleFunction = luaeval('require("mymodule").myfunction') 310 | call LuaModuleFunction() 311 | 312 | " Vimの関数にLuaの関数を値として渡すこともできます。 313 | lua X = function(k, v) return string.format("%s:%s", k, v) end 314 | echo map([1, 2, 3], luaeval("X")) 315 | ``` 316 | 317 | `luaeval()`は式にデータを渡すことのできる任意の2つ目の引数があります。Luaからは`_A`としてアクセスできます。 318 | 319 | ```vim 320 | echo luaeval('_A[1] + _A[2]', [1, 1]) 321 | " 2 322 | 323 | echo luaeval('string.format("Lua is %s", _A)', 'awesome') 324 | " 'Lua is awesome' 325 | ``` 326 | 327 | 参照: 328 | - [`:help luaeval()`](https://neovim.io/doc/user/lua.html#luaeval()) 329 | 330 | ### v:lua 331 | 332 | Vimのグローバル変数です。Vim scriptからLuaのグローバル名前空間([`_G`](https://www.lua.org/manual/5.1/manual.html#pdf-_G)) 内の関数を直接呼ぶことができます。 333 | この場合でも、Vim scriptの型はLuaの型に変換されます。逆も同様です。 334 | 335 | ```vim 336 | call v:lua.print('Hello from Lua!') 337 | " 'Hello from Lua!' 338 | 339 | let scream = v:lua.string.rep('A', 10) 340 | echo scream 341 | " 'AAAAAAAAAA' 342 | 343 | " How about a nice statusline? 344 | lua << EOF 345 | function _G.statusline() 346 | local filepath = '%f' 347 | local align_section = '%=' 348 | local percentage_through_file = '%p%%' 349 | return string.format( 350 | '%s%s%s', 351 | filepath, 352 | align_section, 353 | percentage_through_file 354 | ) 355 | end 356 | EOF 357 | 358 | set statusline=%!v:lua.statusline() 359 | 360 | " Also works in expression mappings 361 | lua << EOF 362 | function _G.check_back_space() 363 | local col = vim.api.nvim_win_get_cursor(0)[2] 364 | return (col == 0 or vim.api.nvim_get_current_line():sub(col, col):match('%s')) and true 365 | end 366 | EOF 367 | 368 | inoremap 369 | \ pumvisible() ? "\" : 370 | \ v:lua.check_back_space() ? "\" : 371 | \ completion#trigger_completion() 372 | 373 | " シングルクォートを使用したり、括弧を省略して、Luaモジュールから関数を呼び出します: 374 | call v:lua.require'module'.foo() 375 | ``` 376 | 377 | 参照: 378 | - [`:help v:lua`](https://neovim.io/doc/user/eval.html#v:lua) 379 | - [`:help v:lua-call`](https://neovim.io/doc/user/lua.html#v:lua-call) 380 | 381 | #### 警告 382 | 383 | この変数は関数呼び出しにのみ使用できます。次の例はエラーになります。: 384 | 385 | ```vim 386 | " 関数のエイリアスは動作しません 387 | let LuaPrint = v:lua.print 388 | 389 | " 辞書アクセスは動作しません 390 | echo v:lua.some_global_dict['key'] 391 | 392 | " 関数を値として使用できません 393 | echo map([1, 2, 3], v:lua.global_callback) 394 | ``` 395 | 396 | ### Tips 397 | 398 | 設定ファイルに、`let g:vimsyn_embed = 'l'`を追加すると.vimファイル内のLuaを構文ハイライトできます。 399 | 詳細は[`:help g:vimsyn_embed`](https://neovim.io/doc/user/syntax.html#g:vimsyn_embed)を参照してください。 400 | 401 | ## vim名前空間 402 | 403 | NeovimはLuaからAPIを使うためのエントリーポイントとして、`vim`グローバル変数を公開しています。 404 | これは、拡張された標準ライブラリやさまざまなサブモジュールを提供します。 405 | 406 | いくつかの注目すべき関数とモジュール: 407 | 408 | - `vim.inspect`: Luaオブジェクトを人間が読みやすい文字列に変換する(テーブルを調べるのに便利です。) 409 | - `vim.regex`: LuaからVimの正規表現を使う 410 | - `vim.api`: API関数を公開するモジュール(リモートプラグインで使うAPIと同じです) 411 | - `vim.ui`: プラグインから利用できる上書き可能な関数 412 | - `vim.loop`: Neovimのイベントループ機能を公開するモジュール(LibUVを使います) 413 | - `vim.lsp`: 組込みのLSPクライアントを操作するモジュール 414 | - `vim.treesitter`: tree-sitterライブラリの機能を公開するモジュール 415 | 416 | このリストは決して包括的なリストではありません。`vim`変数で何かできるかを詳しく知りたい場合は、[`:help lua-stdlib`](https://neovim.io/doc/user/lua.html#lua-stdlib)と[`:help lua-vim`](https://neovim.io/doc/user/lua.html#lua-vim)が最適です。 417 | または、`:lua print(vim.inspect(vim))`を実行してすべてのモジュールのリストを取得できます。 418 | API関数は、[`:help api-global`](https://neovim.io/doc/user/api.html#api-global)にあります。 419 | 420 | #### Tips 421 | 422 | オブジェクトの中身を検査するのに毎回`print(vim.inspect(x))`を書くのは面倒です。設定にグローバルなラッパー関数を含めることは価値があるかもしれません。(Neovim 0.7.0+では、この関数は組込み関数です。参照 [`:help vim.pretty_print()`](https://neovim.io/doc/user/lua.html#vim.pretty_print())): 423 | 424 | ```lua 425 | function _G.put(...) 426 | local objects = {} 427 | for i = 1, select('#', ...) do 428 | local v = select(i, ...) 429 | table.insert(objects, vim.inspect(v)) 430 | end 431 | 432 | print(table.concat(objects, '\n')) 433 | return ... 434 | end 435 | ``` 436 | 437 | コードまたはコマンドラインからとても早くオブジェクトの中身を検査できます。 438 | 439 | ```lua 440 | put({1, 2, 3}) 441 | ``` 442 | 443 | ```vim 444 | :lua put(vim.loop) 445 | ``` 446 | 447 | または、`:lua`コマンドでLua式の前に `=` をつけて、整列させて表示できます。(Neovim 0.7+のみ) 448 | 449 | ```vim 450 | :lua =vim.loop 451 | ``` 452 | 453 | 加えて、他の言語と比較して組込みのLua関数が不足している場合があります(例えば、`os.clock`はミリ秒ではなく秒数のみを返します)。 454 | 必ず、Neovim stdlib(それと`vim.fn`。詳しくは後述します。)を見てください。おそらく、探しものはそこにあります。 455 | 456 | ## LuaからVim scriptを使用する 457 | 458 | ### vim.api.nvim_eval() 459 | 460 | 文字列で与えられたVim scriptの式を評価してその値を返します。Vim scriptの型は自動的にLuaの型に変換されます。(その逆も同様です。) 461 | 462 | これは、Vim scriptの`luaeval()`と同様です。 463 | 464 | ```lua 465 | -- 型は正しく変換されます。 466 | print(vim.api.nvim_eval('1 + 1')) -- 2 467 | print(vim.inspect(vim.api.nvim_eval('[1, 2, 3]'))) -- { 1, 2, 3 } 468 | print(vim.inspect(vim.api.nvim_eval('{"foo": "bar", "baz": "qux"}'))) -- { baz = "qux", foo = "bar" } 469 | print(vim.api.nvim_eval('v:true')) -- true 470 | print(vim.api.nvim_eval('v:null')) -- nil 471 | ``` 472 | 473 | #### 警告 474 | 475 | `luaeval()`と違い、式にデータを渡すための暗黙的な変数`_A`を提供しません。 476 | 477 | ### vim.api.nvim_exec() 478 | 479 | Vim scriptのチャンクを実行します。実行するソースコートを含む文字列と、コードの出力を返すかどうかを決めるbool値を受け取ります(例えば、出力を変数に格納できます)。 480 | 481 | ```lua 482 | local result = vim.api.nvim_exec( 483 | [[ 484 | let s:mytext = 'hello world' 485 | 486 | function! s:MyFunction(text) 487 | echo a:text 488 | endfunction 489 | 490 | call s:MyFunction(mytext) 491 | ]], 492 | true) 493 | 494 | print(result) -- 'hello world' 495 | ``` 496 | 497 | #### 警告 498 | 499 | Neovim 0.6.0より前のバージョンでは 、`nvim_exec` はスクリプトローカル変数(`s:`)をサポートしていません。 500 | 501 | ### vim.api.nvim_command() 502 | 503 | Exコマンドを実行します。実行するコマンドを含む文字列を受け取ります。 504 | 505 | ```lua 506 | vim.api.nvim_command('new') 507 | vim.api.nvim_command('wincmd H') 508 | vim.api.nvim_command('set nonumber') 509 | vim.api.nvim_command('%s/foo/bar/g') 510 | ``` 511 | 512 | ### vim.cmd() 513 | 514 | `vim.api.nvim_exec()`のエイリアスです。コマンドの引数のみを必要とし、`output`は常に`false`に設定されます。 515 | 516 | ```lua 517 | vim.cmd('buffers') 518 | vim.cmd([[ 519 | let g:multiline_list = [ 520 | \ 1, 521 | \ 2, 522 | \ 3, 523 | \ ] 524 | 525 | echo g:multiline_list 526 | ]]) 527 | ``` 528 | 529 | #### Tips 530 | 531 | これらの関数は文字列を渡すため、多くの場合、バックスラッシュをエスケープする必要があります。: 532 | 533 | ```lua 534 | vim.cmd('%s/\\Vfoo/bar/g') 535 | ``` 536 | 537 | 二重括弧の文字列はエスケープが必要ないため使いやすいです。: 538 | 539 | ```lua 540 | vim.cmd([[%s/\Vfoo/bar/g]]) 541 | ``` 542 | 543 | ### vim.api.nvim_replace_termcodes() 544 | 545 | このAPI関数はターミナルコードとVimのキーコードをエスケープできます。 546 | 547 | 次のようなマッピングを見たことがあるかもしれません。: 548 | 549 | ```vim 550 | inoremap pumvisible() ? "\" : "\" 551 | ``` 552 | 553 | 同じことをLuaでやると大変です。次のようにやるかもしれません。: 554 | 555 | ```lua 556 | function _G.smart_tab() 557 | return vim.fn.pumvisible() == 1 and [[\]] or [[\]] 558 | end 559 | 560 | vim.api.nvim_set_keymap('i', '', 'v:lua.smart_tab()', {expr = true, noremap = true}) 561 | ``` 562 | 563 | マッピングに `\` と `\` が挿入されているのを知るためだけに... 564 | 565 | キーコードをエスケープできるのは、Vim scriptの機能です。`\r`, `\42` や `\x10` のような多くのプログラミング言語に共通する通常のエスケープシーケンスとは別に、Vim scriptの `expr-quotes` (ダブルクォートで囲まれる文字列)を使用すると、人間が読める表現のVimキーコードをエスケープします。 566 | 567 | Luaにはそのような機能は組み込まれていません。嬉しいことに、NeovimにはターミナルコードとキーコードをエスケープするAPI関数 `nvim_replace_termcodes()` があります。: 568 | 569 | ```lua 570 | print(vim.api.nvim_replace_termcodes('', true, true, true)) 571 | ``` 572 | 573 | これは少し冗長です。再利用できるラッパーを作ると便利です。: 574 | 575 | ```lua 576 | -- `termcodes` 専用の `t` 関数です 577 | -- この名前で呼ばなくてもいいですが、この簡潔さが便利です 578 | local function t(str) 579 | -- 必要に応じてboolean引数で調整します 580 | return vim.api.nvim_replace_termcodes(str, true, true, true) 581 | end 582 | 583 | print(t'') 584 | ``` 585 | 586 | 先程の例はこれで期待通りに動きます: 587 | 588 | ```lua 589 | local function t(str) 590 | return vim.api.nvim_replace_termcodes(str, true, true, true) 591 | end 592 | 593 | function _G.smart_tab() 594 | return vim.fn.pumvisible() == 1 and t'' or t'' 595 | end 596 | 597 | vim.api.nvim_set_keymap('i', '', 'v:lua.smart_tab()', {expr = true, noremap = true}) 598 | ``` 599 | 600 | `vim.keymap.set()`では、このハックは必要ありません。`expr`が有効な場合、デフォルトで自動的に変換されます。: 601 | 602 | ```lua 603 | vim.keymap.set('i', '', function() 604 | return vim.fn.pumvisible() == 1 and '' or '' 605 | end, {expr = true}) 606 | ``` 607 | 608 | 参照: 609 | - [`:help keycodes`](https://neovim.io/doc/user/intro.html#keycodes) 610 | - [`:help expr-quote`](https://neovim.io/doc/user/eval.html#expr-quote) 611 | - [`:help nvim_replace_termcodes()`](https://neovim.io/doc/user/api.html#nvim_replace_termcodes()) 612 | 613 | ## vimオプションを管理する 614 | 615 | ### API関数を使用する 616 | 617 | Neovimは、オプションの値を読み書きできるAPI関数を提供しています。 618 | 619 | - グローバルオプション: 620 | - [`vim.api.nvim_set_option()`](https://neovim.io/doc/user/api.html#nvim_set_option()) 621 | - [`vim.api.nvim_get_option()`](https://neovim.io/doc/user/api.html#nvim_get_option()) 622 | - バッファオプション: 623 | - [`vim.api.nvim_buf_set_option()`](https://neovim.io/doc/user/api.html#nvim_buf_set_option()) 624 | - [`vim.api.nvim_buf_get_option()`](https://neovim.io/doc/user/api.html#nvim_buf_get_option()) 625 | - ウィンドウオプション: 626 | - [`vim.api.nvim_win_set_option()`](https://neovim.io/doc/user/api.html#nvim_win_set_option()) 627 | - [`vim.api.nvim_win_get_option()`](https://neovim.io/doc/user/api.html#nvim_win_get_option()) 628 | 629 | それらはオプションの名前と設定したい値を含む文字列を受け取ります。 630 | 631 | boolな(`(no)number`のような)オプションは`true`か`false`のどちらかに設定する必要があります。: 632 | 633 | ```lua 634 | vim.api.nvim_set_option('smarttab', false) 635 | print(vim.api.nvim_get_option('smarttab')) -- false 636 | ``` 637 | 638 | 当然ながら、文字列のオプションには文字列を設定する必要があります。: 639 | 640 | ```lua 641 | vim.api.nvim_set_option('selection', 'exclusive') 642 | print(vim.api.nvim_get_option('selection')) -- 'exclusive' 643 | ``` 644 | 645 | 数値のオプションは数値を受け取ります。: 646 | 647 | ```lua 648 | vim.api.nvim_set_option('updatetime', 3000) 649 | print(vim.api.nvim_get_option('updatetime')) -- 3000 650 | ``` 651 | 652 | バッファローカルとウィンドウローカルなオプションはそれぞれの番号も必要です。(`0`を指定した場合、カレントバッファ/ウィンドウが対象になります。): 653 | 654 | ```lua 655 | vim.api.nvim_win_set_option(0, 'number', true) 656 | vim.api.nvim_buf_set_option(10, 'shiftwidth', 4) 657 | print(vim.api.nvim_win_get_option(0, 'number')) -- true 658 | print(vim.api.nvim_buf_get_option(10, 'shiftwidth')) -- 4 659 | ``` 660 | 661 | ### メタアクセサーを使用する 662 | 663 | もっと使い慣れた方法でオプションを設定したい場合、いくつかのメタアクセサーを使用できます。それらは、上記のAPI関数をラップしたものでオプションを変数のように操作できます。: 664 | 665 | - [`vim.o.{option}`](https://neovim.io/doc/user/lua.html#vim.o): `:let &{option-name}`のように動作します 666 | - [`vim.go.{option}`](https://neovim.io/doc/user/lua.html#vim.go): `:let &g:{option-name}`のように動作します 667 | - [`vim.bo.{option}`](https://neovim.io/doc/user/lua.html#vim.bo): バッファローカルオプションの場合`:let &l:{option-name}`のように動作します 668 | - [`vim.wo.{option}`](https://neovim.io/doc/user/lua.html#vim.wo): ウィンドウローカルオプションの場合`:let &l:{option-name}`のように動作します 669 | 670 | ```lua 671 | vim.o.smarttab = false -- let &smarttab = v:false 672 | print(vim.o.smarttab) -- false 673 | vim.o.isfname = vim.o.isfname .. ',@-@' -- on Linux: let &isfname = &isfname .. ',@-@' 674 | print(vim.o.isfname) -- '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@' 675 | 676 | vim.bo.shiftwidth = 4 677 | print(vim.bo.shiftwidth) -- 4 678 | ``` 679 | 680 | バッファとウィンドウの番号を指定できます。0を指定した場合、カレントバッファ/ウィンドウが使用されます。: 681 | 682 | ```lua 683 | vim.bo[4].expandtab = true -- same as vim.api.nvim_buf_set_option(4, 'expandtab', true) 684 | vim.wo.number = true -- same as vim.api.nvim_win_set_option(0, 'number', true) 685 | ``` 686 | 687 | これらには、Luaで設定するのに便利なより洗練されたラッパーとして`vim.opt`があります。 688 | `init.vim`で慣れているものと似ています。: 689 | 690 | - `vim.opt.{option}`: `:set`のように動作します 691 | - `vim.opt_global.{option}`: `:setglobal`のように動作します 692 | - `vim.opt_local.{option}`: `:setlocal`のように動作します 693 | 694 | ```lua 695 | vim.opt.smarttab = false 696 | print(vim.opt.smarttab:get()) -- false 697 | ``` 698 | 699 | いくつかのオプションはLuaのテーブルを使用して設定できます。: 700 | 701 | ```lua 702 | vim.opt.completeopt = {'menuone', 'noselect'} 703 | print(vim.inspect(vim.opt.completeopt:get())) -- { "menuone", "noselect" } 704 | ``` 705 | 706 | list、map、setのようなオプションのラッパーには、Vim scriptの`:set+=`, `:set^=`, `:set-=`と同じように動作するメソッドとメタメソッドが用意されています。 707 | 708 | ```lua 709 | vim.opt.shortmess:append({ I = true }) 710 | -- どちらも等価です: 711 | vim.opt.shortmess = vim.opt.shortmess + { I = true } 712 | 713 | vim.opt.whichwrap:remove({ 'b', 's' }) 714 | -- どちらも等価です: 715 | vim.opt.whichwrap = vim.opt.whichwrap - { 'b', 's' } 716 | ``` 717 | 718 | 詳細は、必ず[`:help vim.opt`](https://neovim.io/doc/user/lua.html#vim.opt)を参照してください。 719 | 720 | 参照: 721 | - [`:help lua-vim-options`](https://neovim.io/doc/user/lua.html#lua-vim-options) 722 | 723 | ## vim内部の変数を管理する 724 | 725 | ### API関数を使用する 726 | 727 | オプションのように、内部変数にもAPI関数があります。 728 | 729 | - グローバル変数 (`g:`): 730 | - [`vim.api.nvim_set_var()`](https://neovim.io/doc/user/api.html#nvim_set_var()) 731 | - [`vim.api.nvim_get_var()`](https://neovim.io/doc/user/api.html#nvim_get_var()) 732 | - [`vim.api.nvim_del_var()`](https://neovim.io/doc/user/api.html#nvim_del_var()) 733 | - バッファ変数 (`b:`): 734 | - [`vim.api.nvim_buf_set_var()`](https://neovim.io/doc/user/api.html#nvim_buf_set_var()) 735 | - [`vim.api.nvim_buf_get_var()`](https://neovim.io/doc/user/api.html#nvim_buf_get_var()) 736 | - [`vim.api.nvim_buf_del_var()`](https://neovim.io/doc/user/api.html#nvim_buf_del_var()) 737 | - ウィンドウ変数 (`w:`): 738 | - [`vim.api.nvim_win_set_var()`](https://neovim.io/doc/user/api.html#nvim_win_set_var()) 739 | - [`vim.api.nvim_win_get_var()`](https://neovim.io/doc/user/api.html#nvim_win_get_var()) 740 | - [`vim.api.nvim_win_del_var()`](https://neovim.io/doc/user/api.html#nvim_win_del_var()) 741 | - タブ変数 (`t:`): 742 | - [`vim.api.nvim_tabpage_set_var()`](https://neovim.io/doc/user/api.html#nvim_tabpage_set_var()) 743 | - [`vim.api.nvim_tabpage_get_var()`](https://neovim.io/doc/user/api.html#nvim_tabpage_get_var()) 744 | - [`vim.api.nvim_tabpage_del_var()`](https://neovim.io/doc/user/api.html#nvim_tabpage_del_var()) 745 | - Vimの定義済み変数 (`v:`): 746 | - [`vim.api.nvim_set_vvar()`](https://neovim.io/doc/user/api.html#nvim_set_vvar()) 747 | - [`vim.api.nvim_get_vvar()`](https://neovim.io/doc/user/api.html#nvim_get_vvar()) 748 | 749 | Vimの定義済み変数を除いて、削除できます(Vim scriptの`:unlet`と同様です)。 750 | ローカル変数(`l:`)、スクリプト変数(`s:`)、関数の引数(`a:`)はVim script内でのみ意味があるため操作できません。 751 | Luaには独自のスコープルールがあります。 752 | 753 | これらの変数が不慣れな場合、[`:help internal-variables`](https://neovim.io/doc/user/eval.html#internal-variables)に説明があります。 754 | 755 | これらの関数は対象の変数名と、設定したい値を含む文字列を受け取ります。 756 | 757 | ```lua 758 | vim.api.nvim_set_var('some_global_variable', { key1 = 'value', key2 = 300 }) 759 | print(vim.inspect(vim.api.nvim_get_var('some_global_variable'))) -- { key1 = "value", key2 = 300 } 760 | vim.api.nvim_del_var('some_global_variable') 761 | ``` 762 | 763 | バッファ、ウィンドウ、タブページなスコープを持つ変数はそれぞれの番号を受け取ります(0を指定した場合は現在のバッファ/ウィンドウ/タブページが使われます。)。: 764 | 765 | ```lua 766 | vim.api.nvim_win_set_var(0, 'some_window_variable', 2500) 767 | vim.api.nvim_tab_set_var(3, 'some_tabpage_variable', 'hello world') 768 | print(vim.api.nvim_win_get_var(0, 'some_window_variable')) -- 2500 769 | print(vim.api.nvim_buf_get_var(3, 'some_tabpage_variable')) -- 'hello world' 770 | vim.api.nvim_win_del_var(0, 'some_window_variable') 771 | vim.api.nvim_buf_del_var(3, 'some_tabpage_variable') 772 | ``` 773 | 774 | ### メタアクセサーを使用する 775 | 776 | 内部の変数はメタアクセサーを使用し、もっと直感的に操作できます。: 777 | 778 | - [`vim.g.{name}`](https://neovim.io/doc/user/lua.html#vim.g): グローバル変数 779 | - [`vim.b.{name}`](https://neovim.io/doc/user/lua.html#vim.b): バッファ変数 780 | - [`vim.w.{name}`](https://neovim.io/doc/user/lua.html#vim.w): ウィンドウ変数 781 | - [`vim.t.{name}`](https://neovim.io/doc/user/lua.html#vim.t): タブ変数 782 | - [`vim.v.{name}`](https://neovim.io/doc/user/lua.html#vim.v): Vimの定義済み変数 783 | - [`vim.env.{name}`](https://neovim.io/doc/user/lua.html#vim.env): 環境変数 784 | 785 | ```lua 786 | vim.g.some_global_variable = { 787 | key1 = 'value', 788 | key2 = 300 789 | } 790 | 791 | print(vim.inspect(vim.g.some_global_variable)) -- { key1 = "value", key2 = 300 } 792 | 793 | -- 特定のバッファ/ウィンドウ/タブを対象とします(Neovim 0.6+) 794 | vim.b[2].myvar = 1 795 | ``` 796 | 797 | 一部の変数名には、Luaの識別子に使用できない文字が含まれている場合があります。 798 | この構文を使用してこれらの変数を操作できます。: `vim.g['my#variable']` 799 | 800 | 変数を削除するには単に`nil`を代入します。: 801 | 802 | ```lua 803 | vim.g.some_global_variable = nil 804 | ``` 805 | 806 | 参照: 807 | - [`:help lua-vim-variables`](https://neovim.io/doc/user/lua.html#lua-vim-variables) 808 | 809 | #### 警告 810 | 811 | 812 | 辞書の1つのキーを追加/更新/削除できません。例えば、次のVim scriptは期待通りに動きません。: 813 | 814 | ```vim 815 | let g:variable = {} 816 | lua vim.g.variable.key = 'a' 817 | echo g:variable 818 | " {} 819 | ``` 820 | 821 | 一時的な変数を使用する回避策があります: 822 | 823 | ```vim 824 | let g:variable = {} 825 | lua << EOF 826 | local tmp = vim.g.variable 827 | tmp.key = 'a' 828 | vim.g.variable = tmp 829 | EOF 830 | echo g:variable 831 | " {'key': 'a'} 832 | ``` 833 | 834 | 既知のissue: 835 | 836 | - [Issue #12544](https://github.com/neovim/neovim/issues/12544) 837 | 838 | ## Vim scriptの関数を呼び出す 839 | 840 | ### vim.fn.{function}() 841 | 842 | `vim.fn`は、Vim script組込みの関数を呼び出せます。 843 | 型はVimとLuaとで変換されます。 844 | 845 | ```lua 846 | print(vim.fn.printf('Hello from %s', 'Lua')) 847 | 848 | local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' }) 849 | print(vim.inspect(reversed_list)) -- { "c", "b", "a" } 850 | 851 | local function print_stdout(chan_id, data, name) 852 | print(data[1]) 853 | end 854 | 855 | vim.fn.jobstart('ls', { on_stdout = print_stdout }) 856 | ``` 857 | 858 | ハッシュ(`#`)はLuaで有効な識別子ではないため、autoload関数は次の構文で呼び出す必要があります。: 859 | 860 | ```lua 861 | vim.fn['my#autoload#function']() 862 | ``` 863 | 864 | `vim.fn`は`vim.call`と同じ動作ですが、よりLuaらしい構文を使用できます。 865 | 866 | `vim.api.nvim_call_function`とは、Vim/Luaオブジェクトを自動で変換する点が異なります。: 867 | `vim.api.nvim_call_function`は浮動小数点数のテーブルを返しLuaのクロージャーを受け入れませんが、`vim.fn`はこれらの型を扱えます。 868 | 869 | 参照: 870 | - [`:help vim.fn`](https://neovim.io/doc/user/lua.html#vim.fn) 871 | 872 | #### Tips 873 | 874 | Neovimにはプラグインに便利な強力な組込み関数を含むライブラリがあります。 875 | アルファベット順のリストは[`:help vim-function`](https://neovim.io/doc/user/eval.html#vim-function)を参照してください。 876 | [`:help function-list`](https://neovim.io/doc/user/usr_41.html#function-list)は機能別に分類されたリストです。 877 | 878 | NeovimのAPI関数は`vim.api{..}`のように直接使用できます。 879 | 詳細は[`:help api`](https://neovim.io/doc/user/api.html#API)を参照してください。 880 | 881 | #### 警告 882 | 883 | いくつかのVim関数はbool値の変わりに`1`か`0`を返します。これは、Vim scriptでは`1`は真で`0`は偽になるため問題ありません。 884 | 次のようなことが可能です。: 885 | 886 | ```vim 887 | if has('nvim') 888 | " do something... 889 | endif 890 | ``` 891 | 892 | しかし、Luaで偽になるのは`false`と`nil`のみで、数値は値に関係なく常に`true`と評価されます。 893 | 明示的に`1`か`0`かをチェックする必要があります。: 894 | 895 | ```lua 896 | if vim.fn.has('nvim') == 1 then 897 | -- do something... 898 | end 899 | ``` 900 | 901 | ## マッピングを定義する 902 | 903 | ### API関数 904 | 905 | Neovimはマッピングを設定、取得、削除するためのAPI関数を提供します。: 906 | 907 | - グローバルマッピング: 908 | - [`vim.api.nvim_set_keymap()`](https://neovim.io/doc/user/api.html#nvim_set_keymap()) 909 | - [`vim.api.nvim_get_keymap()`](https://neovim.io/doc/user/api.html#nvim_get_keymap()) 910 | - [`vim.api.nvim_del_keymap()`](https://neovim.io/doc/user/api.html#nvim_del_keymap()) 911 | - バッファローカルマッピング: 912 | - [`vim.api.nvim_buf_set_keymap()`](https://neovim.io/doc/user/api.html#nvim_buf_set_keymap()) 913 | - [`vim.api.nvim_buf_get_keymap()`](https://neovim.io/doc/user/api.html#nvim_buf_get_keymap()) 914 | - [`vim.api.nvim_buf_del_keymap()`](https://neovim.io/doc/user/api.html#nvim_buf_del_keymap()) 915 | 916 | `vim.api.nvim_set_keymap()`と`vim.api.nvim_buf_set_keymap()`から始めましょう。 917 | 918 | 最初の引数には有効にするモードの名前を含む文字列を渡します。: 919 | 920 | | String value | Help page | Affected modes | Vimscript equivalent | 921 | | ---------------------- | ------------- | ---------------------------------------- | -------------------- | 922 | | `''` (an empty string) | `mapmode-nvo` | Normal, Visual, Select, Operator-pending | `:map` | 923 | | `'n'` | `mapmode-n` | Normal | `:nmap` | 924 | | `'v'` | `mapmode-v` | Visual and Select | `:vmap` | 925 | | `'s'` | `mapmode-s` | Select | `:smap` | 926 | | `'x'` | `mapmode-x` | Visual | `:xmap` | 927 | | `'o'` | `mapmode-o` | Operator-pending | `:omap` | 928 | | `'!'` | `mapmode-ic` | Insert and Command-line | `:map!` | 929 | | `'i'` | `mapmode-i` | Insert | `:imap` | 930 | | `'l'` | `mapmode-l` | Insert, Command-line, Lang-Arg | `:lmap` | 931 | | `'c'` | `mapmode-c` | Command-line | `:cmap` | 932 | | `'t'` | `mapmode-t` | Terminal | `:tmap` | 933 | 934 | 2つ目の引数は、左側のマッピングを含む文字列(マッピングで定義されたコマンドを起動するためのキー)です。 935 | 空の文字列は``と同じで、キーを無効にします。 936 | 937 | 3つ目の引数は、右側のマッピングを含む文字列(実行するコマンド)です。 938 | 939 | 最後の引数は、[`:help :map-arguments`](https://neovim.io/doc/user/map.html#:map-arguments)で定義されているbool型のオプションのテーブルです(`noremap`を含み、`buffer`を除く)。 940 | Neovim 0.7.0から、マッピング実行時、右側のマッピングの代わりに `callback` オプションに渡した関数を呼び出せます。 941 | 942 | バッファローカルなマッピングは、バッファ番号を引数の最初に受け取ります(`0`を指定した場合、カレントバッファです)。 943 | 944 | ```lua 945 | vim.api.nvim_set_keymap('n', '', ':set hlsearch!', { noremap = true, silent = true }) 946 | -- :nnoremap :set hlsearch 947 | vim.api.nvim_set_keymap('n', 'tegf', [[lua require('telescope.builtin').git_files()]], { noremap = true, silent = true }) 948 | -- :nnoremap tegf lua require('telescope.builtin').git_files() 949 | 950 | vim.api.nvim_buf_set_keymap(0, '', 'cc', 'line(".") == 1 ? "cc" : "ggcc"', { noremap = true, expr = true }) 951 | -- :noremap cc line('.') == 1 ? 'cc' : 'ggcc' 952 | 953 | vim.api.nvim_set_keymap('n', 'ex', '', { 954 | noremap = true, 955 | callback = function() 956 | print('My example') 957 | end, 958 | -- Lua関数は便利な文字列表現を持っていないため、 "desc" オプションを使用してマッピングの説明を記入できます。 959 | desc = 'Prints "My example" in the message area', 960 | }) 961 | ``` 962 | 963 | `vim.api.nvim_get_keymap()`は、モードの省略名(上記の表を参照)を含む文字列を受け取ります。 964 | そのモードにあるすべてのグローバルマッピングのテーブルを返します。 965 | 966 | ```lua 967 | print(vim.inspect(vim.api.nvim_get_keymap('n'))) 968 | -- :verbose nmap 969 | ``` 970 | 971 | `vim.api.nvim_buf_get_keymap()`は、最初の引数に追加でバッファ番号を受け取ります(`0`を指定した場合、カレントバッファです)。 972 | 973 | ```lua 974 | print(vim.inspect(vim.api.nvim_buf_get_keymap(0, 'i'))) 975 | -- :verbose imap 976 | ``` 977 | 978 | `vim.api.nvim_del_keymap()`は、モードと左側のマッピングを受け取ります。 979 | 980 | ```lua 981 | vim.api.nvim_del_keymap('n', '') 982 | -- :nunmap 983 | ``` 984 | 985 | この場合でも、`vim.api.nvim_buf_del_keymap()`は最初の引数にバッファ番号を受け取ります。`0`を指定した場合、カレントバッファです。 986 | 987 | ```lua 988 | vim.api.nvim_buf_del_keymap(0, 'i', '') 989 | -- :iunmap 990 | ``` 991 | 992 | ### vim.keymap 993 | 994 | :warning: このセクションで説明するAPI関数はNeovim 0.7.0+のみで使用できます。 995 | 996 | Neovimはマッピングを設定/削除できる2つの関数を提供します: 997 | - [`vim.keymap.set()`](https://neovim.io/doc/user/lua.html#vim.keymap.set()) 998 | - [`vim.keymap.del()`](https://neovim.io/doc/user/lua.html#vim.keymap.del()) 999 | 1000 | これらは、上記のAPI関数に糖類構文を追加したようなものです。 1001 | 1002 | `vim.keymap.set()` は最初の引数として文字列を受け取ります。 1003 | また、複数のモードのマッピングを1度に定義するため、文字列のテーブルを受け取ることもできます: 1004 | 1005 | ```lua 1006 | vim.keymap.set('n', 'ex1', 'lua vim.notify("Example 1")') 1007 | vim.keymap.set({'n', 'c'}, 'ex2', 'lua vim.notify("Example 2")') 1008 | ``` 1009 | 1010 | 2つ目の引数は左側のマッピングです。 1011 | 1012 | 3つ目の引数は右側のマッピングで、文字列かLua関数を受け取れます。 1013 | 1014 | ```lua 1015 | vim.keymap.set('n', 'ex1', 'echomsg "Example 1"') 1016 | vim.keymap.set('n', 'ex2', function() print("Example 2") end) 1017 | vim.keymap.set('n', 'pl1', require('plugin').plugin_action) 1018 | -- モジュールの読み込みによる起動コストを避けるため、マッピングを呼び出したときにモジュールの遅延読みこみができるように関数でラップすることができます。: 1019 | vim.keymap.set('n', 'pl2', function() require('plugin').plugin_action() end) 1020 | ``` 1021 | 1022 | 4つ目の引数(省略可能)はオプションのテーブルで、 `vim.api.nvim_set_keymap()` に渡されるオプションに対応しており、いくつか追加項目があります([`:help vim.keymap.set()`](https://neovim.io/doc/user/lua.html#vim.keymap.set())に一覧があります)。 1023 | 1024 | ```lua 1025 | vim.keymap.set('n', 'ex1', 'echomsg "Example 1"', {buffer = true}) 1026 | vim.keymap.set('n', 'ex2', function() print('Example 2') end, {desc = 'Prints "Example 2" to the message area'}) 1027 | ``` 1028 | 1029 | 文字列を使用して定義するキーマップとLua関数で定義したキーマップは違います。 1030 | 通常の`:nmap ex1`のようなキーマップ情報を表示する方法では、 1031 | `Lua function` とだけ表示され有用な情報(関数の内容自体)が表示されません。 1032 | キーマップの動作を説明する`desc`キーを追加するのを推奨します。 1033 | これはプラグインのマッピングのドキュメント化に特に重要です。 1034 | ユーザーはキーマップの使用方法をより簡単に理解できます。 1035 | 1036 | このAPIが面白いところとして、Vimのマッピングの歴史的な癖をいくつか解消しています。 1037 | - `rhs` が `` マッピングである場合以外、デフォルトで `noremap` です。 1038 | このため、マッピングが再帰的であるかを考える必要はあまりないです。 1039 | 1040 | ```lua 1041 | vim.keymap.set('n', 'test1', 'echo "test"') 1042 | -- :nnoremap test echo "test" 1043 | 1044 | -- マッピングを再帰的に行ないたい場合は、 `remap` オプションを `true` にします 1045 | vim.keymap.set('n', '>', ']', {remap = true}) 1046 | -- :nmap > ] 1047 | 1048 | -- マッピングは再帰的でないと機能しませんが、 vim.keymap.set() は自動的に処理します 1049 | vim.keymap.set('n', 'plug', '(plugin)') 1050 | -- :nmap plug (plugin) 1051 | ``` 1052 | 1053 | - `expr` マッピングが有効なら、 Lua関数が返す文字列に対して `nvim_replace_termcodes()` が自動的に適用されます: 1054 | 1055 | ```lua 1056 | vim.keymap.set('i', '', function() 1057 | return vim.fn.pumvisible == 1 and '' or '' 1058 | end, {expr = true}) 1059 | ``` 1060 | 1061 | 参照: 1062 | - [`:help recursive_mapping`](https://neovim.io/doc/user/map.html#recursive_mapping) 1063 | 1064 | `vim.keymap.del()` も同じように機能しますが、マッピングを削除します: 1065 | 1066 | ```lua 1067 | vim.keymap.del('n', 'ex1') 1068 | vim.keymap.del({'n', 'c'}, 'ex2', {buffer = true}) 1069 | ``` 1070 | 1071 | ## ユーザーコマンドを定義する 1072 | 1073 | :warning: このセクションで説明するAPI関数はNeovim 0.7.0+のみで使用できます。 1074 | 1075 | Neovimはユーザーコマンドを作成するAPI関数を提供します。 1076 | 1077 | - Global user commands: 1078 | - [`vim.api.nvim_create_user_command()`](https://neovim.io/doc/user/api.html#nvim_create_user_command()) 1079 | - [`vim.api.nvim_del_user_command()`](https://neovim.io/doc/user/api.html#nvim_del_user_command()) 1080 | - Buffer-local user commands: 1081 | - [`vim.api.nvim_buf_create_user_command()`](https://neovim.io/doc/user/api.html#nvim_buf_create_user_command()) 1082 | - [`vim.api.nvim_buf_del_user_command()`](https://neovim.io/doc/user/api.html#nvim_buf_del_user_command()) 1083 | 1084 | まず `vim.api.nvim_create_user_command()` から始めます 1085 | 1086 | 最初の引数はコマンドの名前です(名前は大文字で始める必要があります)。 1087 | 1088 | 2つめの引数はコマンドが呼びだされたときに実行するコードです。次のどちらかでコードを指定できます: 1089 | 1090 | 文字列(この場合、VimScriptとして実行されます)。`:commands` のように、``, `` などのエスケープシーケンスを使用できます。 1091 | ```lua 1092 | vim.api.nvim_create_user_command('Upper', 'echo toupper()', { nargs = 1 }) 1093 | -- :command! -nargs=1 Upper echo toupper() 1094 | 1095 | vim.cmd('Upper hello world') -- prints "HELLO WORLD" 1096 | ``` 1097 | 1098 | もしくは、Lua関数。通常のエスケープシーケンスによって提供されるデータを含む、辞書のようなテーブルを受け取ります(利用できるキーのリストは[`:help nvim_create_user_command()`](https://neovim.io/doc/user/api.html#nvim_create_user_command())で確認できます)。 1099 | ```lua 1100 | vim.api.nvim_create_user_command( 1101 | 'Upper', 1102 | function(opts) 1103 | print(string.upper(opts.args)) 1104 | end, 1105 | { nargs = 1 } 1106 | ) 1107 | ``` 1108 | 1109 | 3つめの引数はコマンドの属性をテーブルとして渡せます([`:help command-attributes`](https://neovim.io/doc/user/map.html#command-attributes)を参照)。`vim.api.nvim_buf_create_user_command()`を使用すればバッファローカルなユーザーコマンドを定義できるため、`-buffer`は有効な属性ではありません。 1110 | 1111 | 追加された2つの属性: 1112 | - `desc`はLuaのコールバックとして定義されたコマンドに対して`:command {cmd}`を実行したときの表示内容を制御できます。 1113 | キーマップと同様、Lua関数として定義するコマンドには `desc`キーを追加するのを推奨します。 1114 | - `force`は`:command!`を呼び出すのと同じで、同じ名前のユーザーコマンドが既に存在する場合、そのコマンドを置き換えます。Vimscriptとは異なり、デフォルトでtrueです。 1115 | 1116 | `-complete`属性は[`:help :command-complete`](https://neovim.io/doc/user/map.html#:command-complete)に記載されている属性に加え、Lua関数を取ることができます。 1117 | 1118 | ```lua 1119 | vim.api.nvim_create_user_command('Upper', function() end, { 1120 | nargs = 1, 1121 | complete = function(ArgLead, CmdLine, CursorPos) 1122 | -- return completion candidates as a list-like table 1123 | return { 'foo', 'bar', 'baz' } 1124 | end, 1125 | }) 1126 | ``` 1127 | 1128 | バッファローカルなユーザーコマンドも第1引数にバッファ番号を受け取ります。現在のバッファ用のコマンドを定義することができる`-buffer`より、これは便利です。 1129 | 1130 | ```lua 1131 | vim.api.nvim_buf_create_user_command(4, 'Upper', function() end, {}) 1132 | ``` 1133 | 1134 | `vim.api.nvim_del_user_command()` はコマンド名を受け取ります。 1135 | 1136 | ```lua 1137 | vim.api.nvim_del_user_command('Upper') 1138 | -- :delcommand Upper 1139 | ``` 1140 | 1141 | ここでも、`vim.api.nvim_buf_del_user_command()`はバッファ番号を第1引数として受け取り、`0`は現在のバッファを表します。 1142 | 1143 | ```lua 1144 | vim.api.nvim_buf_del_user_command(4, 'Upper') 1145 | ``` 1146 | 1147 | 参照: 1148 | - [`:help nvim_create_user_command()`](https://neovim.io/doc/user/api.html#nvim_create_user_command()) 1149 | - [`:help 40.2`](https://neovim.io/doc/user/usr_40.html#40.2) 1150 | - [`:help command-attributes`](https://neovim.io/doc/user/map.html#command-attributes) 1151 | 1152 | #### 警告 1153 | 1154 | `-complete=custom`属性は自動的に補完候補をフィルタリングし、ワイルドカード([`:help wildcard`](https://neovim.io/doc/user/editing.html#wildcard))をサポートする機能を組み込みます: 1155 | 1156 | ```vim 1157 | function! s:completion_function(ArgLead, CmdLine, CursorPos) abort 1158 | return join([ 1159 | \ 'strawberry', 1160 | \ 'star', 1161 | \ 'stellar', 1162 | \ ], "\n") 1163 | endfunction 1164 | 1165 | command! -nargs=1 -complete=custom,s:completion_function Test echo 1166 | " `:Test st[ae]` と入力すると "star" と "stellar" を返します 1167 | ``` 1168 | 1169 | `complete` にLua関数を渡すと、ユーザーにフィルタ方法を任せる`customlist`のような動作をします。 1170 | 1171 | ```lua 1172 | vim.api.nvim_create_user_command('Test', function() end, { 1173 | nargs = 1, 1174 | complete = function(ArgLead, CmdLine, CursorPos) 1175 | return { 1176 | 'strawberry', 1177 | 'star', 1178 | 'stellar', 1179 | } 1180 | end, 1181 | }) 1182 | 1183 | -- 候補リストをフィルタしてないので `:Test z` と入力すると全ての補完候補を返します 1184 | ``` 1185 | 1186 | ## オートコマンドを定義する 1187 | 1188 | (この章は現在作成中です) 1189 | 1190 | Neovim 0.7.0はオートコマンド用のAPI関数を持っています。詳細は `:help api-autocmd` を参照してください。 1191 | 1192 | - [Pull request #14661](https://github.com/neovim/neovim/pull/14661) (lua: autocmds take 2) 1193 | 1194 | ## ハイライトを定義する 1195 | 1196 | (この章は現在作成中です) 1197 | 1198 | Neovim 0.7.0はハイライトグループ用のAPI関数を持っています。 1199 | 1200 | 参照: 1201 | - [`:help nvim_set_hl()`](https://neovim.io/doc/user/api.html#nvim_set_hl()) 1202 | - [`:help nvim_get_hl_by_id()`](https://neovim.io/doc/user/api.html#nvim_get_hl_by_id()) 1203 | - [`:help nvim_get_hl_by_name()`](https://neovim.io/doc/user/api.html#nvim_get_hl_by_name()) 1204 | 1205 | ## 一般的なTipsと推奨 1206 | 1207 | ### キャッシュされたモジュールのリロード 1208 | 1209 | Luaでは、`require()`関数がモジュールをキャッシュします。 1210 | これはパフォーマンスには良いですが、後から`require()`を呼んでもモジュールは更新されないため少し面倒です。 1211 | 1212 | 特定のモジュールのキャッシュを更新する場合、`package.loaded`グローバルテーブルを変更する必要があります。: 1213 | 1214 | ```lua 1215 | package.loaded['modname'] = nil 1216 | require('modname') -- 新しい'modname'モジュールを読み込みます 1217 | ``` 1218 | 1219 | [nvim-lua/plenary.nvim](https://github.com/nvim-lua/plenary.nvim)には、これを行う[関数](https://github.com/nvim-lua/plenary.nvim/blob/master/lua/plenary/reload.lua)があります。 1220 | 1221 | ### Luaの文字列をパディングしないでください! 1222 | 1223 | 二重括弧の文字列を使用するとき、パディングの誘惑に負けないでください! スペースを無視するときは問題ないですが、スペースが重要な意味を持つときはデバックが困難な問題の原因になる可能性があります。: 1224 | 1225 | ```lua 1226 | vim.api.nvim_set_keymap('n', 'f', [[ call foo() ]], {noremap = true}) 1227 | ``` 1228 | 1229 | 上記の例では、`f`は`call foo()`ではなく`call foo()`にマッピングされます。 1230 | 1231 | ### Vim script <--> Lua 型変換の注意 1232 | 1233 | #### 変数を変換するとコピーが作られます: 1234 | 1235 | VimからLua、LuaからVimのオブジェクトの参照を直接操作できません。 1236 | 例えば、Vim scriptの`map()`は変数をその場で変更します(破壊的)。 1237 | 1238 | ```vim 1239 | let s:list = [1, 2, 3] 1240 | let s:newlist = map(s:list, {_, v -> v * 2}) 1241 | 1242 | echo s:list 1243 | " [2, 4, 6] 1244 | echo s:newlist 1245 | " [2, 4, 6] 1246 | echo s:list is# s:newlist 1247 | " 1 1248 | ``` 1249 | 1250 | Luaからこの関数を使用すると、代りにコピーが作られます 1251 | 1252 | ```lua 1253 | local tbl = {1, 2, 3} 1254 | local newtbl = vim.fn.map(tbl, function(_, v) return v * 2 end) 1255 | 1256 | print(vim.inspect(tbl)) -- { 1, 2, 3 } 1257 | print(vim.inspect(newtbl)) -- { 2, 4, 6 } 1258 | print(tbl == newtbl) -- false 1259 | ``` 1260 | 1261 | #### 変換を常にできるとは限りません 1262 | 1263 | これは主に関数とテーブルに影響します。 1264 | 1265 | Luaのリストと辞書が混在するテーブルは変換できません。 1266 | 1267 | ```lua 1268 | print(vim.fn.count({1, 1, number = 1}, 1)) 1269 | -- E5100: Cannot convert given lua table: table should either have a sequence of positive integer keys or contain only string keys 1270 | ``` 1271 | 1272 | Luaで`vim.fn`を使用してVim関数を呼べますが、それらの参照を保持できません。 1273 | それは不測の動作の原因になります。: 1274 | 1275 | ```lua 1276 | local FugitiveHead = vim.fn.funcref('FugitiveHead') 1277 | print(FugitiveHead) -- vim.NIL 1278 | 1279 | vim.cmd("let g:test_dict = {'test_lambda': {-> 1}}") 1280 | print(vim.g.test_dict.test_lambda) -- nil 1281 | print(vim.inspect(vim.g.test_dict)) -- {} 1282 | ``` 1283 | 1284 | Luaの関数をVimの関数に渡せますが、Vimの変数に格納できません。 1285 | (Neovim 0.7.0+で修正されて、格納できるようになりました。) 1286 | 1287 | ```lua 1288 | -- This works: 1289 | vim.fn.jobstart({'ls'}, { 1290 | on_stdout = function(chan_id, data, name) 1291 | print(vim.inspect(data)) 1292 | end 1293 | }) 1294 | 1295 | -- This doesn't: 1296 | vim.g.test_dict = {test_lambda = function() return 1 end} -- Error: Cannot convert given lua type 1297 | ``` 1298 | 1299 | ただし、Vim scriptから`luaeval()`を使用して同じことをすると**動作します**。: 1300 | 1301 | ```vim 1302 | let g:test_dict = {'test_lambda': luaeval('function() return 1 end')} 1303 | echo g:test_dict 1304 | " {'test_lambda': function('4714')} 1305 | ``` 1306 | 1307 | #### Vim booleans 1308 | Vim scriptの一般的なパターンではbool値の代わりに`1`と`0`を使用します。 1309 | 実際、Vimにはバージョン7.4.1154まで区別されたbool型がありませんでした。 1310 | 1311 | Luaのbool値は数値ではなく、Vim scriptの実際のbool値に変換されます。: 1312 | 1313 | ```vim 1314 | lua vim.g.lua_true = true 1315 | echo g:lua_true 1316 | " v:true 1317 | lua vim.g.lua_false = false 1318 | echo g:lua_false 1319 | " v:false 1320 | ``` 1321 | 1322 | ### リンターと言語サーバーの設定 1323 | 1324 | Luaのプロジェクトでリンターや言語サーバーを使用して、診断と自動補完を利用している場合、Neovim固有の設定が必要になる場合があります。人気のあるツールの推奨設定は次のとおりです。: 1325 | 1326 | #### luacheck 1327 | 1328 | 次の設定を `~/.luacheckrc` (もしくは `$XDG_CONFIG_HOME/luacheck/.luacheckrc`)に配置すれば、[luacheck](https://github.com/mpeterv/luacheck/)でvimモジュールを認識できます。: 1329 | 1330 | 1331 | ```lua 1332 | globals = { 1333 | "vim", 1334 | } 1335 | ``` 1336 | 1337 | 言語サーバーの[Alloyed/lua-lsp](https://github.com/Alloyed/lua-lsp/)は `luacheck` を使用してリンティングを提供し、同じファイルを読み込みます。 1338 | 1339 | `luacheck` の設定方法の詳細は[ドキュメント](https://luacheck.readthedocs.io/en/stable/config.html)を参照してください。 1340 | 1341 | #### sumneko/lua-language-server 1342 | 1343 | [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig/)リポジトリに[sumneko/lua-language-serverの設定方法](https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#sumneko_lua)があります(例は組込みのLSPクライアントを使っていますが、他のLSPクライアントでも同じ設定である必要があります)。 1344 | 1345 | [sumneko/lua-language-server](https://github.com/sumneko/lua-language-server/)の設定方法の詳細は["Setting"](https://github.com/sumneko/lua-language-server/wiki/Setting)を見てください。 1346 | 1347 | #### coc.nvim 1348 | 1349 | [coc.nvim](https://github.com/neoclide/coc.nvim/)の補完ソースである[rafcamlet/coc-nvim-lua](https://github.com/rafcamlet/coc-nvim-lua/)はNeovim stdlibの項目を提供しています。 1350 | 1351 | ### Luaコードのデバッグ 1352 | 1353 | 別のNeovimインスタンスで実行しているLuaコードを[jbyuki/one-small-step-for-vimkind](https://github.com/jbyuki/one-small-step-for-vimkind)でデバッグできます。 1354 | 1355 | このプラグインは[Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/)を使用しています。 1356 | デバッグアダプターに接続するには、[mfussenegger/nvim-dap](https://github.com/mfussenegger/nvim-dap/)や[puremourning/vimspector](https://github.com/puremourning/vimspector/)のようなDAPクライアントが必要です。 1357 | 1358 | ### Luaマッピング/コマンド/オートコマンドのデバッグ 1359 | 1360 | マッピング/コマンド/オートコマンドが定義されている位置を `:verbose` コマンドで確認できます: 1361 | 1362 | ```vim 1363 | :verbose map m 1364 | ``` 1365 | 1366 | ```text 1367 | n m_ * echo 'example' 1368 | Last set from ~/.config/nvim/init.vim line 26 1369 | ``` 1370 | 1371 | デフォルトでは、Luaのパフォーマンス上の理由でこの機能は無効です。 1372 | Neovim起動時にverboseのレベルが0より上なら、この機能を有効にできます: 1373 | 1374 | ```sh 1375 | nvim -V1 1376 | ``` 1377 | 1378 | 参照: 1379 | - [`:help 'verbose'`](https://neovim.io/doc/user/options.html#'verbose') 1380 | - [`:help -V`](https://neovim.io/doc/user/starting.html#-V) 1381 | - [neovim/neovim#15079](https://github.com/neovim/neovim/pull/15079) 1382 | 1383 | ### Luaコードのテスト 1384 | 1385 | - [plenary.nvim: test harness](https://github.com/nvim-lua/plenary.nvim/#plenarytest_harness) 1386 | - [notomo/vusted](https://github.com/notomo/vusted) 1387 | 1388 | ### Luarocksパッケージを使用する 1389 | 1390 | [wbthomason/packer.nvim](https://github.com/wbthomason/packer.nvim)はLuarocksパッケージをサポートしています。 1391 | 使い方は[README](https://github.com/wbthomason/packer.nvim/#luarocks-support)にあります。 1392 | 1393 | ## その他 1394 | 1395 | ### vim.loop 1396 | 1397 | `vim.loop`はLibUV APIを公開するモジュールです。いくつかのリソース: 1398 | 1399 | - [Official documentation for LibUV](https://docs.libuv.org/en/v1.x/) 1400 | - [Luv documentation](https://github.com/luvit/luv/blob/master/docs.md) 1401 | - [teukka.tech - Using LibUV in Neovim](https://teukka.tech/posts/2020-01-07-vimloop/) 1402 | 1403 | 参照: 1404 | - [`:help vim.loop`](https://neovim.io/doc/user/lua.html#vim.loop) 1405 | 1406 | ### vim.lsp 1407 | 1408 | `vim.lsp`は組込みのLSPクライアントを操作するためのモジュールです。 1409 | [neovim/nvim-lspconfig](https://github.com/neovim/nvim-lspconfig/)は有名なLanguage Serverの設定集です。 1410 | 1411 | クライアントの動作は"lsp-handlers"を使用して設定できます。詳細はこちら: 1412 | - [`:help lsp-handler`](https://neovim.io/doc/user/lsp.html#lsp-handler) 1413 | - [neovim/neovim#12655](https://github.com/neovim/neovim/pull/12655) 1414 | - [How to migrate from diagnostic-nvim](https://github.com/nvim-lua/diagnostic-nvim/issues/73#issue-737897078) 1415 | 1416 | 1417 | LSPクライアントを利用した[プラグイン](https://github.com/rockerBOO/awesome-neovim#lsp)も見たいかもしれません。 1418 | 1419 | 参照: 1420 | - [`:help lsp`](https://neovim.io/doc/user/lsp.html#LSP) 1421 | 1422 | ### vim.treesitter 1423 | 1424 | `vim.treesitter`はNeovim内の[Tree-sitter](https://tree-sitter.github.io/tree-sitter/)ライブラリを操作するためのモジュールです。 1425 | Tree-sitterについてもっと知りたいなら、この[プレゼン (38:37)](https://www.youtube.com/watch?v=Jes3bD6P0To)に興味があるかもしれません。 1426 | 1427 | [nvim-treesitter](https://github.com/nvim-treesitter/)オリジネーションは、ライブラリを利用して様々なプラグインをホストしています。 1428 | 1429 | 参照: 1430 | - [`:help lua-treesitter`](https://neovim.io/doc/user/treesitter.html#lua-treesitter) 1431 | 1432 | ### トランスパイラ 1433 | 1434 | Luaを使用する利点の1つは実際にLuaを書く必要がないことです!利用できるトランスパイラはたくさんあります。 1435 | 1436 | - [Moonscript](https://moonscript.org/) 1437 | 1438 | おそらく、最も知られているLuaのトランスパイラです。クラス、リスト内包表記、関数リテラルなどの便利な機能を多数追加します。 1439 | [svermeulen/nvim-moonmaker](https://github.com/svermeulen/nvim-moonmaker)はNeovimのプラグインと設定をMoonscriptで直接書けるようにします。 1440 | 1441 | - [Fennel](https://fennel-lang.org/) 1442 | 1443 | lispをLuaにコンパイルします。[Olical/aniseed](https://github.com/Olical/aniseed)または、[Hotpot](https://github.com/rktjmp/hotpot.nvim)を使用するとNeovimのプラグインと設定を書くことができます。 1444 | さらに、[Olical/conjure](https://github.com/Olical/conjure)は対話的な開発環境を提供します(他の言語の中で)。 1445 | 1446 | - [Teal](https://github.com/teal-language/tl) 1447 | 1448 | Tealの名前の由来はTL(typed lua)の発音からです。 1449 | まさにその通りで、強力な型をLuaに追加し、それ以外は標準のLuaの構文に近づけています。 1450 | [nvim-teal-maker](https://github.com/svermeulen/nvim-teal-maker)プラグインを使用して、 1451 | TealでNeovimプラグインや設定ファイルを書けます。 1452 | 1453 | その他の興味深いプロジェクト: 1454 | - [TypeScriptToLua/TypeScriptToLua](https://github.com/TypeScriptToLua/TypeScriptToLua) 1455 | - [Haxe](https://haxe.org/) 1456 | - [SwadicalRag/wasm2lua](https://github.com/SwadicalRag/wasm2lua) 1457 | - [hengestone/lua-languages](https://github.com/hengestone/lua-languages) 1458 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | :arrow_upper_left: (Feeling lost? Use the GitHub TOC!) 2 | 3 | **:warning: :warning: :warning: A more up-to-date version of this guide is available in the Neovim documentation, see [`:help lua-guide`](https://neovim.io/doc/user/lua-guide.html#lua-guide) :warning: :warning: :warning:** 4 | 5 | --- 6 | 7 | # Getting started using Lua in Neovim 8 | 9 | ## Translations 10 | 11 | - [Chinese version](https://github.com/glepnir/nvim-lua-guide-zh) 12 | - [Spanish version](https://github.com/RicardoRien/nvim-lua-guide/blob/master/README.esp.md) 13 | - [Portuguese version](https://github.com/npxbr/nvim-lua-guide/blob/master/README.pt-br.md) 14 | - [Japanese version](https://github.com/willelz/nvim-lua-guide-ja/blob/master/README.ja.md) 15 | - [Russian version](https://github.com/kuator/nvim-lua-guide-ru) 16 | - [Ukrainian version](https://github.com/famiclone/nvim-lua-guide-ua) 17 | - [Korean version](https://github.com/krapjost/nvim-lua-guide-kr) 18 | 19 | ## Introduction 20 | 21 | The [integration of Lua](https://www.youtube.com/watch?v=IP3J56sKtn0) as a [first-class language inside Neovim](https://github.com/neovim/neovim/wiki/FAQ#why-embed-lua-instead-of-x) is shaping up to be one of its killer features. 22 | However, the amount of teaching material for learning how to write plugins in Lua is not as large as what you would find for writing them in Vimscript. This is an attempt at providing some basic information to get people started. 23 | 24 | This guide assumes you are using at least version 0.5 of Neovim. 25 | 26 | ### Learning Lua 27 | 28 | If you are not already familiar with the language, there are plenty of resources to get started: 29 | 30 | - The [Learn X in Y minutes page about Lua](https://learnxinyminutes.com/docs/lua/) should give you a quick overview of the basics 31 | - [This guide](https://github.com/medwatt/Notes/blob/main/Lua/Lua_Quick_Guide.ipynb) is also a good resource for getting started quickly 32 | - If videos are more to your liking, Derek Banas has a [1-hour tutorial on the language](https://www.youtube.com/watch?v=iMacxZQMPXs) 33 | - Want something a little more interactive with runnable examples? Try [the LuaScript tutorial](https://www.luascript.dev/learn) 34 | - The [lua-users wiki](http://lua-users.org/wiki/LuaDirectory) is full of useful information on all kinds of Lua-related topics 35 | - The [official reference manual for Lua](https://www.lua.org/manual/5.1/) should give you the most comprehensive tour of the language (exists as a Vimdoc plugin if you want to read it from the comfort of your editor: [milisims/nvim-luaref](https://github.com/milisims/nvim-luaref)) 36 | 37 | It should also be noted that Lua is a very clean and simple language. It is easy to learn, especially if you have experience with similar scripting languages like JavaScript. You may already know more Lua than you realise! 38 | 39 | Note: the version of Lua that Neovim embeds is [LuaJIT](https://staff.fnwi.uva.nl/h.vandermeer/docs/lua/luajit/luajit_intro.html) 2.1.0, which maintains compatibility with Lua 5.1. 40 | 41 | ### Existing tutorials for writing Lua in Neovim 42 | 43 | A few tutorials have already been written to help people write plugins in Lua. Some of them helped quite a bit when writing this guide. Many thanks to their authors. 44 | 45 | - [teukka.tech - From init.vim to init.lua](https://teukka.tech/luanvim.html) 46 | - [dev.to - How to write neovim plugins in Lua](https://dev.to/2nit/how-to-write-neovim-plugins-in-lua-5cca) 47 | - [dev.to - How to make UI for neovim plugins in Lua](https://dev.to/2nit/how-to-make-ui-for-neovim-plugins-in-lua-3b6e) 48 | - [ms-jpq - Neovim Async Tutorial](https://github.com/ms-jpq/neovim-async-tutorial) 49 | - [oroques.dev - Neovim 0.5 features and the switch to init.lua](https://oroques.dev/notes/neovim-init/) 50 | - [Building A Vim Statusline from Scratch - jdhao's blog](https://jdhao.github.io/2019/11/03/vim_custom_statusline/) 51 | - [Configuring Neovim using Lua](https://icyphox.sh/blog/nvim-lua/) 52 | - [Devlog | Everything you need to know to configure neovim using lua](https://vonheikemen.github.io/devlog/tools/configuring-neovim-using-lua/) 53 | 54 | ### Companion plugins 55 | 56 | - [Vimpeccable](https://github.com/svermeulen/vimpeccable) - Plugin to help write your .vimrc in Lua 57 | - [plenary.nvim](https://github.com/nvim-lua/plenary.nvim) - All the lua functions I don't want to write twice 58 | - [popup.nvim](https://github.com/nvim-lua/popup.nvim) - An implementation of the Popup API from vim in Neovim 59 | - [nvim_utils](https://github.com/norcalli/nvim_utils) 60 | - [nvim-luadev](https://github.com/bfredl/nvim-luadev) - REPL/debug console for nvim lua plugins 61 | - [nvim-luapad](https://github.com/rafcamlet/nvim-luapad) - Interactive real time neovim scratchpad for embedded lua engine 62 | - [nlua.nvim](https://github.com/tjdevries/nlua.nvim) - Lua Development for Neovim 63 | - [BetterLua.vim](https://github.com/euclidianAce/BetterLua.vim) - Better Lua syntax highlighting in Vim/NeoVim 64 | 65 | ## Where to put Lua files 66 | 67 | ### init.lua 68 | 69 | Neovim supports loading an `init.lua` file for configuration instead of the usual `init.vim`. 70 | 71 | Note: `init.lua` is of course _completely_ optional. Support for `init.vim` is not going away and is still a valid option for configuration. Do keep in mind that some features are not 100% exposed to Lua yet. 72 | 73 | See also: 74 | - [`:help config`](https://neovim.io/doc/user/starting.html#config) 75 | 76 | ### Modules 77 | 78 | Lua modules are found inside a `lua/` folder in your `'runtimepath'` (for most users, this will mean `~/.config/nvim/lua` on \*nix systems and `~/AppData/Local/nvim/lua` on Windows). You can `require()` files in this folder as Lua modules. 79 | 80 | Let's take the following folder structure as an example: 81 | 82 | ```text 83 | 📂 ~/.config/nvim 84 | ├── 📁 after 85 | ├── 📁 ftplugin 86 | ├── 📂 lua 87 | │ ├── 🌑 myluamodule.lua 88 | │ └── 📂 other_modules 89 | │ ├── 🌑 anothermodule.lua 90 | │ └── 🌑 init.lua 91 | ├── 📁 pack 92 | ├── 📁 plugin 93 | ├── 📁 syntax 94 | └── 🇻 init.vim 95 | ``` 96 | 97 | The following Lua code will load `myluamodule.lua`: 98 | 99 | ```lua 100 | require('myluamodule') 101 | ``` 102 | 103 | Notice the absence of a `.lua` extension. 104 | 105 | Similarly, loading `other_modules/anothermodule.lua` is done like so: 106 | 107 | ```lua 108 | require('other_modules.anothermodule') 109 | -- or 110 | require('other_modules/anothermodule') 111 | ``` 112 | 113 | Path separators are denoted by either a dot `.` or a slash `/`. 114 | 115 | A folder containing an `init.lua` file can be required directly, without having to specify the name of the file. 116 | 117 | ```lua 118 | require('other_modules') -- loads other_modules/init.lua 119 | ``` 120 | 121 | Requiring a nonexistent module or a module which contains syntax errors aborts the currently executing script. 122 | `pcall()` may be used to prevent errors. 123 | 124 | ```lua 125 | local ok, _ = pcall(require, 'module_with_error') 126 | if not ok then 127 | -- not loaded 128 | end 129 | ``` 130 | 131 | See also: 132 | - [`:help lua-require`](https://neovim.io/doc/user/lua.html#lua-require) 133 | 134 | #### Tips 135 | 136 | Several Lua plugins might have identical filenames in their `lua/` folder. This could lead to namespace clashes. 137 | 138 | If two different plugins have a `lua/main.lua` file, then doing `require('main')` is ambiguous: which file do we want to source? 139 | 140 | It might be a good idea to namespace your config or your plugin with a top-level folder, like so: `lua/plugin_name/main.lua` 141 | 142 | ### Runtime files 143 | 144 | Much like Vimscript files, Lua files can be loaded automatically from special folders in your `runtimepath`. Currently, the following folders are supported: 145 | 146 | - `colors/` 147 | - `compiler/` 148 | - `ftplugin/` 149 | - `ftdetect/` 150 | - `indent/` 151 | - `plugin/` 152 | - `syntax/` 153 | 154 | Note: in a runtime directory, all `*.vim` files are sourced before `*.lua` files. 155 | 156 | See also: 157 | - [`:help 'runtimepath'`](https://neovim.io/doc/user/options.html#'runtimepath') 158 | - [`:help load-plugins`](https://neovim.io/doc/user/starting.html#load-plugins) 159 | 160 | #### Tips 161 | 162 | Since runtime files aren't based on the Lua module system, two plugins can have a `plugin/main.lua` file without it being an issue. 163 | 164 | ## Using Lua from Vimscript 165 | 166 | ### :lua 167 | 168 | This command executes a chunk of Lua code. 169 | 170 | ```vim 171 | :lua require('myluamodule') 172 | ``` 173 | 174 | Multi-line scripts are possible using heredoc syntax: 175 | 176 | ```vim 177 | echo "Here's a bigger chunk of Lua code" 178 | 179 | lua << EOF 180 | local mod = require('mymodule') 181 | local tbl = {1, 2, 3} 182 | 183 | for k, v in ipairs(tbl) do 184 | mod.method(v) 185 | end 186 | 187 | print(tbl) 188 | EOF 189 | ``` 190 | 191 | 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: 192 | 193 | ```vim 194 | :lua local foo = 1 195 | :lua print(foo) 196 | " prints 'nil' instead of '1' 197 | ``` 198 | 199 | Note 2: the `print()` function in Lua behaves similarly to the `:echomsg` command. Its output is saved in the message-history and can be suppressed by the `:silent` command. 200 | 201 | See also: 202 | 203 | - [`:help :lua`](https://neovim.io/doc/user/lua.html#Lua) 204 | - [`:help :lua-heredoc`](https://neovim.io/doc/user/lua.html#:lua-heredoc) 205 | 206 | ### :luado 207 | 208 | This command executes a chunk of Lua code that acts on a range of lines in the current buffer. If no range is specified, the whole buffer is used instead. Whatever string is `return`ed from the chunk is used to determine what each line should be replaced with. 209 | 210 | The following command would replace every line in the current buffer with the text `hello world`: 211 | 212 | ```vim 213 | :luado return 'hello world' 214 | ``` 215 | 216 | Two implicit `line` and `linenr` variables are also provided. `line` is the text of the line being iterated upon whereas `linenr` is its number. The following command would make every line whose number is divisible by 2 uppercase: 217 | 218 | ```vim 219 | :luado if linenr % 2 == 0 then return line:upper() end 220 | ``` 221 | 222 | See also: 223 | 224 | - [`:help :luado`](https://neovim.io/doc/user/lua.html#:luado) 225 | 226 | ### Sourcing Lua files 227 | 228 | Neovim provides 3 Ex commands to source Lua files 229 | 230 | - `:luafile` 231 | - `:source` 232 | - `:runtime` 233 | 234 | `:luafile` and `:source` are very similar: 235 | 236 | ```vim 237 | :luafile ~/foo/bar/baz/myluafile.lua 238 | :luafile % 239 | :source ~/foo/bar/baz/myluafile.lua 240 | :source % 241 | ``` 242 | 243 | `:source` also supports ranges, which can be useful to only execute part of a script: 244 | 245 | ```vim 246 | :1,10source 247 | ``` 248 | 249 | `:runtime` is a little different: it uses the `'runtimepath'` option to determine which files to source. See [`:help :runtime`](https://neovim.io/doc/user/repeat.html#:runtime) for more details. 250 | 251 | See also: 252 | 253 | - [`:help :luafile`](https://neovim.io/doc/user/lua.html#:luafile) 254 | - [`:help :source`](https://neovim.io/doc/user/repeat.html#:source) 255 | - [`:help :runtime`](https://neovim.io/doc/user/repeat.html#:runtime) 256 | 257 | #### Sourcing a lua file vs calling require(): 258 | 259 | You might be wondering what the difference between calling the `require()` function and sourcing a Lua file is and whether you should prefer one way over the other. They have different use cases: 260 | 261 | - `require()`: 262 | - is a built-in Lua function. It allows you to take advantage of Lua's module system 263 | - searches for modules in `lua/` folders in your `'runtimepath'` 264 | - keeps track of what modules have been loaded and prevents a script from being parsed and executed a second time. If you change the file containing the code for a module and try to `require()` it a second time while Neovim is running, the module will not actually update 265 | - `:luafile`, `:source` and `:runtime`: 266 | - are Ex commands. They do not support modules 267 | - execute the contents of a script regardless of whether it has been executed before 268 | - `:luafile` and `:source` take a path that is either absolute or relative to the working directory of the current window 269 | - `:runtime` uses the `'runtimepath'` option to find files 270 | 271 | Files sourced via `:source`, `:runtime` or automatically from runtime directories will also show up in `:scriptnames` and `--startuptime` 272 | 273 | ### luaeval() 274 | 275 | This built-in Vimscript function evaluates a Lua expression string and returns its value. Lua data types are automatically converted to Vimscript types (and vice versa). 276 | 277 | ```vim 278 | " You can store the result in a variable 279 | let variable = luaeval('1 + 1') 280 | echo variable 281 | " 2 282 | let concat = luaeval('"Lua".." is ".."awesome"') 283 | echo concat 284 | " 'Lua is awesome' 285 | 286 | " List-like tables are converted to Vim lists 287 | let list = luaeval('{1, 2, 3, 4}') 288 | echo list[0] 289 | " 1 290 | echo list[1] 291 | " 2 292 | " Note that unlike Lua tables, Vim lists are 0-indexed 293 | 294 | " Dict-like tables are converted to Vim dictionaries 295 | let dict = luaeval('{foo = "bar", baz = "qux"}') 296 | echo dict.foo 297 | " 'bar' 298 | 299 | " Same thing for booleans and nil 300 | echo luaeval('true') 301 | " v:true 302 | echo luaeval('nil') 303 | " v:null 304 | 305 | " You can create Vimscript aliases for Lua functions 306 | let LuaMathPow = luaeval('math.pow') 307 | echo LuaMathPow(2, 2) 308 | " 4 309 | let LuaModuleFunction = luaeval('require("mymodule").myfunction') 310 | call LuaModuleFunction() 311 | 312 | " It is also possible to pass Lua functions as values to Vim functions 313 | lua X = function(k, v) return string.format("%s:%s", k, v) end 314 | echo map([1, 2, 3], luaeval("X")) 315 | ``` 316 | 317 | `luaeval()` takes an optional second argument that allows you to pass data to the expression. You can then access that data from Lua using the magic global `_A`: 318 | 319 | ```vim 320 | echo luaeval('_A[1] + _A[2]', [1, 1]) 321 | " 2 322 | 323 | echo luaeval('string.format("Lua is %s", _A)', 'awesome') 324 | " 'Lua is awesome' 325 | ``` 326 | 327 | See also: 328 | - [`:help luaeval()`](https://neovim.io/doc/user/lua.html#luaeval()) 329 | 330 | ### v:lua 331 | 332 | This global Vim variable allows you to call Lua functions in the global namespace ([`_G`](https://www.lua.org/manual/5.1/manual.html#pdf-_G)) directly from Vimscript. Again, Vim data types are converted to Lua types and vice versa. 333 | 334 | ```vim 335 | call v:lua.print('Hello from Lua!') 336 | " 'Hello from Lua!' 337 | 338 | let scream = v:lua.string.rep('A', 10) 339 | echo scream 340 | " 'AAAAAAAAAA' 341 | 342 | " How about a nice statusline? 343 | lua << EOF 344 | function _G.statusline() 345 | local filepath = '%f' 346 | local align_section = '%=' 347 | local percentage_through_file = '%p%%' 348 | return string.format( 349 | '%s%s%s', 350 | filepath, 351 | align_section, 352 | percentage_through_file 353 | ) 354 | end 355 | EOF 356 | 357 | set statusline=%!v:lua.statusline() 358 | 359 | " Also works in expression mappings 360 | lua << EOF 361 | function _G.check_back_space() 362 | local col = vim.api.nvim_win_get_cursor(0)[2] 363 | return (col == 0 or vim.api.nvim_get_current_line():sub(col, col):match('%s')) and true 364 | end 365 | EOF 366 | 367 | inoremap 368 | \ pumvisible() ? "\" : 369 | \ v:lua.check_back_space() ? "\" : 370 | \ completion#trigger_completion() 371 | 372 | " Call a function from a Lua module by using single quotes and omitting parentheses: 373 | call v:lua.require'module'.foo() 374 | ``` 375 | 376 | See also: 377 | - [`:help v:lua`](https://neovim.io/doc/user/eval.html#v:lua) 378 | - [`:help v:lua-call`](https://neovim.io/doc/user/lua.html#v:lua-call) 379 | 380 | #### Caveats 381 | 382 | This variable can only be used to call functions. The following will always throw an error: 383 | 384 | ```vim 385 | " Aliasing functions doesn't work 386 | let LuaPrint = v:lua.print 387 | 388 | " Accessing dictionaries doesn't work 389 | echo v:lua.some_global_dict['key'] 390 | 391 | " Using a function as a value doesn't work 392 | echo map([1, 2, 3], v:lua.global_callback) 393 | ``` 394 | 395 | ### Tips 396 | 397 | You can get Lua syntax highlighting inside .vim files by putting `let g:vimsyn_embed = 'l'` in your configuration file. See [`:help g:vimsyn_embed`](https://neovim.io/doc/user/syntax.html#g:vimsyn_embed) for more on this option. 398 | 399 | ## The vim namespace 400 | 401 | Neovim exposes a global `vim` variable which serves as an entry point to interact with its APIs from Lua. It provides users with an extended "standard library" of functions as well as various sub-modules. 402 | 403 | Some notable functions and modules include: 404 | 405 | - `vim.inspect`: transform Lua objects into human-readable strings (useful for inspecting tables) 406 | - `vim.regex`: use Vim regexes from Lua 407 | - `vim.api`: module that exposes API functions (the same API used by remote plugins) 408 | - `vim.ui`: overridable UI functions that can be leveraged by plugins 409 | - `vim.loop`: module that exposes the functionality of Neovim's event-loop (using LibUV) 410 | - `vim.lsp`: module that controls the built-in LSP client 411 | - `vim.treesitter`: module that exposes the functionality of the tree-sitter library 412 | 413 | This list is by no means comprehensive. If you wish to know more about what's made available by the `vim` variable, [`:help lua-stdlib`](https://neovim.io/doc/user/lua.html#lua-stdlib) and [`:help lua-vim`](https://neovim.io/doc/user/lua.html#lua-vim) are the way to go. Alternatively, you can do `:lua print(vim.inspect(vim))` to get a list of every module. API functions are documented under [`:help api-global`](https://neovim.io/doc/user/api.html#api-global). 414 | 415 | #### Tips 416 | 417 | Writing `print(vim.inspect(x))` every time you want to inspect the contents of an object can get pretty tedious. It might be worthwhile to have a global wrapper function somewhere in your configuration (in Neovim 0.7.0+, this function is built-in, see [`:help vim.pretty_print()`](https://neovim.io/doc/user/lua.html#vim.pretty_print())): 418 | 419 | ```lua 420 | function _G.put(...) 421 | local objects = {} 422 | for i = 1, select('#', ...) do 423 | local v = select(i, ...) 424 | table.insert(objects, vim.inspect(v)) 425 | end 426 | 427 | print(table.concat(objects, '\n')) 428 | return ... 429 | end 430 | ``` 431 | 432 | You can then inspect the contents of an object very quickly in your code or from the command-line: 433 | 434 | ```lua 435 | put({1, 2, 3}) 436 | ``` 437 | 438 | ```vim 439 | :lua put(vim.loop) 440 | ``` 441 | 442 | Alternatively, you can use the `:lua` command to pretty-print a Lua expression by prefixing it with `=` (Neovim 0.7+ only): 443 | ```vim 444 | :lua =vim.loop 445 | ``` 446 | 447 | Additionally, you may find that built-in Lua functions are sometimes lacking compared to what you would find in other languages (for example `os.clock()` only returns a value in seconds, not milliseconds). Be sure to look at the Neovim stdlib (and `vim.fn`, more on that later), it probably has what you're looking for. 448 | 449 | ## Using Vimscript from Lua 450 | 451 | ### vim.api.nvim_eval() 452 | 453 | This function evaluates a Vimscript expression string and returns its value. Vimscript data types are automatically converted to Lua types (and vice versa). 454 | 455 | It is the Lua equivalent of the `luaeval()` function in Vimscript 456 | 457 | ```lua 458 | -- Data types are converted correctly 459 | print(vim.api.nvim_eval('1 + 1')) -- 2 460 | print(vim.inspect(vim.api.nvim_eval('[1, 2, 3]'))) -- { 1, 2, 3 } 461 | print(vim.inspect(vim.api.nvim_eval('{"foo": "bar", "baz": "qux"}'))) -- { baz = "qux", foo = "bar" } 462 | print(vim.api.nvim_eval('v:true')) -- true 463 | print(vim.api.nvim_eval('v:null')) -- nil 464 | ``` 465 | 466 | #### Caveats 467 | 468 | Unlike `luaeval()`, `vim.api.nvim_eval()` does not provide an implicit `_A` variable to pass data to the expression. 469 | 470 | ### vim.api.nvim_exec() 471 | 472 | This function evaluates a chunk of Vimscript code. It takes in a string containing the source code to execute and a boolean to determine whether the output of the code should be returned by the function (you can then store the output in a variable, for example). 473 | 474 | ```lua 475 | local result = vim.api.nvim_exec( 476 | [[ 477 | let s:mytext = 'hello world' 478 | 479 | function! s:MyFunction(text) 480 | echo a:text 481 | endfunction 482 | 483 | call s:MyFunction(s:mytext) 484 | ]], 485 | true) 486 | 487 | print(result) -- 'hello world' 488 | ``` 489 | 490 | #### Caveats 491 | 492 | `nvim_exec` does not support script-local variables (`s:`) prior to Neovim 0.6.0 493 | 494 | ### vim.api.nvim_command() 495 | 496 | This function executes an ex command. It takes in a string containing the command to execute. 497 | 498 | ```lua 499 | vim.api.nvim_command('new') 500 | vim.api.nvim_command('wincmd H') 501 | vim.api.nvim_command('set nonumber') 502 | vim.api.nvim_command('%s/foo/bar/g') 503 | ``` 504 | 505 | ### vim.cmd() 506 | 507 | Alias for `vim.api.nvim_exec()`. Only the command argument is needed, `output` is always set to `false`. 508 | 509 | ```lua 510 | vim.cmd('buffers') 511 | vim.cmd([[ 512 | let g:multiline_list = [ 513 | \ 1, 514 | \ 2, 515 | \ 3, 516 | \ ] 517 | 518 | echo g:multiline_list 519 | ]]) 520 | ``` 521 | 522 | #### Tips 523 | 524 | Since you have to pass strings to these functions, you often end up having to escape backslashes: 525 | 526 | ```lua 527 | vim.cmd('%s/\\Vfoo/bar/g') 528 | ``` 529 | 530 | Double bracketed strings are easier to use as they do not require escaping characters: 531 | 532 | ```lua 533 | vim.cmd([[%s/\Vfoo/bar/g]]) 534 | ``` 535 | 536 | ### vim.api.nvim_replace_termcodes() 537 | 538 | This API function allows you to escape terminal codes and Vim keycodes. 539 | 540 | You may have come across mappings like this one: 541 | 542 | ```vim 543 | inoremap pumvisible() ? "\" : "\" 544 | ``` 545 | 546 | Trying to do the same in Lua can prove to be a challenge. You might be tempted to do it like this: 547 | 548 | ```lua 549 | function _G.smart_tab() 550 | return vim.fn.pumvisible() == 1 and [[\]] or [[\]] 551 | end 552 | 553 | vim.api.nvim_set_keymap('i', '', 'v:lua.smart_tab()', {expr = true, noremap = true}) 554 | ``` 555 | 556 | only to find out that the mapping inserts `\` and `\` literally... 557 | 558 | Being able to escape keycodes is actually a Vimscript feature. Aside from the usual escape sequences like `\r`, `\42` or `\x10` that are common to many programming languages, Vimscript `expr-quotes` (strings surrounded with double quotes) allow you to escape the human-readable representation of Vim keycodes. 559 | 560 | Lua doesn't have such a feature built-in. Fortunately, Neovim has an API function for escaping terminal codes and keycodes: `nvim_replace_termcodes()` 561 | 562 | ```lua 563 | print(vim.api.nvim_replace_termcodes('', true, true, true)) 564 | ``` 565 | 566 | This is a little verbose. Making a reusable wrapper can help: 567 | 568 | ```lua 569 | -- The function is called `t` for `termcodes`. 570 | -- You don't have to call it that, but I find the terseness convenient 571 | local function t(str) 572 | -- Adjust boolean arguments as needed 573 | return vim.api.nvim_replace_termcodes(str, true, true, true) 574 | end 575 | 576 | print(t'') 577 | ``` 578 | 579 | Coming back to our earlier example, this should now work as expected: 580 | 581 | ```lua 582 | local function t(str) 583 | return vim.api.nvim_replace_termcodes(str, true, true, true) 584 | end 585 | 586 | function _G.smart_tab() 587 | return vim.fn.pumvisible() == 1 and t'' or t'' 588 | end 589 | 590 | vim.api.nvim_set_keymap('i', '', 'v:lua.smart_tab()', {expr = true, noremap = true}) 591 | ``` 592 | 593 | This is not necessary with `vim.keymap.set()` as it automatically transforms vim keycodes returned by Lua functions in `expr` mappings by default: 594 | 595 | ```lua 596 | vim.keymap.set('i', '', function() 597 | return vim.fn.pumvisible() == 1 and '' or '' 598 | end, {expr = true}) 599 | ``` 600 | 601 | See also: 602 | 603 | - [`:help keycodes`](https://neovim.io/doc/user/intro.html#keycodes) 604 | - [`:help expr-quote`](https://neovim.io/doc/user/eval.html#expr-quote) 605 | - [`:help nvim_replace_termcodes()`](https://neovim.io/doc/user/api.html#nvim_replace_termcodes()) 606 | 607 | ## Managing vim options 608 | 609 | ### Using api functions 610 | 611 | Neovim provides a set of API functions to either set an option or get its current value: 612 | 613 | - Global options: 614 | - [`vim.api.nvim_set_option()`](https://neovim.io/doc/user/api.html#nvim_set_option()) 615 | - [`vim.api.nvim_get_option()`](https://neovim.io/doc/user/api.html#nvim_get_option()) 616 | - Buffer-local options: 617 | - [`vim.api.nvim_buf_set_option()`](https://neovim.io/doc/user/api.html#nvim_buf_set_option()) 618 | - [`vim.api.nvim_buf_get_option()`](https://neovim.io/doc/user/api.html#nvim_buf_get_option()) 619 | - Window-local options: 620 | - [`vim.api.nvim_win_set_option()`](https://neovim.io/doc/user/api.html#nvim_win_set_option()) 621 | - [`vim.api.nvim_win_get_option()`](https://neovim.io/doc/user/api.html#nvim_win_get_option()) 622 | 623 | They take a string containing the name of the option to set/get as well as the value you want to set it to. 624 | 625 | Boolean options (like `(no)number`) have to be set to either `true` or `false`: 626 | 627 | ```lua 628 | vim.api.nvim_set_option('smarttab', false) 629 | print(vim.api.nvim_get_option('smarttab')) -- false 630 | ``` 631 | 632 | Unsurprisingly, string options have to be set to a string: 633 | 634 | ```lua 635 | vim.api.nvim_set_option('selection', 'exclusive') 636 | print(vim.api.nvim_get_option('selection')) -- 'exclusive' 637 | ``` 638 | 639 | Number options accept a number: 640 | 641 | ```lua 642 | vim.api.nvim_set_option('updatetime', 3000) 643 | print(vim.api.nvim_get_option('updatetime')) -- 3000 644 | ``` 645 | 646 | Buffer-local and window-local options also need a buffer number or a window number (using `0` will set/get the option for the current buffer/window): 647 | 648 | ```lua 649 | vim.api.nvim_win_set_option(0, 'number', true) 650 | vim.api.nvim_buf_set_option(10, 'shiftwidth', 4) 651 | print(vim.api.nvim_win_get_option(0, 'number')) -- true 652 | print(vim.api.nvim_buf_get_option(10, 'shiftwidth')) -- 4 653 | ``` 654 | 655 | ### Using meta-accessors 656 | 657 | A few meta-accessors are available if you want to set options in a more "idiomatic" way. They essentially wrap the above API functions and allow you to manipulate options as if they were variables: 658 | 659 | - [`vim.o`](https://neovim.io/doc/user/lua.html#vim.o): behaves like `:let &{option-name}` 660 | - [`vim.go`](https://neovim.io/doc/user/lua.html#vim.go): behaves like `:let &g:{option-name}` 661 | - [`vim.bo`](https://neovim.io/doc/user/lua.html#vim.bo): behaves like `:let &l:{option-name}` for buffer-local options 662 | - [`vim.wo`](https://neovim.io/doc/user/lua.html#vim.wo): behaves like `:let &l:{option-name}` for window-local options 663 | 664 | ```lua 665 | vim.o.smarttab = false -- let &smarttab = v:false 666 | print(vim.o.smarttab) -- false 667 | vim.o.isfname = vim.o.isfname .. ',@-@' -- on Linux: let &isfname = &isfname .. ',@-@' 668 | print(vim.o.isfname) -- '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@' 669 | 670 | vim.bo.shiftwidth = 4 671 | print(vim.bo.shiftwidth) -- 4 672 | ``` 673 | 674 | You can specify a number for buffer-local and window-local options. If no number is given, the current buffer/window is used: 675 | 676 | ```lua 677 | vim.bo[4].expandtab = true -- same as vim.api.nvim_buf_set_option(4, 'expandtab', true) 678 | vim.wo.number = true -- same as vim.api.nvim_win_set_option(0, 'number', true) 679 | ``` 680 | 681 | These wrappers also have more sophisticated `vim.opt*` variants that provide convenient mechanisms for setting options in Lua. They're similar to what you might be used to in your `init.vim`: 682 | 683 | - `vim.opt`: behaves like `:set` 684 | - `vim.opt_global`: behaves like `:setglobal` 685 | - `vim.opt_local`: behaves like `:setlocal` 686 | 687 | ```lua 688 | vim.opt.smarttab = false 689 | print(vim.opt.smarttab:get()) -- false 690 | ``` 691 | 692 | Some options can be set using Lua tables: 693 | 694 | ```lua 695 | vim.opt.completeopt = {'menuone', 'noselect'} 696 | print(vim.inspect(vim.opt.completeopt:get())) -- { "menuone", "noselect" } 697 | ``` 698 | 699 | Wrappers for list-like, map-like and set-like options also come with methods and metamethods that work similarly to their `:set+=`, `:set^=` and `:set-=` counterparts in Vimscript. 700 | 701 | ```lua 702 | vim.opt.shortmess:append({ I = true }) 703 | -- alternative form: 704 | vim.opt.shortmess = vim.opt.shortmess + { I = true } 705 | 706 | vim.opt.whichwrap:remove({ 'b', 's' }) 707 | -- alternative form: 708 | vim.opt.whichwrap = vim.opt.whichwrap - { 'b', 's' } 709 | ``` 710 | 711 | Be sure to look at [`:help vim.opt`](https://neovim.io/doc/user/lua.html#vim.opt) for more information. 712 | 713 | See also: 714 | - [`:help lua-vim-options`](https://neovim.io/doc/user/lua.html#lua-vim-options) 715 | 716 | ## Managing vim internal variables 717 | 718 | ### Using api functions 719 | 720 | Much like options, internal variables have their own set of API functions: 721 | 722 | - Global variables (`g:`): 723 | - [`vim.api.nvim_set_var()`](https://neovim.io/doc/user/api.html#nvim_set_var()) 724 | - [`vim.api.nvim_get_var()`](https://neovim.io/doc/user/api.html#nvim_get_var()) 725 | - [`vim.api.nvim_del_var()`](https://neovim.io/doc/user/api.html#nvim_del_var()) 726 | - Buffer variables (`b:`): 727 | - [`vim.api.nvim_buf_set_var()`](https://neovim.io/doc/user/api.html#nvim_buf_set_var()) 728 | - [`vim.api.nvim_buf_get_var()`](https://neovim.io/doc/user/api.html#nvim_buf_get_var()) 729 | - [`vim.api.nvim_buf_del_var()`](https://neovim.io/doc/user/api.html#nvim_buf_del_var()) 730 | - Window variables (`w:`): 731 | - [`vim.api.nvim_win_set_var()`](https://neovim.io/doc/user/api.html#nvim_win_set_var()) 732 | - [`vim.api.nvim_win_get_var()`](https://neovim.io/doc/user/api.html#nvim_win_get_var()) 733 | - [`vim.api.nvim_win_del_var()`](https://neovim.io/doc/user/api.html#nvim_win_del_var()) 734 | - Tabpage variables (`t:`): 735 | - [`vim.api.nvim_tabpage_set_var()`](https://neovim.io/doc/user/api.html#nvim_tabpage_set_var()) 736 | - [`vim.api.nvim_tabpage_get_var()`](https://neovim.io/doc/user/api.html#nvim_tabpage_get_var()) 737 | - [`vim.api.nvim_tabpage_del_var()`](https://neovim.io/doc/user/api.html#nvim_tabpage_del_var()) 738 | - Predefined Vim variables (`v:`): 739 | - [`vim.api.nvim_set_vvar()`](https://neovim.io/doc/user/api.html#nvim_set_vvar()) 740 | - [`vim.api.nvim_get_vvar()`](https://neovim.io/doc/user/api.html#nvim_get_vvar()) 741 | 742 | With the exception of predefined Vim variables, they can also be deleted (the `:unlet` command is the equivalent in Vimscript). Local variables (`l:`), script variables (`s:`) and function arguments (`a:`) cannot be manipulated as they only make sense in the context of a Vim script, Lua has its own scoping rules. 743 | 744 | If you are unfamiliar with what these variables do, [`:help internal-variables`](https://neovim.io/doc/user/eval.html#internal-variables) describes them in detail. 745 | 746 | These functions take a string containing the name of the variable to set/get/delete as well as the value you want to set it to. 747 | 748 | ```lua 749 | vim.api.nvim_set_var('some_global_variable', { key1 = 'value', key2 = 300 }) 750 | print(vim.inspect(vim.api.nvim_get_var('some_global_variable'))) -- { key1 = "value", key2 = 300 } 751 | vim.api.nvim_del_var('some_global_variable') 752 | ``` 753 | 754 | Variables that are scoped to a buffer, a window or a tabpage also receive a number (using `0` will set/get/delete the variable for the current buffer/window/tabpage): 755 | 756 | ```lua 757 | vim.api.nvim_win_set_var(0, 'some_window_variable', 2500) 758 | vim.api.nvim_tab_set_var(3, 'some_tabpage_variable', 'hello world') 759 | print(vim.api.nvim_win_get_var(0, 'some_window_variable')) -- 2500 760 | print(vim.api.nvim_buf_get_var(3, 'some_tabpage_variable')) -- 'hello world' 761 | vim.api.nvim_win_del_var(0, 'some_window_variable') 762 | vim.api.nvim_buf_del_var(3, 'some_tabpage_variable') 763 | ``` 764 | 765 | ### Using meta-accessors 766 | 767 | Internal variables can be manipulated more intuitively using these meta-accessors: 768 | 769 | - [`vim.g`](https://neovim.io/doc/user/lua.html#vim.g): global variables 770 | - [`vim.b`](https://neovim.io/doc/user/lua.html#vim.b): buffer variables 771 | - [`vim.w`](https://neovim.io/doc/user/lua.html#vim.w): window variables 772 | - [`vim.t`](https://neovim.io/doc/user/lua.html#vim.t): tabpage variables 773 | - [`vim.v`](https://neovim.io/doc/user/lua.html#vim.v): predefined Vim variables 774 | - [`vim.env`](https://neovim.io/doc/user/lua.html#vim.env): environment variables 775 | 776 | ```lua 777 | vim.g.some_global_variable = { 778 | key1 = 'value', 779 | key2 = 300 780 | } 781 | 782 | print(vim.inspect(vim.g.some_global_variable)) -- { key1 = "value", key2 = 300 } 783 | 784 | -- target a specific buffer/window/tabpage (Neovim 0.6+) 785 | vim.b[2].myvar = 1 786 | ``` 787 | 788 | Some variable names may contain characters that cannot be used for identifiers in Lua. You can still manipulate these variables by using this syntax: `vim.g['my#variable']`. 789 | 790 | To delete one of these variables, simply assign `nil` to it: 791 | 792 | ```lua 793 | vim.g.some_global_variable = nil 794 | ``` 795 | 796 | See also: 797 | - [`:help lua-vim-variables`](https://neovim.io/doc/user/lua.html#lua-vim-variables) 798 | 799 | #### Caveats 800 | 801 | You cannot add/update/delete keys from a dictionary stored in one of these variables. For example, this snippet of Vimscript code does not work as expected: 802 | 803 | ```vim 804 | let g:variable = {} 805 | lua vim.g.variable.key = 'a' 806 | echo g:variable 807 | " {} 808 | ``` 809 | 810 | You can use a temporary variable as a workaround: 811 | 812 | ```vim 813 | let g:variable = {} 814 | lua << EOF 815 | local tmp = vim.g.variable 816 | tmp.key = 'a' 817 | vim.g.variable = tmp 818 | EOF 819 | echo g:variable 820 | " {'key': 'a'} 821 | ``` 822 | 823 | This is a known issue: 824 | 825 | - [Issue #12544](https://github.com/neovim/neovim/issues/12544) 826 | 827 | ## Calling Vimscript functions 828 | 829 | ### vim.fn.{function}() 830 | 831 | `vim.fn` can be used to call a Vimscript function. Data types are converted back and forth from Lua to Vimscript. 832 | 833 | ```lua 834 | print(vim.fn.printf('Hello from %s', 'Lua')) 835 | 836 | local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' }) 837 | print(vim.inspect(reversed_list)) -- { "c", "b", "a" } 838 | 839 | local function print_stdout(chan_id, data, name) 840 | print(data[1]) 841 | end 842 | 843 | vim.fn.jobstart('ls', { on_stdout = print_stdout }) 844 | ``` 845 | 846 | Hashes (`#`) are not valid characters for identifiers in Lua, so autoload functions have to be called with this syntax: 847 | 848 | ```lua 849 | vim.fn['my#autoload#function']() 850 | ``` 851 | 852 | The functionality of `vim.fn` is identical to `vim.call`, but allows a more Lua-like syntax. 853 | 854 | It is distinct from `vim.api.nvim_call_function` in that converting Vim/Lua objects is automatic: `vim.api.nvim_call_function` returns a table for floating point numbers and does not accept Lua closures while `vim.fn` handles these types transparently. 855 | 856 | See also: 857 | - [`:help vim.fn`](https://neovim.io/doc/user/lua.html#vim.fn) 858 | 859 | #### Tips 860 | 861 | Neovim has an extensive library of powerful built-in functions that are very useful for plugins. See [`:help vim-function`](https://neovim.io/doc/user/eval.html#vim-function) for an alphabetical list and [`:help function-list`](https://neovim.io/doc/user/usr_41.html#function-list) for a list of functions grouped by topic. 862 | 863 | Neovim API functions can be used directly through `vim.api.{..}`. See [`:help api`](https://neovim.io/doc/user/api.html#API) for information. 864 | 865 | #### Caveats 866 | 867 | Some Vim functions that should return a boolean return `1` or `0` instead. This isn't a problem in Vimscript as `1` is truthy and `0` falsy, enabling constructs like these: 868 | 869 | ```vim 870 | if has('nvim') 871 | " do something... 872 | endif 873 | ``` 874 | 875 | In Lua however, only `false` and `nil` are considered falsy, numbers always evaluate to `true` no matter their value. You have to explicitly check for `1` or `0`: 876 | 877 | ```lua 878 | if vim.fn.has('nvim') == 1 then 879 | -- do something... 880 | end 881 | ``` 882 | 883 | ## Defining mappings 884 | 885 | ### API functions 886 | 887 | Neovim provides a list of API functions to set, get and delete mappings: 888 | 889 | - Global mappings: 890 | - [`vim.api.nvim_set_keymap()`](https://neovim.io/doc/user/api.html#nvim_set_keymap()) 891 | - [`vim.api.nvim_get_keymap()`](https://neovim.io/doc/user/api.html#nvim_get_keymap()) 892 | - [`vim.api.nvim_del_keymap()`](https://neovim.io/doc/user/api.html#nvim_del_keymap()) 893 | - Buffer-local mappings: 894 | - [`vim.api.nvim_buf_set_keymap()`](https://neovim.io/doc/user/api.html#nvim_buf_set_keymap()) 895 | - [`vim.api.nvim_buf_get_keymap()`](https://neovim.io/doc/user/api.html#nvim_buf_get_keymap()) 896 | - [`vim.api.nvim_buf_del_keymap()`](https://neovim.io/doc/user/api.html#nvim_buf_del_keymap()) 897 | 898 | Let's start with `vim.api.nvim_set_keymap()` and `vim.api.nvim_buf_set_keymap()` 899 | 900 | The first argument passed to the function is a string containing the name of the mode for which the mapping will take effect: 901 | 902 | | String value | Help page | Affected modes | Vimscript equivalent | 903 | | ---------------------- | ------------- | ---------------------------------------- | -------------------- | 904 | | `''` (an empty string) | `mapmode-nvo` | Normal, Visual, Select, Operator-pending | `:map` | 905 | | `'n'` | `mapmode-n` | Normal | `:nmap` | 906 | | `'v'` | `mapmode-v` | Visual and Select | `:vmap` | 907 | | `'s'` | `mapmode-s` | Select | `:smap` | 908 | | `'x'` | `mapmode-x` | Visual | `:xmap` | 909 | | `'o'` | `mapmode-o` | Operator-pending | `:omap` | 910 | | `'!'` | `mapmode-ic` | Insert and Command-line | `:map!` | 911 | | `'i'` | `mapmode-i` | Insert | `:imap` | 912 | | `'l'` | `mapmode-l` | Insert, Command-line, Lang-Arg | `:lmap` | 913 | | `'c'` | `mapmode-c` | Command-line | `:cmap` | 914 | | `'t'` | `mapmode-t` | Terminal | `:tmap` | 915 | 916 | The second argument is a string containing the left-hand side of the mapping (the key or set of keys that trigger the command defined in the mapping). An empty string is equivalent to ``, which disables a key. 917 | 918 | The third argument is a string containing the right-hand side of the mapping (the command to execute). 919 | 920 | The final argument is a table containing boolean options for the mapping as defined in [`:help :map-arguments`](https://neovim.io/doc/user/map.html#:map-arguments) (including `noremap` and excluding `buffer`). Since Neovim 0.7.0, you can also pass a `callback` option to invoke a Lua function instead of the right-hand side when executing the mapping. 921 | 922 | Buffer-local mappings also take a buffer number as their first argument (`0` sets the mapping for the current buffer). 923 | 924 | ```lua 925 | vim.api.nvim_set_keymap('n', '', ':set hlsearch!', { noremap = true, silent = true }) 926 | -- :nnoremap :set hlsearch 927 | vim.api.nvim_set_keymap('n', 'tegf', [[lua require('telescope.builtin').git_files()]], { noremap = true, silent = true }) 928 | -- :nnoremap tegf lua require('telescope.builtin').git_files() 929 | 930 | vim.api.nvim_buf_set_keymap(0, '', 'cc', 'line(".") == 1 ? "cc" : "ggcc"', { noremap = true, expr = true }) 931 | -- :noremap cc line('.') == 1 ? 'cc' : 'ggcc' 932 | 933 | vim.api.nvim_set_keymap('n', 'ex', '', { 934 | noremap = true, 935 | callback = function() 936 | print('My example') 937 | end, 938 | -- Since Lua function don't have a useful string representation, you can use the "desc" option to document your mapping 939 | desc = 'Prints "My example" in the message area', 940 | }) 941 | ``` 942 | 943 | `vim.api.nvim_get_keymap()` takes a string containing the shortname of the mode for which you want the list of mappings (see table above). The return value is a table containing all global mappings for the mode. 944 | 945 | ```lua 946 | print(vim.inspect(vim.api.nvim_get_keymap('n'))) 947 | -- :verbose nmap 948 | ``` 949 | 950 | `vim.api.nvim_buf_get_keymap()` takes an additional buffer number as its first argument (`0` will get mapppings for the current bufffer) 951 | 952 | ```lua 953 | print(vim.inspect(vim.api.nvim_buf_get_keymap(0, 'i'))) 954 | -- :verbose imap 955 | ``` 956 | 957 | `vim.api.nvim_del_keymap()` takes a mode and the left-hand side of a mapping. 958 | 959 | ```lua 960 | vim.api.nvim_del_keymap('n', '') 961 | -- :nunmap 962 | ``` 963 | 964 | Again, `vim.api.nvim_buf_del_keymap()`, takes a buffer number as its first argument, with `0` representing the current buffer. 965 | 966 | ```lua 967 | vim.api.nvim_buf_del_keymap(0, 'i', '') 968 | -- :iunmap 969 | ``` 970 | 971 | ### vim.keymap 972 | 973 | :warning: The functions discussed in this section are only available in Neovim 0.7.0+ 974 | 975 | Neovim provides two functions to set/del mappings: 976 | - [`vim.keymap.set()`](https://neovim.io/doc/user/lua.html#vim.keymap.set()) 977 | - [`vim.keymap.del()`](https://neovim.io/doc/user/lua.html#vim.keymap.del()) 978 | 979 | These are similar to the above API functions with added syntactic sugar. 980 | 981 | `vim.keymap.set()` takes a string as its first argument. It can also be a table of strings to define mappings for multiple modes at once: 982 | 983 | ```lua 984 | vim.keymap.set('n', 'ex1', 'lua vim.notify("Example 1")') 985 | vim.keymap.set({'n', 'c'}, 'ex2', 'lua vim.notify("Example 2")') 986 | ``` 987 | 988 | The second argument is the left-hand side of the mapping. 989 | 990 | The third argument is the right-hand side of the mapping, which can either be a string or a Lua function: 991 | 992 | ```lua 993 | vim.keymap.set('n', 'ex1', 'echomsg "Example 1"') 994 | vim.keymap.set('n', 'ex2', function() print("Example 2") end) 995 | vim.keymap.set('n', 'pl1', require('plugin').plugin_action) 996 | -- To avoid the startup cost of requiring the module, you can wrap it in a function to require it lazily when invoking the mapping: 997 | vim.keymap.set('n', 'pl2', function() require('plugin').plugin_action() end) 998 | ``` 999 | 1000 | The fourth (optional) argument is a table of options that correspond to the options passed to `vim.api.nvim_set_keymap()`, with a few additions (see [`:help vim.keymap.set()`](https://neovim.io/doc/user/lua.html#vim.keymap.set()) for the full list). 1001 | 1002 | ```lua 1003 | vim.keymap.set('n', 'ex1', 'echomsg "Example 1"', {buffer = true}) 1004 | vim.keymap.set('n', 'ex2', function() print('Example 2') end, {desc = 'Prints "Example 2" to the message area'}) 1005 | ``` 1006 | 1007 | Defining keymaps with a Lua function is different from using a string. The usual way to show information about a keymap like `:nmap ex1` will not output useful information (the string itself), but instead only show `Lua function`. It is recommended to add a `desc` key to describe the behavior of your keymap. This is especially important for documenting plugin mappings so users can understand the usage of the keymap more easily. 1008 | 1009 | An interesting feature of this API is that it irons out some historical quirks of Vim mappings: 1010 | - Mappings are `noremap` by default, except when the `rhs` is a `` mapping. This means you rarely have to think about whether a mapping should be recursive or not: 1011 | ```lua 1012 | vim.keymap.set('n', 'test1', 'echo "test"') 1013 | -- :nnoremap test echo "test" 1014 | 1015 | -- If you DO want the mapping to be recursive, set the "remap" option to "true" 1016 | vim.keymap.set('n', '>', ']', {remap = true}) 1017 | -- :nmap > ] 1018 | 1019 | -- mappings don't work unless they're recursive, vim.keymap.set() handles that for you automatically 1020 | vim.keymap.set('n', 'plug', '(plugin)') 1021 | -- :nmap plug (plugin) 1022 | ``` 1023 | - In `expr` mappings, `nvim_replace_termcodes()` is automatically applied to strings returned from Lua functions: 1024 | ```lua 1025 | vim.keymap.set('i', '', function() 1026 | return vim.fn.pumvisible == 1 and '' or '' 1027 | end, {expr = true}) 1028 | ``` 1029 | 1030 | See also: 1031 | - [`:help recursive_mapping`](https://neovim.io/doc/user/map.html#recursive_mapping) 1032 | 1033 | `vim.keymap.del()` works the same way but deletes mappings instead: 1034 | 1035 | ```lua 1036 | vim.keymap.del('n', 'ex1') 1037 | vim.keymap.del({'n', 'c'}, 'ex2', {buffer = true}) 1038 | ``` 1039 | 1040 | ## Defining user commands 1041 | 1042 | :warning: The API functions discussed in this section are only available in Neovim 0.7.0+ 1043 | 1044 | Neovim provides API functions for user-defined commands: 1045 | 1046 | - Global user commands: 1047 | - [`vim.api.nvim_create_user_command()`](https://neovim.io/doc/user/api.html#nvim_create_user_command()) 1048 | - [`vim.api.nvim_del_user_command()`](https://neovim.io/doc/user/api.html#nvim_del_user_command()) 1049 | - Buffer-local user commands: 1050 | - [`vim.api.nvim_buf_create_user_command()`](https://neovim.io/doc/user/api.html#nvim_buf_create_user_command()) 1051 | - [`vim.api.nvim_buf_del_user_command()`](https://neovim.io/doc/user/api.html#nvim_buf_del_user_command()) 1052 | 1053 | Let's start with `vim.api.nvim_create_user_command()` 1054 | 1055 | The first argument passed to this function is the name of the command (which must start with an uppercase letter). 1056 | 1057 | The second argument is the code to execute when invoking said command. It can either be: 1058 | 1059 | A string (in which case it will be executed as Vimscript). You can use escape sequences like ``, ``, etc. like you would with `:command` 1060 | ```lua 1061 | vim.api.nvim_create_user_command('Upper', 'echo toupper()', { nargs = 1 }) 1062 | -- :command! -nargs=1 Upper echo toupper() 1063 | 1064 | vim.cmd('Upper hello world') -- prints "HELLO WORLD" 1065 | ``` 1066 | 1067 | Or a Lua function. It receives a dictionary-like table that contains the data normally provided by escape sequences (see [`:help nvim_create_user_command()`](https://neovim.io/doc/user/api.html#nvim_create_user_command()) for a list of available keys) 1068 | ```lua 1069 | vim.api.nvim_create_user_command( 1070 | 'Upper', 1071 | function(opts) 1072 | print(string.upper(opts.args)) 1073 | end, 1074 | { nargs = 1 } 1075 | ) 1076 | ``` 1077 | 1078 | The third argument lets you pass command attributes as a table (see [`:help command-attributes`](https://neovim.io/doc/user/map.html#command-attributes)). Since you can already define buffer-local user commands with `vim.api.nvim_buf_create_user_command()`, `-buffer` is not a valid attribute. 1079 | 1080 | Two additional attributes are available: 1081 | - `desc` allows you to control what gets displayed when you run `:command {cmd}` on a command defined as a Lua callback. Similarly to keymaps, it is recommended to add a `desc` key to commands defined as Lua functions. 1082 | - `force` is equivalent to calling `:command!` and replaces a command if one with the same name already exists. It is true by default, unlike its Vimscript equivalent. 1083 | 1084 | The `-complete` attribute can take a Lua function in addition to the attributes listed in [`:help :command-complete`](https://neovim.io/doc/user/map.html#:command-complete). 1085 | 1086 | ```lua 1087 | vim.api.nvim_create_user_command('Upper', function() end, { 1088 | nargs = 1, 1089 | complete = function(ArgLead, CmdLine, CursorPos) 1090 | -- return completion candidates as a list-like table 1091 | return { 'foo', 'bar', 'baz' } 1092 | end, 1093 | }) 1094 | ``` 1095 | 1096 | Buffer-local user commands also take a buffer number as their first argument. This is an advantage over `-buffer` which can only define a command for the current buffer. 1097 | 1098 | ```lua 1099 | vim.api.nvim_buf_create_user_command(4, 'Upper', function() end, {}) 1100 | ``` 1101 | 1102 | `vim.api.nvim_del_user_command()` takes a command name. 1103 | 1104 | ```lua 1105 | vim.api.nvim_del_user_command('Upper') 1106 | -- :delcommand Upper 1107 | ``` 1108 | 1109 | Again, `vim.api.nvim_buf_del_user_command()`, takes a buffer number as its first argument, with `0` representing the current buffer. 1110 | 1111 | ```lua 1112 | vim.api.nvim_buf_del_user_command(4, 'Upper') 1113 | ``` 1114 | 1115 | See also: 1116 | - [`:help nvim_create_user_command()`](https://neovim.io/doc/user/api.html#nvim_create_user_command()) 1117 | - [`:help 40.2`](https://neovim.io/doc/user/usr_40.html#40.2) 1118 | - [`:help command-attributes`](https://neovim.io/doc/user/map.html#command-attributes) 1119 | 1120 | ### Caveats 1121 | 1122 | The `-complete=custom` attribute automatically filters completion candidates and has built-in wildcard ([`:help wildcard`](https://neovim.io/doc/user/editing.html#wildcard)) support: 1123 | 1124 | ```vim 1125 | function! s:completion_function(ArgLead, CmdLine, CursorPos) abort 1126 | return join([ 1127 | \ 'strawberry', 1128 | \ 'star', 1129 | \ 'stellar', 1130 | \ ], "\n") 1131 | endfunction 1132 | 1133 | command! -nargs=1 -complete=custom,s:completion_function Test echo 1134 | " Typing `:Test st[ae]` returns "star" and "stellar" 1135 | ``` 1136 | 1137 | Passing a Lua function to `complete` makes it behave like `customlist` which leaves filtering up to the user: 1138 | 1139 | ```lua 1140 | vim.api.nvim_create_user_command('Test', function() end, { 1141 | nargs = 1, 1142 | complete = function(ArgLead, CmdLine, CursorPos) 1143 | return { 1144 | 'strawberry', 1145 | 'star', 1146 | 'stellar', 1147 | } 1148 | end, 1149 | }) 1150 | 1151 | -- Typing `:Test z` returns all the completion results because the list was not filtered 1152 | ``` 1153 | 1154 | ## Defining autocommands 1155 | 1156 | (this section is a work in progress) 1157 | 1158 | Neovim 0.7.0 has API functions for autocommands. See `:help api-autocmd` for details 1159 | 1160 | - [Pull request #14661](https://github.com/neovim/neovim/pull/14661) (lua: autocmds take 2) 1161 | 1162 | ## Defining highlights 1163 | 1164 | (this section is a work in progress) 1165 | 1166 | Neovim 0.7.0 has API functions for highlight groups. See also: 1167 | 1168 | - [`:help nvim_set_hl()`](https://neovim.io/doc/user/api.html#nvim_set_hl()) 1169 | - [`:help nvim_get_hl_by_id()`](https://neovim.io/doc/user/api.html#nvim_get_hl_by_id()) 1170 | - [`:help nvim_get_hl_by_name()`](https://neovim.io/doc/user/api.html#nvim_get_hl_by_name()) 1171 | 1172 | ## General tips and recommendations 1173 | 1174 | ### Reloading cached modules 1175 | 1176 | In Lua, the `require()` function caches modules. This is a good thing for performance, but it can make working on plugins a bit cumbersome because modules are not updated on subsequent `require()` calls. 1177 | 1178 | If you'd like to refresh the cache for a particular module, you have to modify the `package.loaded` global table: 1179 | 1180 | ```lua 1181 | package.loaded['modname'] = nil 1182 | require('modname') -- loads an updated version of module 'modname' 1183 | ``` 1184 | 1185 | The [nvim-lua/plenary.nvim](https://github.com/nvim-lua/plenary.nvim) plugin has a [custom function](https://github.com/nvim-lua/plenary.nvim/blob/master/lua/plenary/reload.lua) that does this for you. 1186 | 1187 | ### Don't pad Lua strings! 1188 | 1189 | When using double bracketed strings, resist the temptation to pad them! While it is fine to do in contexts where spaces are ignored, it can cause hard to debug issues when whitespace is significant: 1190 | 1191 | ```lua 1192 | vim.api.nvim_set_keymap('n', 'f', [[ call foo() ]], {noremap = true}) 1193 | ``` 1194 | 1195 | In the above example, `f` is mapped to `call foo()` instead of `call foo()`. 1196 | 1197 | ### Notes about Vimscript <-> Lua type conversion 1198 | 1199 | #### Converting a variable creates a copy: 1200 | You can't directly interact with the reference to a Vim object from Lua or a Lua object from Vimscript. 1201 | For example, the `map()` function in Vimscript modifies a variable in place: 1202 | 1203 | ```vim 1204 | let s:list = [1, 2, 3] 1205 | let s:newlist = map(s:list, {_, v -> v * 2}) 1206 | 1207 | echo s:list 1208 | " [2, 4, 6] 1209 | echo s:newlist 1210 | " [2, 4, 6] 1211 | echo s:list is# s:newlist 1212 | " 1 1213 | ``` 1214 | 1215 | Using this function from Lua creates a copy instead: 1216 | 1217 | ```lua 1218 | local tbl = {1, 2, 3} 1219 | local newtbl = vim.fn.map(tbl, function(_, v) return v * 2 end) 1220 | 1221 | print(vim.inspect(tbl)) -- { 1, 2, 3 } 1222 | print(vim.inspect(newtbl)) -- { 2, 4, 6 } 1223 | print(tbl == newtbl) -- false 1224 | ``` 1225 | 1226 | #### Conversion is not always possible 1227 | This mostly affects functions and tables: 1228 | 1229 | Lua tables that are a mix between a List and a Dictionary can't be converted: 1230 | 1231 | ```lua 1232 | print(vim.fn.count({1, 1, number = 1}, 1)) 1233 | -- E5100: Cannot convert given lua table: table should either have a sequence of positive integer keys or contain only string keys 1234 | ``` 1235 | 1236 | While you can call Vim functions in Lua with `vim.fn`, you can't hold references to them. This can cause surprising behaviors: 1237 | 1238 | ```lua 1239 | local FugitiveHead = vim.fn.funcref('FugitiveHead') 1240 | print(FugitiveHead) -- vim.NIL 1241 | 1242 | vim.cmd("let g:test_dict = {'test_lambda': {-> 1}}") 1243 | print(vim.g.test_dict.test_lambda) -- nil 1244 | print(vim.inspect(vim.g.test_dict)) -- {} 1245 | ``` 1246 | 1247 | Passing Lua functions to Vim functions is OK, storing them in Vim variables is not (fixed in Neovim 0.7.0+): 1248 | 1249 | ```lua 1250 | -- This works: 1251 | vim.fn.jobstart({'ls'}, { 1252 | on_stdout = function(chan_id, data, name) 1253 | print(vim.inspect(data)) 1254 | end 1255 | }) 1256 | 1257 | -- This doesn't: 1258 | vim.g.test_dict = {test_lambda = function() return 1 end} -- Error: Cannot convert given lua type 1259 | ``` 1260 | 1261 | Note however that doing the same from Vimscript with `luaeval()` **does** work: 1262 | 1263 | ```vim 1264 | let g:test_dict = {'test_lambda': luaeval('function() return 1 end')} 1265 | echo g:test_dict 1266 | " {'test_lambda': function('4714')} 1267 | ``` 1268 | 1269 | #### Vim booleans 1270 | A common pattern in Vim scripts is to use `1` or `0` instead of proper booleans. Indeed, Vim did not have a separate boolean type until version 7.4.1154. 1271 | 1272 | Lua booleans are converted to actual booleans in Vimscript, not numbers: 1273 | 1274 | ```vim 1275 | lua vim.g.lua_true = true 1276 | echo g:lua_true 1277 | " v:true 1278 | lua vim.g.lua_false = false 1279 | echo g:lua_false 1280 | " v:false 1281 | ``` 1282 | 1283 | ### Setting up linters/language servers 1284 | 1285 | If you're using linters and/or language servers to get diagnostics and autocompletion for Lua projects, you may have to configure Neovim-specific settings for them. Here are a few recommended settings for popular tools: 1286 | 1287 | #### luacheck 1288 | 1289 | You can get [luacheck](https://github.com/mpeterv/luacheck/) to recognize the `vim` global by putting this configuration in `~/.luacheckrc` (or `$XDG_CONFIG_HOME/luacheck/.luacheckrc`): 1290 | 1291 | ```lua 1292 | globals = { 1293 | "vim", 1294 | } 1295 | ``` 1296 | 1297 | The [Alloyed/lua-lsp](https://github.com/Alloyed/lua-lsp/) language server uses `luacheck` to provide linting and reads the same file. 1298 | 1299 | For more information on how to configure `luacheck`, please refer to its [documentation](https://luacheck.readthedocs.io/en/stable/config.html) 1300 | 1301 | #### sumneko/lua-language-server 1302 | 1303 | The [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig/) repository contains [instructions to configure sumneko/lua-language-server](https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#sumneko_lua) (the example uses the built-in LSP client but the configuration should be identical for other LSP client implementations). 1304 | 1305 | For more information on how to configure [sumneko/lua-language-server](https://github.com/sumneko/lua-language-server/) see ["Setting"](https://github.com/sumneko/lua-language-server/wiki/Setting) 1306 | 1307 | #### coc.nvim 1308 | 1309 | The [rafcamlet/coc-nvim-lua](https://github.com/rafcamlet/coc-nvim-lua/) completion source for [coc.nvim](https://github.com/neoclide/coc.nvim/) provides completion items for the Neovim stdlib. 1310 | 1311 | ### Debugging Lua code 1312 | 1313 | You can debug Lua code running in a separate Neovim instance with [jbyuki/one-small-step-for-vimkind](https://github.com/jbyuki/one-small-step-for-vimkind) 1314 | 1315 | The plugin uses the [Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/). Connecting to a debug adapter requires a DAP client like [mfussenegger/nvim-dap](https://github.com/mfussenegger/nvim-dap/) or [puremourning/vimspector](https://github.com/puremourning/vimspector/). 1316 | 1317 | ### Debugging Lua mappings/commands/autocommands 1318 | 1319 | The `:verbose` command allows you to see where a mapping/command/autocommand was defined: 1320 | 1321 | ```vim 1322 | :verbose map m 1323 | ``` 1324 | 1325 | ```text 1326 | n m_ * echo 'example' 1327 | Last set from ~/.config/nvim/init.vim line 26 1328 | ``` 1329 | 1330 | By default, this feature is disabled in Lua for performance reasons. You can enable it by starting Neovim with a verbose level greater than 0: 1331 | 1332 | ```sh 1333 | nvim -V1 1334 | ``` 1335 | 1336 | See also: 1337 | - [`:help 'verbose'`](https://neovim.io/doc/user/options.html#'verbose') 1338 | - [`:help -V`](https://neovim.io/doc/user/starting.html#-V) 1339 | - [neovim/neovim#15079](https://github.com/neovim/neovim/pull/15079) 1340 | 1341 | ### Testing Lua code 1342 | 1343 | - [plenary.nvim: test harness](https://github.com/nvim-lua/plenary.nvim/#plenarytest_harness) 1344 | - [notomo/vusted](https://github.com/notomo/vusted) 1345 | 1346 | ### Using Luarocks packages 1347 | 1348 | [wbthomason/packer.nvim](https://github.com/wbthomason/packer.nvim) supports Luarocks packages. Instructions for how to set this up are available in the [README](https://github.com/wbthomason/packer.nvim/#luarocks-support) 1349 | 1350 | ## Miscellaneous 1351 | 1352 | ### vim.loop 1353 | 1354 | `vim.loop` is the module that exposes the LibUV API. Some resources: 1355 | 1356 | - [Official documentation for LibUV](https://docs.libuv.org/en/v1.x/) 1357 | - [Luv documentation](https://github.com/luvit/luv/blob/master/docs.md) 1358 | - [teukka.tech - Using LibUV in Neovim](https://teukka.tech/posts/2020-01-07-vimloop/) 1359 | 1360 | See also: 1361 | - [`:help vim.loop`](https://neovim.io/doc/user/lua.html#vim.loop) 1362 | 1363 | ### vim.lsp 1364 | 1365 | `vim.lsp` is the module that controls the built-in LSP client. The [neovim/nvim-lspconfig](https://github.com/neovim/nvim-lspconfig/) repository contains default configurations for popular language servers. 1366 | 1367 | The behavior of the client can be configured using "lsp-handlers". For more information: 1368 | - [`:help lsp-handler`](https://neovim.io/doc/user/lsp.html#lsp-handler) 1369 | - [neovim/neovim#12655](https://github.com/neovim/neovim/pull/12655) 1370 | - [How to migrate from diagnostic-nvim](https://github.com/nvim-lua/diagnostic-nvim/issues/73#issue-737897078) 1371 | 1372 | You may also want to take a look at [plugins built around the LSP client](https://github.com/rockerBOO/awesome-neovim#lsp) 1373 | 1374 | See also: 1375 | - [`:help lsp`](https://neovim.io/doc/user/lsp.html#LSP) 1376 | 1377 | ### vim.treesitter 1378 | 1379 | `vim.treesitter` is the module that controls the integration of the [Tree-sitter](https://tree-sitter.github.io/tree-sitter/) library in Neovim. If you want to know more about Tree-sitter, you may be interested in this [presentation (38:37)](https://www.youtube.com/watch?v=Jes3bD6P0To). 1380 | 1381 | The [nvim-treesitter](https://github.com/nvim-treesitter/) organisation hosts various plugins taking advantage of the library. 1382 | 1383 | See also: 1384 | - [`:help lua-treesitter`](https://neovim.io/doc/user/treesitter.html#lua-treesitter) 1385 | 1386 | ### Transpilers 1387 | 1388 | One advantage of using Lua is that you don't actually have to write Lua code! There is a multitude of transpilers available for the language. 1389 | 1390 | - [Moonscript](https://moonscript.org/) 1391 | 1392 | Probably one of the most well-known transpilers for Lua. Adds a lots of convenient features like classes, list comprehensions or function literals. The [svermeulen/nvim-moonmaker](https://github.com/svermeulen/nvim-moonmaker) plugin allows you to write Neovim plugins and configuration directly in Moonscript. 1393 | 1394 | - [Fennel](https://fennel-lang.org/) 1395 | 1396 | A lisp that compiles to Lua. You can write configuration and plugins for Neovim in Fennel with the [Olical/aniseed](https://github.com/Olical/aniseed) or the [Hotpot](https://github.com/rktjmp/hotpot.nvim) plugin. Additionally, the [Olical/conjure](https://github.com/Olical/conjure) plugin provides an interactive development environment that supports Fennel (among other languages). 1397 | 1398 | - [Teal](https://github.com/teal-language/tl) 1399 | 1400 | The name Teal comes from pronouncing TL (typed lua). This is exactly what it tries to do - add strong typing to lua while otherwise remaining close to standard lua syntax. The [nvim-teal-maker](https://github.com/svermeulen/nvim-teal-maker) plugin can be used to write Neovim plugins or configuration files directly in Teal 1401 | 1402 | Other interesting projects: 1403 | - [TypeScriptToLua/TypeScriptToLua](https://github.com/TypeScriptToLua/TypeScriptToLua) 1404 | - [Haxe](https://haxe.org/) 1405 | - [SwadicalRag/wasm2lua](https://github.com/SwadicalRag/wasm2lua) 1406 | - [hengestone/lua-languages](https://github.com/hengestone/lua-languages) 1407 | -------------------------------------------------------------------------------- /doc/nvim-lua-guide.jax: -------------------------------------------------------------------------------- 1 | *nvim-lua-guide.txt* Getting started using Lua in Neovim 2 | 3 | ============================================================================== 4 | はじめに 5 | *luaguide-introduction* 6 | 7 | Neovimのファーストクラス言語としてのLuaはキラー機能の1つになりつつあります。 8 | しかし、Luaでプラグインを書くための教材はVim 9 | script程多くありません。これは、Luaを始めるための基本的な情報を提供する試みです。 10 | 11 | このガイドは少なくともNeovim 0.5を使用していることを前提としています。 12 | 13 | Luaを学ぶ~ 14 | 15 | まだLuaについて詳しくない場合、学ぶためのリソースはたくさんあります。: 16 | 17 | - Learn X in Y minutes page about Lua: 18 | https://learnxinyminutes.com/docs/lua/ 19 | は基本的な概要を説明します。 20 | - このガイド https://github.com/medwatt/Notes/blob/main/Lua/Lua_Quick_Guide.ipynb 21 | も素早く始めるのに良いチュートリアルです。 22 | - 動画が好きなら、Derek Banasの動画があります。 1-hour 23 | tutorial on the language: https://www.youtube.com/watch?v=iMacxZQMPXs 24 | - 実行できるサンプルを使い、対話的に学びたいですか? 25 | LuaScript tutorial: https://www.luascript.dev/learn を試してみてください。 26 | - lua-users wiki: http://lua-users.org/wiki/LuaDirectory 27 | にはLua関連のトピックごとの便利な情報がたくさんあります。 28 | - official reference manual for Lua: https://www.lua.org/manual/5.1/ 29 | には最も包括的な情報があります。 30 | エディタで快適に読みたいなら、Vimdocプラグインがあります。: 31 | milisims/nvim-luaref: https://github.com/milisims/nvim-luaref 32 | 33 | Luaはとてもクリーンでシンプルな言語であることに注意してください。 34 | JavaScriptのようなスクリプト言語の経験があれば、学ぶことは簡単です。 35 | あなたはもう自分で思っているよりLuaについて知っているかもしれません! 36 | 37 | Note: Neovimに埋め込まれているLuaはLuaJIT: 38 | https://staff.fnwi.uva.nl/h.vandermeer/docs/lua/luajit/luajit_intro.html 39 | 2.1.0でLua 5.1と互換性を維持しています。 40 | 41 | Luaを書くための既存のチュートリアル~ 42 | 43 | Luaでプラグインを書くためのチュートリアルが既にいくつかあります。 44 | それらはこのガイドを書くのに役に立ちました。筆者に感謝します。 45 | 46 | - teukka.tech - init.vimからinit.luaへ: 47 | https://teukka.tech/luanvim.html 48 | - 2n.pl - プラグインをLuaで書く方法: 49 | https://dev.to/2nit/how-to-write-neovim-plugins-in-lua-5cca 50 | - 2n.pl - プラグインのUIをLuaで作る方法: 51 | https://dev.to/2nit/how-to-make-ui-for-neovim-plugins-in-lua-3b6e 52 | - ms-jpq - Neovim Async Tutorial: 53 | https://github.com/ms-jpq/neovim-async-tutorial 54 | - oroques.dev - Neovim 0.5の機能とinit.luaへの切り替え: 55 | https://oroques.dev/notes/neovim-init/ 56 | - ゼロからステータスラインを作る - jdhao's blog: 57 | https://jdhao.github.io/2019/11/03/vim_custom_statusline/ 58 | - LuaでNeovimを設定する: https://icyphox.sh/blog/nvim-lua/ 59 | - Devlog | Luaで設定するために知る必要のあること: 60 | https://vonheikemen.github.io/devlog/tools/configuring-neovim-using-lua/ 61 | 62 | 関連するプラグイン~ 63 | 64 | - Vimpeccable: https://github.com/svermeulen/vimpeccable - 65 | .vimrc内でLuaを書くのに役に立つプラグイン 66 | - plenary.nvim: https://github.com/nvim-lua/plenary.nvim - 67 | 二度書きたくないLua関数のすべて 68 | - popup.nvim: https://github.com/nvim-lua/popup.nvim - vimのPopup 69 | APIのNeovimでの実装 70 | - nvim_utils: https://github.com/norcalli/nvim_utils 71 | - nvim-luadev: https://github.com/bfredl/nvim-luadev - 72 | REPL/debugコンソール 73 | - nvim-luapad: https://github.com/rafcamlet/nvim-luapad - 74 | 組込みLuaエンジンのインタラクティブなリアルタイムスクラッチパッド 75 | - nlua.nvim: https://github.com/tjdevries/nlua.nvim - NeovimのLua開発 76 | - BetterLua.vim: https://github.com/euclidianAce/BetterLua.vim - 77 | Vim/Neovimより良いシンタックスハイライト 78 | 79 | ============================================================================== 80 | Luaファイルを置く場所 81 | *luaguide-where-to-put-lua-files* 82 | 83 | init.lua~ 84 | 85 | Neovimは、`init.vim`の代わりに設定ファイルとして`init.lua`を読み込むことをサポートしています。 86 | 87 | Note: `init.lua`は_完全に_オプションです。`init.vim`は廃止されず、設定として有効です。 88 | いくつかの機能は、まだ100%Luaに公開されていないので注意してください。 89 | 90 | 参照: 91 | - |config| 92 | 93 | モジュール~ 94 | 95 | Luaモジュールは、`'runtimepath'`内の`lua/`フォルダにあります(ほとんどの場合、 96 | \*nixでは`~/.config/nvim/lua`、Windowsでは`~/AppData/Local/nvim/lua`を意味します)。 97 | このフォルダにあるファイルをLuaモジュールとして`require()`できます。 98 | 99 | 例として次のフォルダ構造を取り上げましょう。: 100 | 101 | > 102 | 📂 ~/.config/nvim 103 | ├── 📁 after 104 | ├── 📁 ftplugin 105 | ├── 📂 lua 106 | │ ├── 🌑 myluamodule.lua 107 | │ └── 📂 other_modules 108 | │ ├── 🌑 anothermodule.lua 109 | │ └── 🌑 init.lua 110 | ├── 📁 pack 111 | ├── 📁 plugin 112 | ├── 📁 syntax 113 | └── 🇻 init.vim 114 | < 115 | 116 | 次のLuaコードは`myluamodule.lua`をロードします。: 117 | 118 | > 119 | require('myluamodule') 120 | < 121 | 122 | `.lua`拡張子がないことに注意してください。 123 | 124 | 同様に、`other_modules/anothermodule.lua` 125 | のロードは次のように行います。: 126 | 127 | > 128 | require('other_modules.anothermodule') 129 | -- or 130 | require('other_modules/anothermodule') 131 | < 132 | 133 | パスの区切りはドット`.`またはスラッシュ`/`で示されます。 134 | 135 | フォルダに`init.lua`が含まれている場合、ファイル名を指定せずにロードできます。 136 | 137 | > 138 | require('other_modules') -- other_modules/init.luaをロード 139 | < 140 | 141 | 存在しないモジュール、構文エラーを含むモジュールをrequireすると実行中のスクリプトは停止します。 142 | エラーを防ぐために、`pcall()`を使用できます。 143 | 144 | > 145 | local ok, _ = pcall(require, 'module_with_error') 146 | if not ok then 147 | -- not loaded 148 | end 149 | < 150 | 151 | 参照: 152 | - `:help lua-require` 153 | 154 | Runtime files~ 155 | 156 | Vim scriptと同様に、`runtimepath`内にある特定のフォルダからLuaファイルを自動的に読み込めます。 157 | 現在、次のフォルダがサポートされています。: 158 | 159 | - `colors/` 160 | - `compiler/` 161 | - `ftplugin/` 162 | - `ftdetect/` 163 | - `indent/` 164 | - `plugin/` 165 | - `syntax/` 166 | 167 | 参照: 168 | - `:help 'runtimepath'` 169 | 170 | Tips~ 171 | 172 | いくつかのLuaプラグインは`lua/`フォルダ内に同じ名前のファイルがあるかもしれません。 173 | これにより、名前空間の衝突を起こす可能性があります。 174 | 175 | 異なる2つのプラグインに`lua/main.lua`がある場合、`require('main')`は曖昧です。: 176 | どのファイルを読み込みますか? 177 | 178 | トップレベルのフォルダで名前空間をつけることをお勧めします。: 179 | `lua/plugin_name/main.lua` 180 | 181 | Runtime files~ 182 | 183 | Vim scriptと同様に、`runtimepath`内にある特定のフォルダからLuaファイルを自動的に読み込めます。 184 | 現在、次のフォルダがサポートされています。: 185 | 186 | - `colors/` 187 | - `compiler/` 188 | - `ftplugin/` 189 | - `ftdetect/` 190 | - `indent/` 191 | - `plugin/` 192 | - `syntax/` 193 | 194 | Note: runtimeデイレクトリでは、すべての`*.vim`ファイルは`*.lua`ファイルの前に読み込まれます。 195 | 196 | 197 | 参照: 198 | - `:help 'runtimepath'` 199 | - `:help load-plugins` 200 | 201 | Tips~ 202 | 203 | ランタイムファイルはLuaのモジュールシステムをベースとしていないため、2つのプラグインは`plugin/main.lua`を問題なく持つことができます。 204 | 205 | ============================================================================== 206 | Vim scriptからLuaを使用する 207 | *luaguide-using-lua-from-vimscript* 208 | 209 | :lua~ 210 | 211 | Luaのチャンクを実行します。 212 | 213 | > 214 | :lua require('myluamodule') 215 | < 216 | 217 | ヒアドキュメント構文を使用すると複数行に書くことができます。: 218 | 219 | > 220 | echo "Here's a bigger chunk of Lua code" 221 | 222 | lua << EOF 223 | local mod = require('mymodule') 224 | local tbl = {1, 2, 3} 225 | 226 | for k, v in ipairs(tbl) do 227 | mod.method(v) 228 | end 229 | 230 | print(tbl) 231 | EOF 232 | < 233 | 234 | Note: 各`:lua`コマンドは独自のスコープを持っており、`local`を付けた変数はコマンドの外からアクセスできません。 235 | 次の例は動作しません。: 236 | 237 | > 238 | :lua local foo = 1 239 | :lua print(foo) 240 | " '1'ではなく'nil'が出力されます。 241 | < 242 | 243 | Note 2: Luaの`print()`は`:echomsg`と同じように動作します。出力はメッセージ履歴に保存されます。また、`:silent`で抑制できます。 244 | 245 | 参照: 246 | 247 | - |:lua| 248 | - |:lua-heredoc| 249 | 250 | :luado~ 251 | 252 | このコマンドはカレントバッファの範囲行にLuaチャンクを実行します。範囲を指定しない場合、バッファ全体に作用します。 253 | チャンクから`return`された文字列は、各行を置き換えるために使用されます。 254 | 255 | 次のコマンドは、カレントバッファのすべての行を`hello 256 | world`に置き換えます。: 257 | 258 | > 259 | :luado return 'hello world' 260 | < 261 | 262 | 2つの暗黙的な変数`line`と`liner`が提供されます。`line`は対象行のテキストで、`liner`はその行数です。 263 | 次のコマンドは、すべての偶数行のテキストを大文字にします。 264 | 265 | > 266 | :luado if linenr % 2 == 0 then return line:upper() end 267 | < 268 | 269 | 参照: 270 | 271 | - |:luado| 272 | 273 | Luaファイルの読み込み~ 274 | 275 | NeovimはLuaファイルを読み込むためのEXコマンドを3つ提供しています。 276 | 277 | - `:luafile` 278 | - `:source` 279 | - `:runtime` 280 | 281 | `:luafile`と`:source`はとてもよく似ています。: 282 | 283 | > 284 | :luafile ~/foo/bar/baz/myluafile.lua 285 | :luafile % 286 | :source ~/foo/bar/baz/myluafile.lua 287 | :source % 288 | < 289 | 290 | `:source`は範囲指定もサポートしており、スクリプトの一部を実行するのに役立ちます。: 291 | 292 | > 293 | :1,10source 294 | < 295 | 296 | `:runtime`は少し異なります。: `'runtimepath'`オプションで読み込むファイルを指定します。詳細は`:help :runtime`を参照してください。 297 | 298 | 参照: 299 | 300 | - `:help :luafile` 301 | - `:help :source` 302 | - `:help :runtime` 303 | 304 | Sourcing a lua file vs calling require()~ 305 | 306 | `require()`関数を呼ぶこととLuaファイルの読み込みの違いは何か、どちらを使うべきかを疑問に思うかもしれません。 307 | それらには異なるユースケースがあります。: 308 | 309 | - `require()`: 310 | - Luaの組込み関数です。Luaのモジュールを読み込むのに使用します。 311 | - `'runtimepath'`内にある`lua/`フォルダからモジュールを探します。 312 | - どのモジュールをロードしたかを記憶し、多重に実行されるのを防ぎます。 313 | Neovim実行中に、モジュールに含まれるコードを変更し、もう一度`require()`を実行してもモジュールは更新されません。 314 | - `:luafile`, `:source`, `runtime`: 315 | - Exコマンドです。モジュールには対応していません。 316 | - 以前に実行されたかどうかに関わらず実行されます。 317 | - `:luafile`と`:source`は現在のウィンドウのディレクトリに対して相対パス・絶対パスを取ります。 318 | - `runtime`は、`'rutimepath'`オプションを使用してファイルを探します。 319 | 320 | `:source`や`:runtime`、ランタイムディレクトリから自動的に読み込まれたファイルも`scriptnames`と`--startuptime`に表示されます。 321 | 322 | luaeval()~ 323 | 324 | Vim 325 | scriptの組込み関数です。文字列のLua式を評価して返します。 326 | Luaの型は自動的にVim 327 | scriptの型に変換されます。(その逆も同様です。) 328 | 329 | > 330 | " 変数に結果を代入することができます。 331 | let variable = luaeval('1 + 1') 332 | echo variable 333 | " 2 334 | let concat = luaeval('"Lua".." is ".."awesome"') 335 | echo concat 336 | " 'Lua is awesome' 337 | 338 | " リストのようなテーブルはVimのリストに変換されます。 339 | let list = luaeval('{1, 2, 3, 4}') 340 | echo list[0] 341 | " 1 342 | echo list[1] 343 | " 2 344 | " 注意 345 | Luaのテーブルと違い、Vimのリストは0インデックスです。 346 | 347 | " 辞書のようなテーブルはVimの辞書に変換されます。 348 | let dict = luaeval('{foo = "bar", baz = "qux"}') 349 | echo dict.foo 350 | " 'bar' 351 | 352 | " bool値とnilも同様です。 353 | echo luaeval('true') 354 | " v:true 355 | echo luaeval('nil') 356 | " v:null 357 | 358 | " Lua関数のエイリアスをVim 359 | scriptで作ることができます。 360 | let LuaMathPow = luaeval('math.pow') 361 | echo LuaMathPow(2, 2) 362 | " 4 363 | let LuaModuleFunction = luaeval('require("mymodule").myfunction') 364 | call LuaModuleFunction() 365 | 366 | " Vimの関数にLuaの関数を値として渡すこともできます。 367 | lua X = function(k, v) return string.format("%s:%s", k, v) end 368 | echo map([1, 2, 3], luaeval("X")) 369 | < 370 | 371 | `luaeval()`は式にデータを渡すことのできる任意の2つ目の引数があります。Luaからは`_A`としてアクセスできます。 372 | 373 | > 374 | echo luaeval('_A[1] + _A[2]', [1, 1]) 375 | " 2 376 | 377 | echo luaeval('string.format("Lua is %s", _A)', 'awesome') 378 | " 'Lua is awesome' 379 | < 380 | 381 | 参照: 382 | - |luaeval()| 383 | 384 | v:lua~ 385 | 386 | Vimのグローバル変数です。Vim 387 | scriptからLuaのグローバル名前空間(`_G`: https://www.lua.org/manual/5.1/manual.html#pdf-_G 388 | )内の関数を直接呼ぶことができます。 389 | この場合でも、Vim scriptの型はLuaの型に変換されます。逆も同様です。 390 | 391 | > 392 | call v:lua.print('Hello from Lua!') 393 | " 'Hello from Lua!' 394 | 395 | let scream = v:lua.string.rep('A', 10) 396 | echo scream 397 | " 'AAAAAAAAAA' 398 | 399 | " How about a nice statusline? 400 | lua << EOF 401 | function _G.statusline() 402 | local filepath = '%f' 403 | local align_section = '%=' 404 | local percentage_through_file = '%p%%' 405 | return string.format( 406 | '%s%s%s', 407 | filepath, 408 | align_section, 409 | percentage_through_file 410 | ) 411 | end 412 | EOF 413 | 414 | set statusline=%!v:lua.statusline() 415 | 416 | " Also works in expression mappings 417 | lua << EOF 418 | function _G.check_back_space() 419 | local col = vim.api.nvim_win_get_cursor(0)[2] 420 | return (col == 0 or vim.api.nvim_get_current_line():sub(col, col):match('%s')) and true 421 | end 422 | EOF 423 | 424 | inoremap 425 | \ pumvisible() ? "\" : 426 | \ v:lua.check_back_space() ? "\" : 427 | \ completion#trigger_completion() 428 | 429 | " シングルクォートを使用したり、括弧を省略して、 430 | " Luaモジュールから関数を呼び出します: 431 | call v:lua.require'module'.foo() 432 | < 433 | 434 | 参照: 435 | - |v:lua| 436 | - |v:lua-call| 437 | 438 | 警告~ 439 | 440 | この変数は関数呼び出しにのみ使用できます。次の例はエラーになります。: 441 | 442 | > 443 | " 関数のエイリアスは動作しません 444 | let LuaPrint = v:lua.print 445 | 446 | " 辞書アクセスは動作しません 447 | echo v:lua.some_global_dict['key'] 448 | 449 | " 関数を値として使用できません 450 | echo map([1, 2, 3], v:lua.global_callback) 451 | < 452 | 453 | Tips~ 454 | 455 | 設定ファイルに、`let g:vimsyn_embed = 456 | 'l'`を追加すると.vimファイル内のLuaを構文ハイライトできます。 457 | 詳細は`:h g:vimsyn_embed`を参照してください。 458 | 459 | ============================================================================== 460 | vim名前空間 461 | *luaguide-the-vim-namespace* 462 | 463 | NeovimはLuaからAPIを使うためのエントリーポイントとして、`vim`グーローバル変数を公開しています。 464 | これは、拡張された標準ライブラリやさまざまなサブモジュールを提供します。 465 | 466 | いくつかの注目すべき関数とモジュール: 467 | 468 | - `vim.inspect`: 469 | Luaオブジェクトを人間が読みやすい文字列に変換する(テーブルを調べるのに便利です。) 470 | - `vim.regex`: LuaからVimの正規表現を使う 471 | - `vim.api`: 472 | API関数を公開するモジュール(リモートプラグインで使うAPIと同じです) 473 | - `vim.ui`: 474 | プラグインから利用できる上書き可能な関数 475 | - `vim.loop`: 476 | Neovimのイベントループ機能を公開するモジュール(LibUVを使います) 477 | - `vim.lsp`: 478 | 組込みのLSPクライアントを操作するモジュール 479 | - `vim.treesitter`: 480 | tree-sitterライブラリの機能を公開するモジュール 481 | 482 | このリストは決して包括的なリストではありません。`vim`変数で何かできるかを詳しく知りたい場合は、`:h 483 | lua-stdlib`と`:help lua-vim`が最適です。 484 | または、`:lua 485 | print(vim.inspect(vim))`を実行してすべてのモジュールのリストを取得できます。 486 | API関数は、`:help api-global`にあります。 487 | 488 | Tips~ 489 | 490 | オブジェクトの中身を検査するのに毎回`print(vim.inspect(x)`を書くのは面倒です。設定にグローバルなラッパー関数を含めることは価値があるかもしれません。 491 | (Neovim 0.7.0+では、この関数は組込み関数です。参照 |help vim.pretty_print()|): 492 | 493 | > 494 | function _G.put(...) 495 | local objects = {} 496 | for i = 1, select('#', ...) do 497 | local v = select(i, ...) 498 | table.insert(objects, vim.inspect(v)) 499 | end 500 | 501 | print(table.concat(objects, '\n')) 502 | return ... 503 | end 504 | < 505 | 506 | コードまたはコマンドラインからとても早くオブジェクトの中身を検査できます。 507 | 508 | > 509 | put({1, 2, 3}) 510 | < 511 | 512 | > 513 | :lua put(vim.loop) 514 | < 515 | 516 | または、`:lua`コマンドでLua式の前に `=` をつけて、整列させて表示できます。(Neovim 0.7+のみ) 517 | > 518 | :lua =vim.loop 519 | 520 | 521 | 加えて、他の言語と比較して組込みのLua関数が不足している場合があります(例えば、`os.clock`はミリ秒ではなく秒数のみを返します)。 522 | 必ず、Neovim 523 | stdlib(それと`vim.fn`。詳しくは後述します。)を見てください。おそらく、探しものはそこにあります。 524 | 525 | ============================================================================== 526 | LuaからVim scriptを使用する 527 | *luaguide-using-vimscript-from-lua* 528 | 529 | vim.api.nvim_eval()~ 530 | 531 | 文字列で与えられたVim 532 | scriptの式を評価してその値を返します。Vim 533 | scriptの型は自動的にLuaの型に変換されます。(その逆も同様です。) 534 | 535 | これは、Vim scriptの`luaeval()`と同様です。 536 | 537 | > 538 | -- 型は正しく変換されます。 539 | print(vim.api.nvim_eval('1 + 1')) -- 2 540 | print(vim.inspect(vim.api.nvim_eval('[1, 2, 3]'))) -- { 1, 2, 3 } 541 | print(vim.inspect(vim.api.nvim_eval('{"foo": "bar", "baz": "qux"}'))) 542 | -- { baz = "qux", foo = "bar" } 543 | print(vim.api.nvim_eval('v:true')) -- true 544 | print(vim.api.nvim_eval('v:null')) -- nil 545 | < 546 | 547 | 警告~ 548 | 549 | `luaeval()`と違い、式にデータを渡すための暗黙的な変数`_A`を提供しません。 550 | 551 | vim.api.nvim_exec()~ 552 | 553 | Vim 554 | scriptのチャンクを実行します。実行するソースコートを含む文字列と、コードの出力を返すかどうかを決めるbool値を受け取ります(例えば、出力を変数に格納できます)。 555 | 556 | > 557 | local result = vim.api.nvim_exec( 558 | [[ 559 | let s:mytext = 'hello world' 560 | 561 | function! s:MyFunction(text) 562 | echo a:text 563 | endfunction 564 | 565 | call MyFunction(s:mytext) 566 | ]], 567 | true) 568 | 569 | print(result) -- 'hello world' 570 | < 571 | 警告 572 | 573 | Neovim 0.6.0より前のバージョンでは 、`nvim_exec` はスクリプトローカル変数(`s:`)をサポートしていません。 574 | 575 | vim.api.nvim_command()~ 576 | 577 | Exコマンドを実行します。実行するコマンドを含む文字列を受け取ります。 578 | 579 | > 580 | vim.api.nvim_command('new') 581 | vim.api.nvim_command('wincmd H') 582 | vim.api.nvim_command('set nonumber') 583 | vim.api.nvim_command('%s/foo/bar/g') 584 | < 585 | 586 | 587 | vim.cmd()~ 588 | 589 | `vim.api.nvim_exec()`のエイリアスです。コマンドの引数のみを必要とし、`output`は常に`false`に設定されます。 590 | 591 | > 592 | vim.cmd('buffers') 593 | vim.cmd([[ 594 | let g:multiline_list = [ 595 | \ 1, 596 | \ 2, 597 | \ 3, 598 | \ ] 599 | 600 | echo g:multiline_list 601 | ]]) 602 | 603 | Tips~ 604 | 605 | これらの関数は文字列を渡すため、多くの場合、バックスラッシュをエスケープする必要があります。: 606 | 607 | > 608 | vim.cmd('%s/\\Vfoo/bar/g') 609 | < 610 | 611 | 二重括弧の文字列はエスケープが必要ないため使いやすいです。: 612 | 613 | > 614 | vim.cmd([[%s/\Vfoo/bar/g]]) 615 | < 616 | 617 | vim.api.nvim_replace_termcodes()~ 618 | 619 | このAPI関数はターミナルコードとVimのキーコードをエスケープできます。 620 | 621 | 次のようなマッピングを見たことがあるかもしれません。: 622 | 623 | > 624 | inoremap pumvisible() ? "\" : "\" 625 | < 626 | 627 | 同じことをLuaでやると大変です。 628 | 次のようにやるかもしれません。: 629 | 630 | > 631 | function _G.smart_tab() 632 | return vim.fn.pumvisible() == 1 and [[\]] or [[\]] 633 | end 634 | 635 | vim.api.nvim_set_keymap('i', '', 'v:lua.smart_tab()', {expr = 636 | true, noremap = true}) 637 | < 638 | 639 | マッピングに `\` と `\` が挿入されているのを知るためだけに... 640 | 641 | キーコードをエスケープできるのは、Vim scriptの機能です。 642 | `\r`, `\42` や `\x10` のような多くのプログラミング言語に共通する通常のエスケープシーケンスとは別に、 643 | Vim scriptの `expr-quotes` (ダブルクォートで囲まれる文字列)を使用すると、 644 | 人間が読める表現のVimキーコードをエスケープします。 645 | 646 | Luaにはそのような機能は組み込まれていません。 647 | 嬉しいことに、NeovimにはターミナルコードとキーコードをエスケープするAPI関数 648 | `nvim_replace_termcodes()` があります。: 649 | 650 | > 651 | print(vim.api.nvim_replace_termcodes('', true, true, true)) 652 | < 653 | 654 | これは少し冗長です。再利用できるラッパーを作ると便利です。: 655 | 656 | > 657 | -- `termcodes` 専用の `t` 関数です 658 | -- この名前で呼ばなくてもいいですが、この簡潔さが便利です 659 | local function t(str) 660 | -- 必要に応じてboolean引数で調整します 661 | return vim.api.nvim_replace_termcodes(str, true, true, true) 662 | end 663 | 664 | print(t'') 665 | < 666 | 667 | 先程の例はこれで期待通りに動きます。: 668 | 669 | > 670 | local function t(str) 671 | return vim.api.nvim_replace_termcodes(str, true, true, true) 672 | end 673 | 674 | function _G.smart_tab() 675 | return vim.fn.pumvisible() == 1 and t'' or t'' 676 | end 677 | 678 | vim.api.nvim_set_keymap('i', '', 'v:lua.smart_tab()', {expr = 679 | true, noremap = true}) 680 | < 681 | 682 | `vim.keymap.set()`では、このハックは必要ありません。 683 | `expr`が有効な場合、デフォルトで自動的に変換されます。: 684 | 685 | > 686 | vim.keymap.set('i', '', function() 687 | return vim.fn.pumvisible() == 1 and '' or '' 688 | end, {expr = true}) 689 | < 690 | 691 | 参照: 692 | - |keycodes| 693 | - |expr-quote| 694 | - |nvim_replace_termcodes()| 695 | 696 | ============================================================================== 697 | vimオプションを管理する 698 | *luaguide-managing-vim-options* 699 | 700 | API関数を使用する~ 701 | 702 | Neovimは、オプションの値を読み書きできるAPI関数を提供しています。 703 | 704 | - グローバルオプション: 705 | - `vim.api.nvim_set_option()` 706 | - `vim.api.nvim_get_option()` 707 | - バッファオプション: 708 | - `vim.api.nvim_buf_set_option()` 709 | - `vim.api.nvim_buf_get_option()` 710 | - ウィンドウオプション: 711 | - `vim.api.nvim_win_set_option()` 712 | - `vim.api.nvim_win_get_option()` 713 | 714 | それらはオプションの名前と設定したい値を含む文字列を受け取ります。 715 | 716 | boolな(`(no)number`のような)オプションは`true`か`false`のどちらかに設定する必要があります。: 717 | 718 | > 719 | vim.api.nvim_set_option('smarttab', false) 720 | print(vim.api.nvim_get_option('smarttab')) -- false 721 | < 722 | 723 | 当然ながら、文字列のオプションには文字列を設定する必要があります。: 724 | 725 | > 726 | vim.api.nvim_set_option('selection', 'exclusive') 727 | print(vim.api.nvim_get_option('selection')) -- 'exclusive' 728 | < 729 | 730 | 数値のオプションは数値を受け取ります。: 731 | 732 | > 733 | vim.api.nvim_set_option('updatetime', 3000) 734 | print(vim.api.nvim_get_option('updatetime')) -- 3000 735 | < 736 | 737 | バッファローカルとウィンドウローカルなオプションはそれぞれの番号も必要です。(`0`を指定した場合、カレントバッファ/ウィンドウが対象になります。): 738 | 739 | > 740 | vim.api.nvim_win_set_option(0, 'number', true) 741 | vim.api.nvim_buf_set_option(10, 'shiftwidth', 4) 742 | print(vim.api.nvim_win_get_option(0, 'number')) -- true 743 | print(vim.api.nvim_buf_get_option(10, 'shiftwidth')) -- 4 744 | < 745 | 746 | メタアクセサーを使用する~ 747 | 748 | もっと使い慣れた方法でオプションを設定したい場合、いくつかのメタアクセサーを使用できます。それらは、上記のAPI関数をラップしたものでオプションを変数のように操作できます。: 749 | 750 | - `vim.o.{option}`: `:let &{option-name}`のように動作します 751 | - `vim.go.{option}`: `:let &g:{option-name}`のように動作します 752 | - `vim.bo.{option}`: バッファローカルオプションの場合`:let &l:{option-name}`のように動作します 753 | - `vim.wo.{option}`: ウィンドウローカルオプションの場合`:let &l:{option-name}`のように動作します 754 | 755 | > 756 | vim.o.smarttab = false -- let &smarttab = v:false 757 | print(vim.o.smarttab) -- false 758 | vim.o.isfname = vim.o.isfname .. ',@-@' -- on Linux: let &isfname = &isfname .. ',@-@' 759 | print(vim.o.isfname) -- '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@' 760 | 761 | vim.bo.shiftwidth = 4 762 | print(vim.bo.shiftwidth) -- 4 763 | < 764 | 765 | バッファとウィンドウの番号を指定できます。0を指定した場合、カレントバッファ/ウィンドウが使用されます。: 766 | 767 | > 768 | vim.bo[4].expandtab = true -- same as vim.api.nvim_buf_set_option(4, 769 | 'expandtab', true) 770 | vim.wo.number = true -- same as vim.api.nvim_win_set_option(0, 771 | 'number', true) 772 | < 773 | 774 | これらには、Luaで設定するのに便利なより洗練されたラッパーとして`vim.opt`があります。 775 | `init.vim`で慣れているものと似ています。: 776 | 777 | - `vim.opt.{option}`: `:set`のように動作します 778 | - `vim.opt_global.{option}`: `:setglobal`のように動作します 779 | - `vim.opt_local.{option}`: `:setlocal`のように動作します 780 | 781 | > 782 | vim.opt.smarttab = false 783 | print(vim.opt.smarttab:get()) -- false 784 | < 785 | 786 | いくつかのオプションはLuaのテーブルを使用して設定できます。: 787 | 788 | > 789 | vim.opt.completeopt = {'menuone', 'noselect'} 790 | print(vim.inspect(vim.opt.completeopt:get())) -- { "menuone", "noselect" } 791 | < 792 | 793 | list、map、setのようなオプションのラッパーには、Vim scriptの 794 | `:set+=`, `:set^=`, `:set-=`と同じように動作するメソッドとメタメソッドが用意されています。 795 | 796 | > 797 | vim.opt.shortmess:append({ I = true }) 798 | -- どちらも等価です: 799 | vim.opt.shortmess = vim.opt.shortmess + { I = true } 800 | 801 | vim.opt.whichwrap:remove({ 'b', 's' }) 802 | -- どちらも等価です: 803 | vim.opt.whichwrap = vim.opt.whichwrap - { 'b', 's' } 804 | < 805 | 806 | 詳細は、必ず`:help vim.opt`を参照してください。 807 | 808 | 参照: 809 | - `:help lua-vim-options` 810 | 811 | 参照: 812 | - |lua-vim-options| 813 | 814 | ============================================================================== 815 | vim内部の変数を管理する 816 | *luaguide-managing-vim-internal-variables* 817 | 818 | API関数を使用する~ 819 | 820 | オプションのように、内部変数にもAPI関数があります。 821 | 822 | - グローバル変数 (`g:`): 823 | - `vim.api.nvim_set_var()` 824 | - `vim.api.nvim_get_var()` 825 | - `vim.api.nvim_del_var()` 826 | - バッファ変数 (`b:`): 827 | - `vim.api.nvim_buf_set_var()` 828 | - `vim.api.nvim_buf_get_var()` 829 | - `vim.api.nvim_buf_del_var()` 830 | - ウィンドウ変数 (`w:`): 831 | - `vim.api.nvim_win_set_var()` 832 | - `vim.api.nvim_win_get_var()` 833 | - `vim.api.nvim_win_del_var()` 834 | - タブ変数 (`t:`): 835 | - `vim.api.nvim_tabpage_set_var()` 836 | - `vim.api.nvim_tabpage_get_var()` 837 | - `vim.api.nvim_tabpage_del_var()` 838 | - Vimの定義済み変数 (`v:`): 839 | - `vim.api.nvim_set_vvar()` 840 | - `vim.api.nvim_get_vvar()` 841 | 842 | Vimの定義済み変数を除いて、削除できます(Vim 843 | scriptの`:unlet`と同様です)。 844 | ローカル変数(`l:`)、スクリプト変数(`s:`)、関数の引数(`a:`)はVim 845 | script内でのみ意味があるため操作できません。 846 | Luaには独自のスコープルールがあります。 847 | 848 | これらの変数が不慣れな場合、`:h 849 | internal-variables`に説明があります。 850 | 851 | これらの関数は対象の変数名と、設定したい値を含む文字列を受け取ります。 852 | 853 | > 854 | vim.api.nvim_set_var('some_global_variable', { key1 = 'value', key2 = 855 | 300 }) 856 | print(vim.inspect(vim.api.nvim_get_var('some_global_variable'))) -- 857 | { key1 = "value", key2 = 300 } 858 | vim.api.nvim_del_var('some_global_variable') 859 | < 860 | 861 | バッファ、ウィンドウ、タブページなスコープを持つ変数はそれぞれの番号を受け取ります(0を指定した場合は現在のバッファ/ウィンドウ/タブページが使われます。)。: 862 | 863 | > 864 | vim.api.nvim_win_set_var(0, 'some_window_variable', 2500) 865 | vim.api.nvim_tab_set_var(3, 'some_tabpage_variable', 'hello world') 866 | print(vim.api.nvim_win_get_var(0, 'some_window_variable')) -- 2500 867 | print(vim.api.nvim_buf_get_var(3, 'some_tabpage_variable')) -- 868 | 'hello world' 869 | vim.api.nvim_win_del_var(0, 'some_window_variable') 870 | vim.api.nvim_buf_del_var(3, 'some_tabpage_variable') 871 | < 872 | 873 | メタアクセサーを使用する~ 874 | 875 | 内部の変数はメタアクセサーを使用し、もっと直感的に操作できます。: 876 | 877 | - `vim.g.{name}`: グローバル変数 878 | - `vim.b.{name}`: バッファ変数 879 | - `vim.w.{name}`: ウィンドウ変数 880 | - `vim.t.{name}`: タブ変数 881 | - `vim.v.{name}`: Vimの定義済み変数 882 | - `vim.env.{name}`: 環境変数 883 | 884 | > 885 | vim.g.some_global_variable = { 886 | key1 = 'value', 887 | key2 = 300 888 | } 889 | 890 | print(vim.inspect(vim.g.some_global_variable)) -- { key1 = "value", 891 | key2 = 300 } 892 | 893 | -- 特定のバッファ/ウィンドウ/タブを対象とします(Neovim 0.6+) 894 | vim.b[2].myvar = 1 895 | < 896 | 897 | 一部の変数名には、Luaの識別子に使用できない文字が含まれている場合があります。 898 | この構文を使用してこれらの変数を操作できます。: `vim.g['my#variable']` 899 | 900 | 変数を削除するには単に`nil`を代入します。: 901 | 902 | > 903 | vim.g.some_global_variable = nil 904 | < 905 | 906 | 警告~ 907 | 908 | 辞書の1つのキーを追加/更新/削除できません。例えば、次のVim 909 | scriptは期待通りに動きません。: 910 | 911 | > 912 | let g:variable = {} 913 | lua vim.g.variable.key = 'a' 914 | echo g:variable 915 | " {} 916 | 917 | 918 | 一時的な変数を使用する回避策があります: 919 | 920 | > 921 | let g:variable = {} 922 | lua << EOF 923 | local tmp = vim.g.variable 924 | tmp.key = 'a' 925 | vim.g.variable = tmp 926 | EOF 927 | echo g:variable 928 | " {'key': 'a'} 929 | 930 | 931 | 既知のissue: 932 | 933 | - Issue #12544: https://github.com/neovim/neovim/issues/12544 934 | 935 | ============================================================================== 936 | Vim scriptの関数を呼び出す 937 | *luaguide-calling-vimscript-functions* 938 | 939 | vim.fn.{function}()~ 940 | 941 | `vim.fn`は、Vim script組込みの関数を呼び出せます。 942 | 型はVimとLuaとで変換されます。 943 | 944 | > 945 | print(vim.fn.printf('Hello from %s', 'Lua')) 946 | 947 | local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' }) 948 | print(vim.inspect(reversed_list)) -- { "c", "b", "a" } 949 | 950 | local function print_stdout(chan_id, data, name) 951 | print(data[1]) 952 | end 953 | 954 | vim.fn.jobstart('ls', { on_stdout = print_stdout }) 955 | < 956 | 957 | ハッシュ(`#`)はLuaで有効な識別子ではないため、autoload関数は次の構文で呼び出す必要があります。: 958 | 959 | > 960 | vim.fn['my#autoload#function']() 961 | < 962 | `vim.fn`は`vim.call`と同じ動作ですが、よりLuaらしい構文を使用できます。 963 | 964 | `vim.api.nvim_call_function`とは、Vim/Luaオブジェクトを自動で変換する点が異なります。: 965 | `vim.api.nvim_call_function`は浮動小数点数のテーブルを返しLuaのクロージャーを受け入れませんが、`vim.fn`はこれらの型を扱えます。 966 | 967 | 参照: 968 | - |vim.fn| 969 | 970 | Tips~ 971 | 972 | Neovimにはプラグインに便利な強力な組込み関数を含むライブラリがあります。 973 | アルファベット順のリストは`:help 974 | vim-function`を参照してください。 975 | `:help function-list`は機能別に分類されたリストです。 976 | 977 | NeovimのAPI関数は`vim.api{..}`のように直接使用できます。 978 | 詳細は`:help api`を参照してください。 979 | 980 | 警告~ 981 | 982 | いくつかのVim関数はbool値の変わりに`1`か`0`を返します。これは、Vim 983 | scriptでは`1`は真で`0`は偽になるため問題ありません。 984 | 次のようなことが可能です。: 985 | 986 | > 987 | if has('nvim') 988 | " do something... 989 | endif 990 | < 991 | 992 | しかし、Luaで偽になるのは`false`と`nil`のみで、数値は値に関係なく常に`true`と評価されます。 993 | 明示的に`1`か`0`かをチェックする必要があります。: 994 | 995 | > 996 | if vim.fn.has('nvim') == 1 then 997 | -- do something... 998 | end 999 | < 1000 | 1001 | ============================================================================== 1002 | マッピングを定義する 1003 | *luaguide-defining-mappings* 1004 | 1005 | API関数~ 1006 | 1007 | Neovimはマッピングを設定、取得、削除するためのAPI関数を提供します。: 1008 | 1009 | - グローバルマッピング: 1010 | - `vim.api.nvim_set_keymap()` 1011 | - `vim.api.nvim_get_keymap()` 1012 | - `vim.api.nvim_del_keymap()` 1013 | - バッファローカルマッピング: 1014 | - `vim.api.nvim_buf_set_keymap()` 1015 | - `vim.api.nvim_buf_get_keymap()` 1016 | - `vim.api.nvim_buf_del_keymap()` 1017 | 1018 | `vim.api.nvim_set_keymap()`と`vim.api.nvim_buf_set_keymap()`から始めましょう。 1019 | 1020 | 最初の引数には有効にするモードの名前を含む文字列を渡します。: 1021 | 1022 | 1023 | | String value | Help page | Affected modes | Vimscript equivalent | 1024 | | ---------------------- | ------------- | ---------------------------------------- | -------------------- | 1025 | | `''` (an empty string) | `mapmode-nvo` | Normal, Visual, Select, Operator-pending | `:map` | 1026 | | `'n'` | `mapmode-n` | Normal | `:nmap` | 1027 | | `'v'` | `mapmode-v` | Visual and Select | `:vmap` | 1028 | | `'s'` | `mapmode-s` | Select | `:smap` | 1029 | | `'x'` | `mapmode-x` | Visual | `:xmap` | 1030 | | `'o'` | `mapmode-o` | Operator-pending | `:omap` | 1031 | | `'!'` | `mapmode-ic` | Insert and Command-line | `:map!` | 1032 | | `'i'` | `mapmode-i` | Insert | `:imap` | 1033 | | `'l'` | `mapmode-l` | Insert, Command-line, Lang-Arg | `:lmap` | 1034 | | `'c'` | `mapmode-c` | Command-line | `:cmap` | 1035 | | `'t'` | `mapmode-t` | Terminal | `:tmap` | 1036 | 1037 | 2つ目の引数は、左側のマッピングを含む文字列(マッピングで定義されたコマンドを起動するためのキー)です。 1038 | 空の文字列は``と同じで、キーを無効にします。 1039 | 1040 | 3つ目の引数は、右側のマッピングを含む文字列(実行するコマンド)です。 1041 | 1042 | 最後の引数は、|:map-arguments| で定義されているbool型のオプションのテーブルです(`noremap`を含み、`buffer`を除く)。 1043 | Neovim 0.7.0から、マッピング実行時、右側のマッピングの代わりに `callback` オプションに渡した関数を呼び出せます。 1044 | 1045 | バッファローカルなマッピングは、バッファ番号を引数の最初に受け取ります(`0`を指定した場合、カレントバッファです)。 1046 | 1047 | > 1048 | vim.api.nvim_set_keymap('n', '', ':set hlsearch!', 1049 | { noremap = true, silent = true }) 1050 | -- :nnoremap :set hlsearch 1051 | vim.api.nvim_set_keymap('n', 'tegf', [[lua 1052 | require('telescope.builtin').git_files()]], { noremap = true, 1053 | silent = true }) 1054 | -- :nnoremap tegf lua 1055 | require('telescope.builtin').git_files() 1056 | 1057 | vim.api.nvim_buf_set_keymap(0, '', 'cc', 'line(".") == 1 ? "cc" : 1058 | "ggcc"', { noremap = true, expr = true }) 1059 | -- :noremap cc line('.') == 1 ? 'cc' : 'ggcc' 1060 | 1061 | vim.api.nvim_set_keymap('n', 'ex', '', { 1062 | noremap = true, 1063 | callback = function() 1064 | print('My example') 1065 | end, 1066 | -- Lua関数は便利な文字列表現を持っていないため、 1067 | -- "desc" オプションを使用してマッピングの説明を記入できます。 1068 | desc = 'Prints "My example" in the message area', 1069 | }) 1070 | < 1071 | 1072 | `vim.api.nvim_get_keymap()`は、モードの省略名(上記の表を参照)を含む文字列を受け取ります。 1073 | そのモードにあるすべてのグローバルマッピングのテーブルを返します。 1074 | 1075 | > 1076 | print(vim.inspect(vim.api.nvim_get_keymap('n'))) 1077 | -- :verbose nmap 1078 | < 1079 | 1080 | `vim.api.nvim_buf_get_keymap()`は、最初の引数に追加でバッファ番号を受け取ります(`0`を指定した場合、カレントバッファです)。 1081 | 1082 | > 1083 | print(vim.inspect(vim.api.nvim_buf_get_keymap(0, 'i'))) 1084 | -- :verbose imap 1085 | < 1086 | 1087 | `vim.api.nvim_del_keymap()`は、モードと左側のマッピングを受け取ります。 1088 | 1089 | > 1090 | vim.api.nvim_del_keymap('n', '') 1091 | -- :nunmap 1092 | < 1093 | 1094 | この場合でも、`vim.api.nvim_buf_del_keymap()`は最初の引数にバッファ番号を受け取ります。`0`を指定した場合、カレントバッファです。 1095 | 1096 | > 1097 | vim.api.nvim_buf_del_keymap(0, 'i', '') 1098 | -- :iunmap 1099 | < 1100 | 1101 | vim.keymap~ 1102 | 1103 | :警告: このセクションで説明するAPI関数はNeovim 1104 | 0.7.0+のみで使用できます。 1105 | 1106 | Neovimはマッピングを設定/削除できる2つの関数を提供します: 1107 | - |vim.keymap.set()| 1108 | - |vim.keymap.del()| 1109 | 1110 | これらは、上記の類似API関数に糖類構文を追加したようなものです。 1111 | 1112 | `vim.keymap.set()` 1113 | は最初の引数として文字列を受け取ります。 1114 | また、複数のモードのマッピングを1度に定義するため、文字列のテーブルを受け取ることもできます: 1115 | 1116 | > 1117 | vim.keymap.set('n', 'ex1', 'lua vim.notify("Example 1118 | 1")') 1119 | vim.keymap.set({'n', 'c'}, 'ex2', 'lua 1120 | vim.notify("Example 2")') 1121 | < 1122 | 1123 | 2つ目の引数は左側のマッピングです。 1124 | 1125 | 3つ目の引数は右側のマッピングで、文字列かLua関数を受け取れます。 1126 | 1127 | > 1128 | vim.keymap.set('n', 'ex1', 'echomsg "Example 1"') 1129 | vim.keymap.set('n', 'ex2', function() print("Example 2") end) 1130 | vim.keymap.set('n', 'pl1', require('plugin').plugin_action) 1131 | -- モジュールの読み込みによる起動コストを避けるため、 1132 | -- マッピングを呼び出したときにモジュールの遅延読みこみができるように関数でラップすることができます。: 1133 | vim.keymap.set('n', 'pl2', function() require('plugin').plugin_action() end) 1134 | < 1135 | 1136 | 4つ目の引数)省略可能)はオプションのテーブルで、 `vim.api.nvim_set_keymap` 1137 | に渡されるオプションに対応しており、いくつか追加項目があります 1138 | (|vim.keymap.set()|にhttps://neovim.io/doc/user/lua.html#vim.keymap.setに一覧があります)。 1139 | 1140 | > 1141 | vim.keymap.set('n', 'ex1', 'echomsg "Example 1"', 1142 | {buffer = true}) 1143 | vim.keymap.set('n', 'ex2', function() print('Example 2') 1144 | end, {desc = 'Prints "Example 2" to the message area'}) 1145 | < 1146 | 文字列を使用して定義するキーマップとLua関数で定義したキーマップは違います。 1147 | 通常の`:nmap ex1`のようなキーマップ情報を表示する方法では、 1148 | `Lua function` とだけ表示され有用な情報(関数の内容自体)が表示されません。 1149 | キーマップの動作を説明する`desc`キーを追加するのを推奨します。 1150 | これはプラグインのマッピングのドキュメント化に特に重要です。 1151 | ユーザーはキーマップの使用方法をより簡単に理解できます。 1152 | 1153 | このAPIが面白いところとして、Vimのマッピングの歴史的な癖をいくつか解消しています。 1154 | - `rhs` が `` マッピングである場合以外、デフォルトで `noremap` です。 1155 | このため、マッピングが再帰的であるかを考える必要はあまりないです。 1156 | 1157 | > 1158 | vim.keymap.set('n', 'test1', 'echo "test"') 1159 | -- :nnoremap test echo "test" 1160 | 1161 | -- マッピングを再帰的に行ないたい場合は、 `remap` 1162 | オプションを `true` にします 1163 | vim.keymap.set('n', '>', ']', {remap = true}) 1164 | -- :nmap > ] 1165 | 1166 | -- マッピングは再帰的でないと機能しませんが、 vim.keymap.set() は自動的に処理します 1167 | vim.keymap.set('n', 'plug', '(plugin)') 1168 | -- :nmap plug (plugin) 1169 | < 1170 | 1171 | - `expr` マッピングが有効なら、 Lua関数が返す文字列に対して `nvim_replace_termcodes()` が自動的に適用されます: 1172 | 1173 | > 1174 | vim.keymap.set('i', '', function() 1175 | return vim.fn.pumvisible == 1 and '' or '' 1176 | end, {expr = true}) 1177 | < 1178 | 1179 | 参照: 1180 | - `:help recursive_mapping`: 1181 | https://neovim.io/doc/user/map.html#recursive_mapping 1182 | 1183 | `vim.keymap.del()` も同じように機能しますが、マッピングを削除します: 1184 | 1185 | > 1186 | vim.keymap.del('n', 'ex1') 1187 | vim.keymap.del({'n', 'c'}, 'ex2', {buffer = true}) 1188 | < 1189 | 1190 | ============================================================================== 1191 | ユーザーコマンドを定義する 1192 | *luaguide-defining-user-commands* 1193 | 1194 | WARNING: このセクションで説明するAPI関数はNeovim 0.7.0+のみで使用できます。 1195 | 1196 | Neovimはユーザーコマンドを作成するAPI関数を提供します。 1197 | 1198 | - Global user commands: 1199 | - |nvim_create_user_command()| 1200 | - |nvim_del_user_command()| 1201 | - Buffer-local user commands: 1202 | - |nvim_buf_create_user_command()| 1203 | - |nvim_buf_del_user_command()| 1204 | 1205 | まず `vim.api.nvim_create_user_command()` から始めます 1206 | 1207 | 最初の引数はコマンドの名前です(名前は大文字で始める必要があります)。 1208 | 1209 | 2つめの引数はコマンドが呼びだされたときに実行するコードです。次のどちらかでコードを指定できます: 1210 | 1211 | 文字列(この場合、VimScriptとして実行されます)。 1212 | `:commands` のように、``, `` などのエスケープシーケンスを使用できます。 1213 | > 1214 | vim.api.nvim_create_user_command('Upper', 'echo toupper()', { 1215 | nargs = 1 }) 1216 | -- :command! -nargs=1 Upper echo toupper() 1217 | 1218 | vim.cmd('Upper hello world') -- prints "HELLO WORLD" 1219 | < 1220 | 1221 | もしくは、Lua関数。 1222 | 通常のエスケープシーケンスによって提供されるデータを含む、 辞書のようなテーブルを受け取ります 1223 | (利用できるキーのリストは|nvim_create_user_command()|で確認できます)。 1224 | > 1225 | vim.api.nvim_create_user_command( 1226 | 'Upper', 1227 | function(opts) 1228 | print(string.upper(opts.args)) 1229 | end, 1230 | { nargs = 1 } 1231 | ) 1232 | < 1233 | 1234 | 3つめの引数はコマンドの属性をテーブルとして渡せます(|command-attributes|を参照)。 1235 | `vim.api.nvim_buf_create_user_command()`を使用すればバッファローカルなユーザーコマンドを定義できるため、 1236 | `-buffer`は有効な属性ではありません。 1237 | 1238 | 追加された2つの属性: 1239 | - `desc`はLuaのコールバックとして定義されたコマンドに対して`:command {cmd}`を実行したときの表示内容を制御できます。 1240 | キーマップと同様、Lua関数として定義するコマンドには `desc`キーを追加するのを推奨します。 1241 | - `force`は`:command!`を呼び出すのと同じで、同じ名前のユーザーコマンドが既に存在する場合、そのコマンドを置き換えます。 1242 | Vimscriptとは異なり、デフォルトでtrueです。 1243 | 1244 | `-complete`属性は|:command-complete|に記載されている属性に加え、Lua関数を取ることができます。 1245 | 1246 | > 1247 | vim.api.nvim_create_user_command('Upper', function() end, { 1248 | nargs = 1, 1249 | complete = function(ArgLead, CmdLine, CursorPos) 1250 | -- return completion candidates as a list-like table 1251 | return { 'foo', 'bar', 'baz' } 1252 | end, 1253 | }) 1254 | < 1255 | 1256 | バッファローカルなユーザーコマンドも第1引数にバッファ番号を受け取ります。 1257 | 現在のバッファ用のコマンドを定義することができる`-buffer`より、これは便利です。 1258 | 1259 | > 1260 | vim.api.nvim_buf_create_user_command(4, 'Upper', function() end, {}) 1261 | < 1262 | 1263 | `vim.api.nvim_del_user_command()` はコマンド名を受け取ります。 1264 | 1265 | > 1266 | vim.api.nvim_del_user_command('Upper') 1267 | -- :delcommand Upper 1268 | < 1269 | 1270 | ここでも、`vim.api.nvim_buf_del_user_command()`はバッファ番号を第1引数として受け取り、`0`は現在のバッファを表します。 1271 | 1272 | > 1273 | vim.api.nvim_buf_del_user_command(4, 'Upper') 1274 | < 1275 | 1276 | 参照: 1277 | - |nvim_create_user_command()| 1278 | - |40.2| 1279 | - |command-attributes| 1280 | 1281 | 警告~ 1282 | 1283 | `-complete=custom`属性は自動的に補完候補をフィルタリングし、 1284 | ワイルドカード(|wildcard|)をサポートする機能を組み込みます: 1285 | 1286 | > 1287 | function! s:completion_function(ArgLead, CmdLine, CursorPos) abort 1288 | return join([ 1289 | \ 'strawberry', 1290 | \ 'star', 1291 | \ 'stellar', 1292 | \ ], "\n") 1293 | endfunction 1294 | 1295 | command! -nargs=1 -complete=custom,s:completion_function Test echo 1296 | 1297 | " `:Test st[ae]` と入力すると "star" と "stellar" を返します 1298 | < 1299 | 1300 | `complete` にLua関数に渡すと、ユーザーにフィルタ方法を任せる`customlist`のような動作をします。 1301 | 1302 | > 1303 | vim.api.nvim_create_user_command('Test', function() end, { 1304 | nargs = 1, 1305 | complete = function(ArgLead, CmdLine, CursorPos) 1306 | return { 1307 | 'strawberry', 1308 | 'star', 1309 | 'stellar', 1310 | } 1311 | end, 1312 | }) 1313 | 1314 | -- 候補リストをフィルタしてないので `:Test z` と入力すると全ての補完候補を返します 1315 | < 1316 | 1317 | ============================================================================== 1318 | オートコマンドを定義する 1319 | *luaguide-defining-autocommands* 1320 | 1321 | (この章は現在作成中です) 1322 | 1323 | Neovim 0.7.0はオートコマンド用のAPI関数を持っています。詳細は|api-autocmd|を参照してください。 1324 | 1325 | - Pull request #14661: https://github.com/neovim/neovim/pull/14661 (lua: autocmds take 2) 1326 | 1327 | ============================================================================== 1328 | ハイライトを定義する 1329 | *luaguide-defining-syntax-highlights* 1330 | 1331 | (この章は現在作成中です) 1332 | 1333 | Neovim 0.7.0はハイライトグループ用のAPI関数を持っています。 1334 | 1335 | 参照: 1336 | - |nvim_set_hl()| 1337 | - |nvim_get_hl_by_id()| 1338 | - |nvim_get_hl_by_name()| 1339 | 1340 | ============================================================================== 1341 | 一般的なTipsと推奨 1342 | *luaguide-general-tips-and-recommendations* 1343 | 1344 | 1345 | キャッシュされたモジュールのリロード~ 1346 | 1347 | Luaでは、`require()`関数がモジュールをキャッシュします。 1348 | これはパフォーマンスには良いですが、後から`require()`を呼んでもモジュールは更新されないため少し面倒です。 1349 | 1350 | 特定のモジュールのキャッシュを更新する場合、`package.loaded`グローバルテーブルを変更する必要があります。: 1351 | 1352 | > 1353 | package.loaded['modname'] = nil 1354 | require('modname') -- 新しい'modname'モジュールを読み込みます 1355 | < 1356 | 1357 | nvim-lua/plenary.nvim: https://github.com/nvim-lua/plenary.nvim には、これを行う関数: 1358 | https://github.com/nvim-lua/plenary.nvim/blob/master/lua/plenary/reload.lua があります。 1359 | 1360 | Luaの文字列をパディングしないでください!~ 1361 | 1362 | 二重括弧の文字列を使用するとき、パディングの誘惑に負けないでください! 1363 | スペースを無視するときは問題ないですが、スペースが重要な意味を持つときはデバックが困難な問題の原因になる可能性があります。: 1364 | 1365 | > 1366 | vim.api.nvim_set_keymap('n', 'f', [[ call foo() 1367 | ]], {noremap = true}) 1368 | < 1369 | 1370 | 上記の例では、`f`は`call foo()`ではなく`call foo()`にマッピングされます。 1371 | 1372 | Vim script <--> Lua 型変換の注意~ 1373 | 1374 | 1375 | 変数を変換するとコピーが作られます:~ 1376 | 1377 | VimからLua、LuaからVimのオブジェクトの参照を直接操作できません。 1378 | 例えば、Vim scriptの`map()`は変数をその場で変更します(破壊的)。 1379 | 1380 | > 1381 | let s:list = [1, 2, 3] 1382 | let s:newlist = map(s:list, {_, v -> v * 2}) 1383 | 1384 | echo s:list 1385 | " [2, 4, 6] 1386 | echo s:newlist 1387 | " [2, 4, 6] 1388 | echo s:list is# s:newlist 1389 | " 1 1390 | < 1391 | 1392 | Luaからこの関数を使用すると、代りにコピーが作られます 1393 | 1394 | > 1395 | local tbl = {1, 2, 3} 1396 | local newtbl = vim.fn.map(tbl, function(_, v) return v * 2 end) 1397 | 1398 | print(vim.inspect(tbl)) -- { 1, 2, 3 } 1399 | print(vim.inspect(newtbl)) -- { 2, 4, 6 } 1400 | print(tbl == newtbl) -- false 1401 | < 1402 | 1403 | 変換を常にできるとは限りません~ 1404 | 1405 | これは主に関数とテーブルに影響します。 1406 | 1407 | Luaのリストと辞書が混在するテーブルは変換できません。 1408 | 1409 | > 1410 | print(vim.fn.count({1, 1, number = 1}, 1)) 1411 | -- E5100: Cannot convert given lua table: table should either have a sequence of positive integer keys or contain only string keys 1412 | < 1413 | 1414 | Luaで`vim.fn`を使用してVim関数を呼べますが、それらの参照を保持できません。 1415 | それは不測の動作の原因になります。: 1416 | 1417 | > 1418 | local FugitiveHead = vim.fn.funcref('FugitiveHead') 1419 | print(FugitiveHead) -- vim.NIL 1420 | 1421 | vim.cmd("let g:test_dict = {'test_lambda': {-> 1}}") 1422 | print(vim.g.test_dict.test_lambda) -- nil 1423 | print(vim.inspect(vim.g.test_dict)) -- {} 1424 | < 1425 | 1426 | Luaの関数をVimの関数に渡せますが、Vimの変数に格納できません。 1427 | (Neovim 0.7.0+で修正されて、格納できるようになりました。) 1428 | 1429 | 1430 | > 1431 | -- This works: 1432 | vim.fn.jobstart({'ls'}, { 1433 | on_stdout = function(chan_id, data, name) 1434 | print(vim.inspect(data)) 1435 | end 1436 | }) 1437 | 1438 | -- This doesn't: 1439 | vim.g.test_dict = {test_lambda = function() return 1 end} -- Error: Cannot convert given lua type 1440 | < 1441 | 1442 | ただし、Vim scriptから`luaeval()`を使用して同じことをすると**動作します**。: 1443 | 1444 | > 1445 | let g:test_dict = {'test_lambda': luaeval('function() return 1 end')} 1446 | echo g:test_dict 1447 | " {'test_lambda': function('4714')} 1448 | < 1449 | 1450 | Vim booleans~ 1451 | Vim scriptの一般的なパターンではbool値の代わりに`1`と`0`を使用します。 1452 | 実際、Vimにはバージョン7.4.1154まで区別されたbool型がありませんでした。 1453 | 1454 | Luaのbool値は数値ではなく、Vim scriptの実際のbool値に変換されます。: 1455 | 1456 | > 1457 | lua vim.g.lua_true = true 1458 | echo g:lua_true 1459 | " v:true 1460 | lua vim.g.lua_false = false 1461 | echo g:lua_false 1462 | " v:false 1463 | < 1464 | 1465 | リンターと言語サーバーの設定~ 1466 | 1467 | Luaのプロジェクトでリンターや言語サーバーを使用して、診断と自動補完を利用している場合、Neovim固有の設定が必要になる場合があります。人気のあるツールの推奨設定は次のとおりです。: 1468 | 1469 | luacheck~ 1470 | 1471 | 次の設定を `~/.luacheckrc` もしくは `$XDG_CONFIG_HOME/luacheck/.luacheckrc` に配置すれば、 luacheck: https://github.com/mpeterv/luacheck/ でvimモジュールを認識できます。: 1472 | 1473 | 1474 | > 1475 | globals = { 1476 | "vim", 1477 | } 1478 | < 1479 | 1480 | 言語サーバーの Alloyed/lua-lsp: https://github.com/Alloyed/lua-lsp/ は `luacheck` を使用してリンティングを提供し、同じファイルを読み込みます。 1481 | 1482 | `luacheck` の設定方法の詳細は ドキュメント: https://luacheck.readthedocs.io/en/stable/config.html を参照してください。 1483 | 1484 | sumneko/lua-language-server~ 1485 | 1486 | nvim-lspconfig: https://github.com/neovim/nvim-lspconfig/ リポジトリに sumneko/lua-language-serverの設定方法: https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#sumneko_lua があります。例は組込みのLSPクライアントを使っていますが、他のLSPクライアントでも同じ設定である必要があります。 1487 | 1488 | sumneko/lua-language-server: https://github.com/sumneko/lua-language-server/ の設定方法の詳細は "Setting": https://github.com/sumneko/lua-language-server/wiki/Setting を見てください。 1489 | 1490 | coc.nvim~ 1491 | 1492 | coc.nvim: https://github.com/neoclide/coc.nvim/ の補完ソースである rafcamlet/coc-nvim-lua: https://github.com/rafcamlet/coc-nvim-lua/ はNeovim stdlibの項目を提供しています。 1493 | 1494 | Luaコードのデバッグ~ 1495 | 1496 | 別のNeovimインスタンスで実行しているLuaコードを jbyuki/one-small-step-for-vimkind: 1497 | https://github.com/jbyuki/one-small-step-for-vimkind でデバッグできます。 1498 | 1499 | このプラグインは Debug Adapter Protocol: https://microsoft.github.io/debug-adapter-protocol/ を使用しています。 1500 | デバッグアダプターに接続するには、 mfussenegger/nvim-dap: https://github.com/mfussenegger/nvim-dap/ や 1501 | puremourning/vimspector: https://github.com/puremourning/vimspector/ のようなDAPクライアントが必要です。 1502 | 1503 | Luaマッピング/コマンド/オートコマンドのデバッグ~ 1504 | 1505 | マッピング/コマンド/オートコマンドが定義されている位置を `:verbose` コマンドで確認できます: 1506 | 1507 | > 1508 | :verbose map m 1509 | < 1510 | 1511 | > 1512 | n m_ * echo 'example' 1513 | Last set from ~/.config/nvim/init.vim line 26 1514 | < 1515 | 1516 | デフォルトでは、Luaのパフォーマンス上の理由でこの機能は無効です。 1517 | Neovim起動時にverboseのレベルが0より上なら、この機能を有効にできます: 1518 | 1519 | > 1520 | nvim -V1 1521 | < 1522 | 1523 | 参照: 1524 | - |'verbose'| 1525 | - |-V| 1526 | - neovim/neovim#15079: https://github.com/neovim/neovim/pull/15079 1527 | 1528 | Luaコードのテスト~ 1529 | 1530 | - plenary.nvim: test harness: 1531 | https://github.com/nvim-lua/plenary.nvim/#plenarytest_harness 1532 | - notomo/vusted: https://github.com/notomo/vusted 1533 | 1534 | Luarocksパッケージを使用する~ 1535 | 1536 | wbthomason/packer.nvim: https://github.com/wbthomason/packer.nvim はLuarocksパッケージをサポートしています。 1537 | 使い方はREADME: https://github.com/wbthomason/packer.nvim/#luarocks-support にあります。 1538 | 1539 | ============================================================================== 1540 | その他 1541 | *luaguide-miscellaneous* 1542 | 1543 | vim.loop~ 1544 | 1545 | `vim.loop`はLibUV 1546 | APIを公開するモジュールです。いくつかのリソース: 1547 | 1548 | - Official documentation for LibUV: https://docs.libuv.org/en/v1.x/ 1549 | - Luv documentation: https://github.com/luvit/luv/blob/master/docs.md 1550 | - teukka.tech - Using LibUV in Neovim: https://teukka.tech/posts/2020-01-07-vimloop/ 1551 | 1552 | 参照: 1553 | - |vim.loop| 1554 | 1555 | vim.lsp~ 1556 | 1557 | `vim.lsp`は組込みのLSPクライアントを操作するためのモジュールです。 1558 | neovim/nvim-lspconfig: https://github.com/neovim/nvim-lspconfig/ 1559 | は有名なLanguage Serverの設定集です。 1560 | 1561 | クライアントの動作は"lsp-handlers"を使用して設定できます。詳細はこちら: 1562 | - |lsp-handler| 1563 | - neovim/neovim#12655: https://github.com/neovim/neovim/pull/12655 1564 | - How to migrate from diagnostic-nvim: 1565 | https://github.com/nvim-lua/diagnostic-nvim/issues/73#issue-737897078 1566 | 1567 | 1568 | LSPクライアントを利用したプラグインも見たいかもしれません。: 1569 | https://github.com/rockerBOO/awesome-neovim#lsp 1570 | 1571 | 参照: 1572 | - |lsp| 1573 | 1574 | vim.treesitter~ 1575 | 1576 | `vim.treesitter`はNeovim内の Tree-sitter: 1577 | https://tree-sitter.github.io/tree-sitter/ 1578 | ライブラリを操作するためのモジュールです。 1579 | Tree-sitterについてもっと知りたいなら、この 1580 | プレゼン 38:37 : https://www.youtube.com/watch?v=Jes3bD6P0To 1581 | に興味があるかもしれません。 1582 | 1583 | nvim-treesitter: https://github.com/nvim-treesitter/ 1584 | オリジネーションは、ライブラリを利用して様々なプラグインをホストしています。 1585 | 1586 | 参照: 1587 | - |lua-treesitter| 1588 | 1589 | トランスパイラ~ 1590 | 1591 | Luaを使用する利点の1つは実際にLuaを書く必要がないことです!利用できるトランスパイラはたくさんあります。 1592 | 1593 | - Moonscript: https://moonscript.org/ 1594 | 1595 | おそらく、最も知られているLuaのトランスパイラです。クラス、リスト内包表記、関数リテラルなどの便利な機能を多数追加します。 1596 | svermeulen/nvim-moonmaker: https://github.com/svermeulen/nvim-moonmaker 1597 | はNeovimのプラグインと設定をMoonscriptで直接書けるようにします。 1598 | 1599 | - Fennel: https://fennel-lang.org/ 1600 | 1601 | lispをLuaにコンパイルします。 1602 | Olical/aniseed: https://github.com/Olical/aniseed 1603 | または、Hotpot: https://github.com/rktjmp/hotpot.nvim 1604 | を使用するとNeovimのプラグインと設定を書くことができます。 1605 | さらに、 Olical/conjure: https://github.com/Olical/conjure 1606 | は対話的な開発環境を提供します 他の言語の中で 。 1607 | 1608 | - Teal: https://github.com/teal-language/tl 1609 | 1610 | Tealの名前の由来はTL(typed lua)の発音からです。 1611 | まさにその通りで、強力な型をLuaに追加し、それ以外は標準のLuaの構文に近づけています。 1612 | nvim-teal-maker https://github.com/svermeulen/nvim-teal-maker プラグインを使用して、 1613 | TealでNeovimプラグインや設定ファイルを書けます。 1614 | 1615 | その他の興味深いプロジェクト: 1616 | - TypeScriptToLua/TypeScriptToLua: 1617 | https://github.com/TypeScriptToLua/TypeScriptToLua 1618 | - Haxe: https://haxe.org/ 1619 | - SwadicalRag/wasm2lua: https://github.com/SwadicalRag/wasm2lua 1620 | - hengestone/lua-languages: https://github.com/hengestone/lua-languages 1621 | 1622 | vim:tw=78:ts=8:noet:ft=help:norl: 1623 | -------------------------------------------------------------------------------- /doc/nvim-lua-guide.txt: -------------------------------------------------------------------------------- 1 | *nvim-lua-guide.txt* Getting started using Lua in Neovim 2 | 3 | ============================================================================== 4 | INTRODUCTION 5 | *luaguide-introduction* 6 | 7 | The integration of Lua: https://www.youtube.com/watch?v=IP3J56sKtn0 8 | as a first-class language inside Neovim: 9 | https://github.com/neovim/neovim/wiki/FAQ#why-embed-lua-instead-of-x 10 | is shaping up to be one of its killer features. 11 | However, the amount of teaching material for learning how to write 12 | plugins in Lua is not as large as what you would find for writing them 13 | in Vimscript. This is an attempt at providing some basic information to 14 | get people started. 15 | 16 | This guide assumes you are using at least version 0.5 of Neovim. 17 | 18 | Learning Lua~ 19 | 20 | If you are not already familiar with the language, there are plenty of 21 | resources to get started: 22 | 23 | - The Learn X in Y minutes page about Lua: 24 | https://learnxinyminutes.com/docs/lua/ should give you a quick overview 25 | of the basics 26 | - This guide: 27 | https://github.com/medwatt/Notes/blob/main/Lua/Lua_Quick_Guide.ipynb 28 | is also a good resource for getting started quickly 29 | - If videos are more to your liking, Derek Banas has a 1-hour tutorial 30 | on the language: https://www.youtube.com/watch?v=iMacxZQMPXs 31 | - Want something a little more interactive with runnable examples? Try 32 | the LuaScript tutorial: https://www.luascript.dev/learn 33 | - The lua-users wiki: http://lua-users.org/wiki/LuaDirectory is full 34 | of useful information on all kinds of Lua-related topics 35 | - The official reference manual for Lua: https://www.lua.org/manual/5.1/ 36 | should give you the most comprehensive tour of the language exists as 37 | a Vimdoc plugin if you want to read it from the comfort of your editor: 38 | milisims/nvim-luaref: https://github.com/milisims/nvim-luaref 39 | 40 | It should also be noted that Lua is a very clean and simple language. It 41 | is easy to learn, especially if you have experience with similar scripting 42 | languages like JavaScript. You may already know more Lua than you realise! 43 | 44 | Note: the version of Lua that Neovim embeds is LuaJIT: 45 | https://staff.fnwi.uva.nl/h.vandermeer/docs/lua/luajit/luajit_intro.html 46 | 2.1.0, which maintains compatibility with Lua 5.1. 47 | 48 | Existing tutorials for writing Lua in Neovim~ 49 | 50 | A few tutorials have already been written to help people write plugins 51 | in Lua. Some of them helped quite a bit when writing this guide. Many 52 | thanks to their authors. 53 | 54 | - teukka.tech - From init.vim to init.lua: 55 | https://teukka.tech/luanvim.html 56 | - dev.to - How to write neovim plugins in Lua: 57 | https://dev.to/2nit/how-to-write-neovim-plugins-in-lua-5cca 58 | - dev.to - How to make UI for neovim plugins in Lua: 59 | https://dev.to/2nit/how-to-make-ui-for-neovim-plugins-in-lua-3b6e 60 | - ms-jpq - Neovim Async Tutorial: 61 | https://github.com/ms-jpq/neovim-async-tutorial 62 | - oroques.dev - Neovim 0.5 features and the switch to init.lua: 63 | https://oroques.dev/notes/neovim-init/ 64 | - Building A Vim Statusline from Scratch - jdhao's blog: 65 | https://jdhao.github.io/2019/11/03/vim_custom_statusline/ 66 | - Configuring Neovim using Lua: https://icyphox.sh/blog/nvim-lua/ 67 | - Devlog | Everything you need to know to configure neovim using lua: 68 | https://vonheikemen.github.io/devlog/tools/configuring-neovim-using-lua/ 69 | 70 | Companion plugins~ 71 | 72 | - Vimpeccable: https://github.com/svermeulen/vimpeccable - Plugin to 73 | help write your .vimrc in Lua 74 | - plenary.nvim: https://github.com/nvim-lua/plenary.nvim - All the 75 | lua functions I don't want to write twice 76 | - popup.nvim: https://github.com/nvim-lua/popup.nvim - An implementation 77 | of the Popup API from vim in Neovim 78 | - nvim_utils: https://github.com/norcalli/nvim_utils 79 | - nvim-luadev: https://github.com/bfredl/nvim-luadev - REPL/debug 80 | console for nvim lua plugins 81 | - nvim-luapad: https://github.com/rafcamlet/nvim-luapad - Interactive 82 | real time neovim scratchpad for embedded lua engine 83 | - nlua.nvim: https://github.com/tjdevries/nlua.nvim - Lua Development 84 | for Neovim 85 | - BetterLua.vim: https://github.com/euclidianAce/BetterLua.vim - 86 | Better Lua syntax highlighting in Vim/NeoVim 87 | 88 | ============================================================================== 89 | WHERE TO PUT LUA FILES 90 | *luaguide-where-to-put-lua-files* 91 | 92 | init.lua~ 93 | 94 | Neovim supports loading an `init.lua` file for configuration instead of 95 | the usual `init.vim`. 96 | 97 | Note: `init.lua` is of course _completely_ optional. Support 98 | for `init.vim` is not going away and is still a valid option for 99 | configuration. Do keep in mind that some features are not 100% exposed 100 | to Lua yet. 101 | 102 | See also: 103 | - |config| 104 | 105 | Modules~ 106 | 107 | Lua modules are found inside a `lua/` folder in your `'runtimepath'` 108 | (for most users, this will mean `~/.config/nvim/lua` on \*nix systems 109 | and `~/AppData/Local/nvim/lua` on Windows). You can `require()` files 110 | in this folder as Lua modules. 111 | 112 | Let's take the following folder structure as an example: 113 | 114 | > 115 | 📂 ~/.config/nvim 116 | ├── 📁 after 117 | ├── 📁 ftplugin 118 | ├── 📂 lua 119 | │ ├── 🌑 myluamodule.lua 120 | │ └── 📂 other_modules 121 | │ ├── 🌑 anothermodule.lua 122 | │ └── 🌑 init.lua 123 | ├── 📁 pack 124 | ├── 📁 plugin 125 | ├── 📁 syntax 126 | └── 🇻 init.vim 127 | < 128 | 129 | The following Lua code will load `myluamodule.lua`: 130 | 131 | > 132 | require('myluamodule') 133 | < 134 | 135 | Notice the absence of a `.lua` extension. 136 | 137 | Similarly, loading `other_modules/anothermodule.lua` is done like so: 138 | 139 | > 140 | require('other_modules.anothermodule') 141 | -- or 142 | require('other_modules/anothermodule') 143 | < 144 | 145 | Path separators are denoted by either a dot `.` or a slash `/`. 146 | 147 | A folder containing an `init.lua` file can be required directly, without 148 | having to specify the name of the file. 149 | 150 | > 151 | require('other_modules') -- loads other_modules/init.lua 152 | < 153 | 154 | Requiring a nonexistent module or a module which contains syntax errors 155 | aborts the currently executing script. 156 | `pcall()` may be used to prevent errors. 157 | 158 | > 159 | local ok, _ = pcall(require, 'module_with_error') 160 | if not ok then 161 | -- not loaded 162 | end 163 | < 164 | 165 | See also: 166 | - |lua-require| 167 | 168 | Tips~ 169 | 170 | Several Lua plugins might have identical filenames in their `lua/` 171 | folder. This could lead to namespace clashes. 172 | 173 | If two different plugins have a `lua/main.lua` file, then doing 174 | `require('main')` is ambiguous: which file do we want to source? 175 | 176 | It might be a good idea to namespace your config or your plugin with a 177 | top-level folder, like so: `lua/plugin_name/main.lua` 178 | 179 | Runtime files~ 180 | 181 | Much like Vimscript files, Lua files can be loaded automatically from 182 | special folders in your `runtimepath`. Currently, the following folders 183 | are supported: 184 | 185 | - `colors/` 186 | - `compiler/` 187 | - `ftplugin/` 188 | - `ftdetect/` 189 | - `indent/` 190 | - `plugin/` 191 | - `syntax/` 192 | 193 | Note: in a runtime directory, all `*.vim` files are sourced before 194 | `*.lua` files. 195 | 196 | See also: 197 | - |'runtimepath'| 198 | - |load-plugins| 199 | 200 | Tips~ 201 | 202 | Since runtime files aren't based on the Lua module system, two plugins 203 | can have a `plugin/main.lua` file without it being an issue. 204 | 205 | ============================================================================== 206 | USING LUA FROM VIMSCRIPT 207 | *luaguide-using-lua-from-vimscript* 208 | 209 | :lua~ 210 | 211 | This command executes a chunk of Lua code. 212 | 213 | > 214 | :lua require('myluamodule') 215 | < 216 | 217 | Multi-line scripts are possible using heredoc syntax: 218 | 219 | > 220 | echo "Here's a bigger chunk of Lua code" 221 | 222 | lua << EOF 223 | local mod = require('mymodule') 224 | local tbl = {1, 2, 3} 225 | 226 | for k, v in ipairs(tbl) do 227 | mod.method(v) 228 | end 229 | 230 | print(tbl) 231 | EOF 232 | < 233 | 234 | Note: each `:lua` command has its own scope and variables declared with 235 | the `local` keyword are not accessible outside of the command. This 236 | won't work: 237 | 238 | > 239 | :lua local foo = 1 240 | :lua print(foo) 241 | " prints 'nil' instead of '1' 242 | < 243 | 244 | Note 2: the `print()` function in Lua behaves similarly to the `:echomsg` 245 | command. Its output is saved in the message-history and can be suppressed 246 | by the `:silent` command. 247 | 248 | See also: 249 | 250 | - |:lua| 251 | - |:lua-heredoc| 252 | 253 | :luado~ 254 | 255 | This command executes a chunk of Lua code that acts on a range of lines 256 | in the current buffer. If no range is specified, the whole buffer is 257 | used instead. Whatever string is `return`ed from the chunk is used to 258 | determine what each line should be replaced with. 259 | 260 | The following command would replace every line in the current buffer 261 | with the text `hello world`: 262 | 263 | > 264 | :luado return 'hello world' 265 | < 266 | 267 | Two implicit `line` and `linenr` variables are also provided. `line` 268 | is the text of the line being iterated upon whereas `linenr` is its 269 | number. The following command would make every line whose number is 270 | divisible by 2 uppercase: 271 | 272 | > 273 | :luado if linenr % 2 == 0 then return line:upper() end 274 | < 275 | 276 | See also: 277 | 278 | - |:luado| 279 | 280 | Sourcing Lua files~ 281 | 282 | Neovim provides 3 Ex commands to source Lua files 283 | 284 | - `:luafile` 285 | - `:source` 286 | - `:runtime` 287 | 288 | `:luafile` and `:source` are very similar: 289 | 290 | > 291 | :luafile ~/foo/bar/baz/myluafile.lua 292 | :luafile % 293 | :source ~/foo/bar/baz/myluafile.lua 294 | :source % 295 | < 296 | 297 | `:source` also supports ranges, which can be useful to only execute part 298 | of a script: 299 | 300 | > 301 | :1,10source 302 | < 303 | 304 | `:runtime` is a little different: it uses the `'runtimepath'` option to 305 | determine which files to source. See |:runtime| for more details. 306 | 307 | See also: 308 | 309 | - |:luafile| 310 | - |:source| 311 | - |:runtime| 312 | 313 | Sourcing a lua file vs calling require():~ 314 | 315 | You might be wondering what the difference between calling the `require()` 316 | function and sourcing a Lua file is and whether you should prefer one 317 | way over the other. They have different use cases: 318 | 319 | - `require()`: 320 | - is a built-in Lua function. It allows you to take advantage of 321 | Lua's module system 322 | - searches for modules in `lua/` folders in your `'runtimepath'` 323 | - keeps track of what modules have been loaded and prevents a script 324 | from being parsed and executed a second time. If you change the file 325 | containing the code for a module and try to `require()` it a second 326 | time while Neovim is running, the module will not actually update 327 | - `:luafile`, `:source` and `:runtime`: 328 | - are Ex commands. They do not support modules 329 | - execute the contents of a script regardless of whether it has been 330 | executed before 331 | - `:luafile` and `:source` take a path that is either absolute or 332 | relative to the working directory of the current window 333 | - `:runtime` uses the `'runtimepath'` option to find files 334 | 335 | Files sourced via `:source`, `:runtime` or automatically from runtime 336 | directories will also show up in `:scriptnames` and `--startuptime` 337 | 338 | luaeval()~ 339 | 340 | This built-in Vimscript function evaluates a Lua expression string 341 | and returns its value. Lua data types are automatically converted to 342 | Vimscript types (and vice versa). 343 | 344 | > 345 | " You can store the result in a variable 346 | let variable = luaeval('1 + 1') 347 | echo variable 348 | " 2 349 | let concat = luaeval('"Lua".." is ".."awesome"') 350 | echo concat 351 | " 'Lua is awesome' 352 | 353 | " List-like tables are converted to Vim lists 354 | let list = luaeval('{1, 2, 3, 4}') 355 | echo list[0] 356 | " 1 357 | echo list[1] 358 | " 2 359 | " Note that unlike Lua tables, Vim lists are 0-indexed 360 | 361 | " Dict-like tables are converted to Vim dictionaries 362 | let dict = luaeval('{foo = "bar", baz = "qux"}') 363 | echo dict.foo 364 | " 'bar' 365 | 366 | " Same thing for booleans and nil 367 | echo luaeval('true') 368 | " v:true 369 | echo luaeval('nil') 370 | " v:null 371 | 372 | " You can create Vimscript aliases for Lua functions 373 | let LuaMathPow = luaeval('math.pow') 374 | echo LuaMathPow(2, 2) 375 | " 4 376 | let LuaModuleFunction = luaeval('require("mymodule").myfunction') 377 | call LuaModuleFunction() 378 | 379 | " It is also possible to pass Lua functions as values to Vim functions 380 | lua X = function(k, v) return string.format("%s:%s", k, v) end 381 | echo map([1, 2, 3], luaeval("X")) 382 | < 383 | 384 | `luaeval()` takes an optional second argument that allows you to pass 385 | data to the expression. You can then access that data from Lua using 386 | the magic global `_A`: 387 | 388 | > 389 | echo luaeval('_A[1] + _A[2]', [1, 1]) 390 | " 2 391 | 392 | echo luaeval('string.format("Lua is %s", _A)', 'awesome') 393 | " 'Lua is awesome' 394 | < 395 | 396 | See also: 397 | - |luaeval()| 398 | 399 | v:lua~ 400 | 401 | This global Vim variable allows you to call Lua functions in the global 402 | namespace `_G`: https://www.lua.org/manual/5.1/manual.html#pdf-_G 403 | directly from Vimscript. Again, Vim data types are converted to Lua 404 | types and vice versa. 405 | 406 | > 407 | call v:lua.print('Hello from Lua!') 408 | " 'Hello from Lua!' 409 | 410 | let scream = v:lua.string.rep('A', 10) 411 | echo scream 412 | " 'AAAAAAAAAA' 413 | 414 | " How about a nice statusline? 415 | lua << EOF 416 | function _G.statusline() 417 | local filepath = '%f' 418 | local align_section = '%=' 419 | local percentage_through_file = '%p%%' 420 | return string.format( 421 | '%s%s%s', 422 | filepath, 423 | align_section, 424 | percentage_through_file 425 | ) 426 | end 427 | EOF 428 | 429 | set statusline=%!v:lua.statusline() 430 | 431 | " Also works in expression mappings 432 | lua << EOF 433 | function _G.check_back_space() 434 | local col = vim.api.nvim_win_get_cursor(0)[2] 435 | return (col == 0 or vim.api.nvim_get_current_line():sub(col, 436 | col):match('%s')) and true 437 | end 438 | EOF 439 | 440 | inoremap 441 | \ pumvisible() ? "\" : 442 | \ v:lua.check_back_space() ? "\" : 443 | \ completion#trigger_completion() 444 | 445 | " Call a function from a Lua module by using single quotes and 446 | omitting parentheses: 447 | call v:lua.require'module'.foo() 448 | < 449 | 450 | See also: 451 | - |v:lua| 452 | - |v:lua-call| 453 | 454 | Caveats~ 455 | 456 | This variable can only be used to call functions. The following will 457 | always throw an error: 458 | 459 | > 460 | " Aliasing functions doesn't work 461 | let LuaPrint = v:lua.print 462 | 463 | " Accessing dictionaries doesn't work 464 | echo v:lua.some_global_dict['key'] 465 | 466 | " Using a function as a value doesn't work 467 | echo map([1, 2, 3], v:lua.global_callback) 468 | < 469 | 470 | Tips~ 471 | 472 | You can get Lua syntax highlighting inside .vim files by putting `let 473 | g:vimsyn_embed = 'l'` in your configuration file. See |g:vimsyn_embed| 474 | for more on this option. 475 | 476 | ============================================================================== 477 | THE VIM NAMESPACE 478 | *luaguide-the-vim-namespace* 479 | 480 | Neovim exposes a global `vim` variable which serves as an entry point 481 | to interact with its APIs from Lua. It provides users with an extended 482 | "standard library" of functions as well as various sub-modules. 483 | 484 | Some notable functions and modules include: 485 | 486 | - `vim.inspect`: transform Lua objects into human-readable strings 487 | (useful for inspecting tables) 488 | - `vim.regex`: use Vim regexes from Lua 489 | - `vim.api`: module that exposes API functions (the same API used by 490 | remote plugins) 491 | - `vim.ui`: overridable UI functions that can be leveraged by plugins 492 | - `vim.loop`: module that exposes the functionality of Neovim's event-loop 493 | (using LibUV) 494 | - `vim.lsp`: module that controls the built-in LSP client 495 | - `vim.treesitter`: module that exposes the functionality of the 496 | tree-sitter library 497 | 498 | This list is by no means comprehensive. If you wish to know more about what's 499 | made available by the `vim` variable, |lua-stdlib| and |lua-vim| are the way 500 | to go. Alternatively, you can do `:lua print(vim.inspect(vim))` to get a list 501 | of every module. API functions are documented under |api-global|. 502 | 503 | Tips~ 504 | 505 | Writing `print(vim.inspect(x))` every time you want to inspect the 506 | contents of an object can get pretty tedious. It might be worthwhile 507 | to have a global wrapper function somewhere in your configuration (in 508 | Neovim 0.7.0+, this function is built-in, see |vim.pretty_print()|: 509 | 510 | > 511 | function _G.put(...) 512 | local objects = {} 513 | for i = 1, select('#', ...) do 514 | local v = select(i, ...) 515 | table.insert(objects, vim.inspect(v)) 516 | end 517 | 518 | print(table.concat(objects, '\n')) 519 | return ... 520 | end 521 | < 522 | 523 | You can then inspect the contents of an object very quickly in your code 524 | or from the command-line: 525 | 526 | > 527 | put({1, 2, 3}) 528 | < 529 | 530 | > 531 | :lua put(vim.loop) 532 | < 533 | 534 | Alternatively, you can use the `:lua` command to pretty-print a Lua 535 | expression by prefixing it with `=` (Neovim 0.7+ only): 536 | > 537 | :lua =vim.loop 538 | < 539 | 540 | Additionally, you may find that built-in Lua functions are sometimes 541 | lacking compared to what you would find in other languages (for example 542 | `os.clock()` only returns a value in seconds, not milliseconds). Be 543 | sure to look at the Neovim stdlib (and `vim.fn`, more on that later), 544 | it probably has what you're looking for. 545 | 546 | ============================================================================== 547 | USING VIMSCRIPT FROM LUA 548 | *luaguide-using-vimscript-from-lua* 549 | 550 | vim.api.nvim_eval()~ 551 | 552 | This function evaluates a Vimscript expression string and returns its 553 | value. Vimscript data types are automatically converted to Lua types 554 | (and vice versa). 555 | 556 | It is the Lua equivalent of the `luaeval()` function in Vimscript 557 | 558 | > 559 | -- Data types are converted correctly 560 | print(vim.api.nvim_eval('1 + 1')) -- 2 561 | print(vim.inspect(vim.api.nvim_eval('[1, 2, 3]'))) -- { 1, 2, 3 } 562 | print(vim.inspect(vim.api.nvim_eval('{"foo": "bar", "baz": "qux"}'))) 563 | -- { baz = "qux", foo = "bar" } 564 | print(vim.api.nvim_eval('v:true')) -- true 565 | print(vim.api.nvim_eval('v:null')) -- nil 566 | < 567 | 568 | Caveats~ 569 | 570 | Unlike `luaeval()`, `vim.api.nvim_eval()` does not provide an implicit 571 | `_A` variable to pass data to the expression. 572 | 573 | vim.api.nvim_exec()~ 574 | 575 | This function evaluates a chunk of Vimscript code. It takes in a string 576 | containing the source code to execute and a boolean to determine whether 577 | the output of the code should be returned by the function (you can then 578 | store the output in a variable, for example). 579 | 580 | > 581 | local result = vim.api.nvim_exec( 582 | [[ 583 | let s:mytext = 'hello world' 584 | 585 | function! s:MyFunction(text) 586 | echo a:text 587 | endfunction 588 | 589 | call s:MyFunction(s:mytext) 590 | ]], 591 | true) 592 | 593 | print(result) -- 'hello world' 594 | < 595 | 596 | Caveats~ 597 | 598 | `nvim_exec` does not support script-local variables (`s:`) prior to 599 | Neovim 0.6.0 600 | 601 | vim.api.nvim_command()~ 602 | 603 | This function executes an ex command. It takes in a string containing 604 | the command to execute. 605 | 606 | > 607 | vim.api.nvim_command('new') 608 | vim.api.nvim_command('wincmd H') 609 | vim.api.nvim_command('set nonumber') 610 | vim.api.nvim_command('%s/foo/bar/g') 611 | < 612 | 613 | vim.cmd()~ 614 | 615 | Alias for `vim.api.nvim_exec()`. Only the command argument is needed, 616 | `output` is always set to `false`. 617 | 618 | > 619 | vim.cmd('buffers') 620 | vim.cmd([[ 621 | let g:multiline_list = [ 622 | \ 1, 623 | \ 2, 624 | \ 3, 625 | \ ] 626 | 627 | echo g:multiline_list 628 | ]]) 629 | < 630 | 631 | Tips~ 632 | 633 | Since you have to pass strings to these functions, you often end up 634 | having to escape backslashes: 635 | 636 | > 637 | vim.cmd('%s/\\Vfoo/bar/g') 638 | < 639 | 640 | Double bracketed strings are easier to use as they do not require 641 | escaping characters: 642 | 643 | > 644 | vim.cmd([[%s/\Vfoo/bar/g]]) 645 | < 646 | 647 | vim.api.nvim_replace_termcodes()~ 648 | 649 | This API function allows you to escape terminal codes and Vim keycodes. 650 | 651 | You may have come across mappings like this one: 652 | 653 | > 654 | inoremap pumvisible() ? "\" : "\" 655 | < 656 | 657 | Trying to do the same in Lua can prove to be a challenge. You might be 658 | tempted to do it like this: 659 | 660 | > 661 | function _G.smart_tab() 662 | return vim.fn.pumvisible() == 1 and [[\]] or [[\]] 663 | end 664 | 665 | vim.api.nvim_set_keymap('i', '', 'v:lua.smart_tab()', {expr = 666 | true, noremap = true}) 667 | < 668 | 669 | only to find out that the mapping inserts `\` and `\` 670 | literally... 671 | 672 | Being able to escape keycodes is actually a Vimscript feature. Aside 673 | from the usual escape sequences like `\r`, `\42` or `\x10` that are 674 | common to many programming languages, Vimscript `expr-quotes` (strings 675 | surrounded with double quotes) allow you to escape the human-readable 676 | representation of Vim keycodes. 677 | 678 | Lua doesn't have such a feature built-in. Fortunately, Neovim 679 | has an API function for escaping terminal codes and keycodes: 680 | `nvim_replace_termcodes()` 681 | 682 | > 683 | print(vim.api.nvim_replace_termcodes('', true, true, true)) 684 | < 685 | 686 | This is a little verbose. Making a reusable wrapper can help: 687 | 688 | > 689 | -- The function is called `t` for `termcodes`. 690 | -- You don't have to call it that, but I find the terseness convenient 691 | local function t(str) 692 | -- Adjust boolean arguments as needed 693 | return vim.api.nvim_replace_termcodes(str, true, true, true) 694 | end 695 | 696 | print(t'') 697 | < 698 | 699 | Coming back to our earlier example, this should now work as expected: 700 | 701 | > 702 | local function t(str) 703 | return vim.api.nvim_replace_termcodes(str, true, true, true) 704 | end 705 | 706 | function _G.smart_tab() 707 | return vim.fn.pumvisible() == 1 and t'' or t'' 708 | end 709 | 710 | vim.api.nvim_set_keymap('i', '', 'v:lua.smart_tab()', {expr = 711 | true, noremap = true}) 712 | < 713 | 714 | This is not necessary with `vim.keymap.set()` as it automatically 715 | transforms vim keycodes returned by Lua functions in `expr` mappings 716 | by default: 717 | 718 | > 719 | vim.keymap.set('i', '', function() 720 | return vim.fn.pumvisible() == 1 and '' or '' 721 | end, {expr = true}) 722 | < 723 | 724 | See also: 725 | 726 | - |keycodes| 727 | - |expr-quote| 728 | - |nvim_replace_termcodes()| 729 | 730 | ============================================================================== 731 | MANAGING VIM OPTIONS 732 | *luaguide-managing-vim-options* 733 | 734 | Using api functions~ 735 | 736 | Neovim provides a set of API functions to either set an option or get 737 | its current value: 738 | 739 | - Global options: 740 | - |nvim_set_option()| 741 | - |nvim_get_option()| 742 | - Buffer-local options: 743 | - |nvim_buf_set_option()| 744 | - |nvim_buf_get_option()| 745 | - Window-local options: 746 | - |nvim_win_set_option()| 747 | - |nvim_win_get_option()| 748 | 749 | They take a string containing the name of the option to set/get as well 750 | as the value you want to set it to. 751 | 752 | Boolean options (like `(no)number`) have to be set to either `true` or 753 | `false`: 754 | 755 | > 756 | vim.api.nvim_set_option('smarttab', false) 757 | print(vim.api.nvim_get_option('smarttab')) -- false 758 | < 759 | 760 | Unsurprisingly, string options have to be set to a string: 761 | 762 | > 763 | vim.api.nvim_set_option('selection', 'exclusive') 764 | print(vim.api.nvim_get_option('selection')) -- 'exclusive' 765 | < 766 | 767 | Number options accept a number: 768 | 769 | > 770 | vim.api.nvim_set_option('updatetime', 3000) 771 | print(vim.api.nvim_get_option('updatetime')) -- 3000 772 | < 773 | 774 | Buffer-local and window-local options also need a buffer number or 775 | a window number (using `0` will set/get the option for the current 776 | buffer/window): 777 | 778 | > 779 | vim.api.nvim_win_set_option(0, 'number', true) 780 | vim.api.nvim_buf_set_option(10, 'shiftwidth', 4) 781 | print(vim.api.nvim_win_get_option(0, 'number')) -- true 782 | print(vim.api.nvim_buf_get_option(10, 'shiftwidth')) -- 4 783 | < 784 | 785 | Using meta-accessors~ 786 | 787 | A few meta-accessors are available if you want to set options in a more 788 | "idiomatic" way. They essentially wrap the above API functions and allow 789 | you to manipulate options as if they were variables: 790 | 791 | - |vim.o|: behaves like `:let &{option-name}` 792 | - |vim.go|: behaves like `:let &g:{option-name}` 793 | - |vim.bo|: behaves like `:let &l:{option-name}` for buffer-local options 794 | - |vim.wo|: behaves like `:let &l:{option-name}` for window-local options 795 | 796 | > 797 | vim.o.smarttab = false -- let &smarttab = v:false 798 | print(vim.o.smarttab) -- false 799 | vim.o.isfname = vim.o.isfname .. ',@-@' -- on Linux: let &isfname = 800 | &isfname .. ',@-@' 801 | print(vim.o.isfname) -- '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@' 802 | 803 | vim.bo.shiftwidth = 4 804 | print(vim.bo.shiftwidth) -- 4 805 | < 806 | 807 | You can specify a number for buffer-local and window-local options. If 808 | no number is given, the current buffer/window is used: 809 | 810 | > 811 | vim.bo[4].expandtab = true -- same as vim.api.nvim_buf_set_option(4, 812 | 'expandtab', true) 813 | vim.wo.number = true -- same as vim.api.nvim_win_set_option(0, 814 | 'number', true) 815 | < 816 | 817 | These wrappers also have more sophisticated `vim.opt*` variants that 818 | provide convenient mechanisms for setting options in Lua. They're similar 819 | to what you might be used to in your `init.vim`: 820 | 821 | - `vim.opt`: behaves like `:set` 822 | - `vim.opt_global`: behaves like `:setglobal` 823 | - `vim.opt_local`: behaves like `:setlocal` 824 | 825 | > 826 | vim.opt.smarttab = false 827 | print(vim.opt.smarttab:get()) -- false 828 | < 829 | 830 | Some options can be set using Lua tables: 831 | 832 | > 833 | vim.opt.completeopt = {'menuone', 'noselect'} 834 | print(vim.inspect(vim.opt.completeopt:get())) -- { "menuone", 835 | "noselect" } 836 | < 837 | 838 | Wrappers for list-like, map-like and set-like options also come with 839 | methods and metamethods that work similarly to their `:set+=`, `:set^=` 840 | and `:set-=` counterparts in Vimscript. 841 | 842 | > 843 | vim.opt.shortmess:append({ I = true }) 844 | -- alternative form: 845 | vim.opt.shortmess = vim.opt.shortmess + { I = true } 846 | 847 | vim.opt.whichwrap:remove({ 'b', 's' }) 848 | -- alternative form: 849 | vim.opt.whichwrap = vim.opt.whichwrap - { 'b', 's' } 850 | < 851 | 852 | Be sure to look at |vim.opt| for more information. 853 | 854 | See also: 855 | - |lua-vim-options| 856 | 857 | ============================================================================== 858 | MANAGING VIM INTERNAL VARIABLES 859 | *luaguide-managing-vim-internal-variables* 860 | 861 | Using api functions~ 862 | 863 | Much like options, internal variables have their own set of API functions: 864 | 865 | - Global variables (`g:`): 866 | - |nvim_set_var()| 867 | - |nvim_get_var()| 868 | - |nvim_del_var()| 869 | - Buffer variables (`b:`): 870 | - |nvim_buf_set_var()| 871 | - |nvim_buf_get_var()| 872 | - |nvim_buf_del_var()| 873 | - Window variables (`w:`): 874 | - |nvim_win_set_var()| 875 | - |nvim_win_get_var()| 876 | - |nvim_win_del_var()| 877 | - Tabpage variables (`t:`): 878 | - |nvim_tabpage_set_var()| 879 | - |nvim_tabpage_get_var()| 880 | - |nvim_tabpage_del_var()| 881 | - Predefined Vim variables (`v:`): 882 | - |nvim_set_vvar()| 883 | - |nvim_get_vvar()| 884 | 885 | With the exception of predefined Vim variables, they can also be deleted 886 | (the `:unlet` command is the equivalent in Vimscript). Local variables 887 | (`l:`), script variables (`s:`) and function arguments (`a:`) cannot 888 | be manipulated as they only make sense in the context of a Vim script, 889 | Lua has its own scoping rules. 890 | 891 | If you are unfamiliar with what these variables do, |internal-variables| 892 | describes them in detail. 893 | 894 | These functions take a string containing the name of the variable to 895 | set/get/delete as well as the value you want to set it to. 896 | 897 | > 898 | vim.api.nvim_set_var('some_global_variable', { key1 = 'value', key2 = 899 | 300 }) 900 | print(vim.inspect(vim.api.nvim_get_var('some_global_variable'))) -- 901 | { key1 = "value", key2 = 300 } 902 | vim.api.nvim_del_var('some_global_variable') 903 | < 904 | 905 | Variables that are scoped to a buffer, a window or a tabpage also 906 | receive a number (using `0` will set/get/delete the variable for the 907 | current buffer/window/tabpage): 908 | 909 | > 910 | vim.api.nvim_win_set_var(0, 'some_window_variable', 2500) 911 | vim.api.nvim_tab_set_var(3, 'some_tabpage_variable', 'hello world') 912 | print(vim.api.nvim_win_get_var(0, 'some_window_variable')) -- 2500 913 | print(vim.api.nvim_buf_get_var(3, 'some_tabpage_variable')) -- 914 | 'hello world' 915 | vim.api.nvim_win_del_var(0, 'some_window_variable') 916 | vim.api.nvim_buf_del_var(3, 'some_tabpage_variable') 917 | < 918 | 919 | Using meta-accessors~ 920 | 921 | Internal variables can be manipulated more intuitively using these 922 | meta-accessors: 923 | 924 | - |vim.g|: global variables 925 | - |vim.b|: buffer variables 926 | - |vim.w|: window variables 927 | - |vim.t|: tabpage variables 928 | - |vim.v|: predefined Vim variables 929 | - |vim.env|: environment variables 930 | 931 | > 932 | vim.g.some_global_variable = { 933 | key1 = 'value', 934 | key2 = 300 935 | } 936 | 937 | print(vim.inspect(vim.g.some_global_variable)) -- { key1 = "value", 938 | key2 = 300 } 939 | 940 | -- target a specific buffer/window/tabpage (Neovim 0.6+) 941 | vim.b[2].myvar = 1 942 | < 943 | 944 | Some variable names may contain characters that cannot be used for 945 | identifiers in Lua. You can still manipulate these variables by using 946 | this syntax: `vim.g['my#variable']`. 947 | 948 | To delete one of these variables, simply assign `nil` to it: 949 | 950 | > 951 | vim.g.some_global_variable = nil 952 | < 953 | 954 | See also: 955 | - |lua-vim-variables| 956 | 957 | Caveats~ 958 | 959 | You cannot add/update/delete keys from a dictionary stored in one of 960 | these variables. For example, this snippet of Vimscript code does not 961 | work as expected: 962 | 963 | > 964 | let g:variable = {} 965 | lua vim.g.variable.key = 'a' 966 | echo g:variable 967 | " {} 968 | < 969 | 970 | You can use a temporary variable as a workaround: 971 | 972 | > 973 | let g:variable = {} 974 | lua << EOF 975 | local tmp = vim.g.variable 976 | tmp.key = 'a' 977 | vim.g.variable = tmp 978 | EOF 979 | echo g:variable 980 | " {'key': 'a'} 981 | < 982 | 983 | This is a known issue: 984 | 985 | - Issue #12544: https://github.com/neovim/neovim/issues/12544 986 | 987 | ============================================================================== 988 | CALLING VIMSCRIPT FUNCTIONS 989 | *luaguide-calling-vimscript-functions* 990 | 991 | vim.fn.{function}()~ 992 | 993 | `vim.fn` can be used to call a Vimscript function. Data types are 994 | converted back and forth from Lua to Vimscript. 995 | 996 | > 997 | print(vim.fn.printf('Hello from %s', 'Lua')) 998 | 999 | local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' }) 1000 | print(vim.inspect(reversed_list)) -- { "c", "b", "a" } 1001 | 1002 | local function print_stdout(chan_id, data, name) 1003 | print(data[1]) 1004 | end 1005 | 1006 | vim.fn.jobstart('ls', { on_stdout = print_stdout }) 1007 | < 1008 | 1009 | Hashes (`#`) are not valid characters for identifiers in Lua, so autoload 1010 | functions have to be called with this syntax: 1011 | 1012 | > 1013 | vim.fn['my#autoload#function']() 1014 | < 1015 | 1016 | The functionality of `vim.fn` is identical to `vim.call`, but allows a 1017 | more Lua-like syntax. 1018 | 1019 | It is distinct from `vim.api.nvim_call_function` in that converting 1020 | Vim/Lua objects is automatic: `vim.api.nvim_call_function` returns a 1021 | table for floating point numbers and does not accept Lua closures while 1022 | `vim.fn` handles these types transparently. 1023 | 1024 | See also: 1025 | - |vim.fn| 1026 | 1027 | Tips~ 1028 | 1029 | Neovim has an extensive library of powerful built-in functions that are very 1030 | useful for plugins. See |vim-function| for an alphabetical list and 1031 | |function-list| for a list of functions grouped by topic. 1032 | 1033 | Neovim API functions can be used directly through `vim.api.{..}`. See 1034 | |api| for information. 1035 | 1036 | Caveats~ 1037 | 1038 | Some Vim functions that should return a boolean return `1` or `0` 1039 | instead. This isn't a problem in Vimscript as `1` is truthy and `0` 1040 | falsy, enabling constructs like these: 1041 | 1042 | > 1043 | if has('nvim') 1044 | " do something... 1045 | endif 1046 | < 1047 | 1048 | In Lua however, only `false` and `nil` are considered falsy, numbers 1049 | always evaluate to `true` no matter their value. You have to explicitly 1050 | check for `1` or `0`: 1051 | 1052 | > 1053 | if vim.fn.has('nvim') == 1 then 1054 | -- do something... 1055 | end 1056 | < 1057 | 1058 | ============================================================================== 1059 | DEFINING MAPPINGS 1060 | *luaguide-defining-mappings* 1061 | 1062 | API functions~ 1063 | 1064 | Neovim provides a list of API functions to set, get and delete mappings: 1065 | 1066 | - Global mappings: 1067 | - |nvim_set_keymap()| 1068 | - |nvim_get_keymap()| 1069 | - |nvim_del_keymap()| 1070 | - Buffer-local mappings: 1071 | - |nvim_buf_set_keymap()| 1072 | - |nvim_buf_get_keymap()| 1073 | - |nvim_buf_del_keymap()| 1074 | 1075 | Let's start with `vim.api.nvim_set_keymap()` and 1076 | `vim.api.nvim_buf_set_keymap()` 1077 | 1078 | The first argument passed to the function is a string containing the 1079 | name of the mode for which the mapping will take effect: 1080 | 1081 | | String value | Help page | Affected modes | Vimscript equivalent | 1082 | | ---------------------- | ------------- | ---------------------------------------- | -------------------- | 1083 | | `''` (an empty string) | `mapmode-nvo` | Normal, Visual, Select, Operator-pending | `:map` | 1084 | | `'n'` | `mapmode-n` | Normal | `:nmap` | 1085 | | `'v'` | `mapmode-v` | Visual and Select | `:vmap` | 1086 | | `'s'` | `mapmode-s` | Select | `:smap` | 1087 | | `'x'` | `mapmode-x` | Visual | `:xmap` | 1088 | | `'o'` | `mapmode-o` | Operator-pending | `:omap` | 1089 | | `'!'` | `mapmode-ic` | Insert and Command-line | `:map!` | 1090 | | `'i'` | `mapmode-i` | Insert | `:imap` | 1091 | | `'l'` | `mapmode-l` | Insert, Command-line, Lang-Arg | `:lmap` | 1092 | | `'c'` | `mapmode-c` | Command-line | `:cmap` | 1093 | | `'t'` | `mapmode-t` | Terminal | `:tmap` | 1094 | 1095 | The second argument is a string containing the left-hand side of the 1096 | mapping (the key or set of keys that trigger the command defined in the 1097 | mapping). An empty string is equivalent to ``, which disables a key. 1098 | 1099 | The third argument is a string containing the right-hand side of the 1100 | mapping (the command to execute). 1101 | 1102 | The final argument is a table containing boolean options for the mapping 1103 | as defined in |:map-arguments|. Since Neovim 0.7.0, you can also pass a 1104 | `callback` option to invoke a Lua function instead of the right-hand 1105 | side when executing the mapping. 1106 | 1107 | Buffer-local mappings also take a buffer number as their first argument 1108 | (`0` sets the mapping for the current buffer). 1109 | 1110 | > 1111 | vim.api.nvim_set_keymap('n', '', ':set hlsearch!', 1112 | { noremap = true, silent = true }) 1113 | -- :nnoremap :set hlsearch 1114 | vim.api.nvim_set_keymap('n', 'tegf', [[lua 1115 | require('telescope.builtin').git_files()]], { noremap = true, 1116 | silent = true }) 1117 | -- :nnoremap tegf lua 1118 | require('telescope.builtin').git_files() 1119 | 1120 | vim.api.nvim_buf_set_keymap(0, '', 'cc', 'line(".") == 1 ? "cc" : 1121 | "ggcc"', { noremap = true, expr = true }) 1122 | -- :noremap cc line('.') == 1 ? 'cc' : 'ggcc' 1123 | 1124 | vim.api.nvim_set_keymap('n', 'ex', '', { 1125 | noremap = true, 1126 | callback = function() 1127 | print('My example') 1128 | end, 1129 | -- Since Lua function don't have a useful string representation, 1130 | you can use the "desc" option to document your mapping 1131 | desc = 'Prints "My example" in the message area', 1132 | }) 1133 | < 1134 | 1135 | `vim.api.nvim_get_keymap()` takes a string containing the shortname of 1136 | the mode for which you want the list of mappings (see table above). The 1137 | return value is a table containing all global mappings for the mode. 1138 | 1139 | > 1140 | print(vim.inspect(vim.api.nvim_get_keymap('n'))) 1141 | -- :verbose nmap 1142 | < 1143 | 1144 | `vim.api.nvim_buf_get_keymap()` takes an additional buffer number as 1145 | its first argument (`0` will get mapppings for the current bufffer) 1146 | 1147 | > 1148 | print(vim.inspect(vim.api.nvim_buf_get_keymap(0, 'i'))) 1149 | -- :verbose imap 1150 | < 1151 | 1152 | `vim.api.nvim_del_keymap()` takes a mode and the left-hand side of 1153 | a mapping. 1154 | 1155 | > 1156 | vim.api.nvim_del_keymap('n', '') 1157 | -- :nunmap 1158 | < 1159 | 1160 | Again, `vim.api.nvim_buf_del_keymap()`, takes a buffer number as its 1161 | first argument, with `0` representing the current buffer. 1162 | 1163 | > 1164 | vim.api.nvim_buf_del_keymap(0, 'i', '') 1165 | -- :iunmap 1166 | < 1167 | 1168 | vim.keymap~ 1169 | 1170 | WARNING: The functions discussed in this section are only available in 1171 | Neovim 0.7.0+ 1172 | 1173 | Neovim provides two functions to set/del mappings: 1174 | - |vim.keymap.set()| 1175 | - |vim.keymap.del()| 1176 | 1177 | These are similar to the above API functions with added syntactic sugar. 1178 | 1179 | `vim.keymap.set()` takes a string as its first argument. It can also be 1180 | a table of strings to define mappings for multiple modes at once: 1181 | 1182 | > 1183 | vim.keymap.set('n', 'ex1', 'lua vim.notify("Example 1184 | 1")') 1185 | vim.keymap.set({'n', 'c'}, 'ex2', 'lua 1186 | vim.notify("Example 2")') 1187 | < 1188 | 1189 | The second argument is the left-hand side of the mapping. 1190 | 1191 | The third argument is the right-hand side of the mapping, which can 1192 | either be a string or a Lua function: 1193 | 1194 | > 1195 | vim.keymap.set('n', 'ex1', 'echomsg "Example 1"') 1196 | vim.keymap.set('n', 'ex2', function() print("Example 2") end) 1197 | vim.keymap.set('n', 'pl1', require('plugin').plugin_action) 1198 | -- To avoid the startup cost of requiring the module, you can wrap 1199 | it in a function to require it lazily when invoking the mapping: 1200 | vim.keymap.set('n', 'pl2', function() 1201 | require('plugin').plugin_action() end) 1202 | < 1203 | 1204 | The fourth (optional) argument is a table of options that correspond to 1205 | the options passed to `vim.api.nvim_set_keymap()`, with a few additions 1206 | (see |vim.keymap.set()|. 1207 | 1208 | > 1209 | vim.keymap.set('n', 'ex1', 'echomsg "Example 1"', 1210 | {buffer = true}) 1211 | vim.keymap.set('n', 'ex2', function() print('Example 2') 1212 | end, {desc = 'Prints "Example 2" to the message area'}) 1213 | < 1214 | 1215 | Defining keymaps with a Lua function is different from using a string. The 1216 | usual way to show information about a keymap like `:nmap ex1` 1217 | will not output useful information (the string itself), but instead 1218 | only show `Lua function`. It is recommended to add a `desc` key to 1219 | describe the behavior of your keymap. This is especially important for 1220 | documenting plugin mappings so users can understand the usage of the 1221 | keymap more easily. 1222 | 1223 | An interesting feature of this API is that it irons out some historical 1224 | quirks of Vim mappings: 1225 | - Mappings are `noremap` by default, except when the `rhs` is a `` 1226 | mapping. This means you rarely have to think about whether a mapping 1227 | should be recursive or not: 1228 | ```lua 1229 | vim.keymap.set('n', 'test1', 'echo "test"') 1230 | -- :nnoremap test echo "test" 1231 | 1232 | -- If you DO want the mapping to be recursive, set the "remap" 1233 | option to "true" 1234 | vim.keymap.set('n', '>', ']', {remap = true}) 1235 | -- :nmap > ] 1236 | 1237 | -- mappings don't work unless they're recursive, 1238 | vim.keymap.set() handles that for you automatically 1239 | vim.keymap.set('n', 'plug', '(plugin)') 1240 | -- :nmap plug (plugin) 1241 | ``` 1242 | - In `expr` mappings, `nvim_replace_termcodes()` is automatically applied 1243 | to strings returned from Lua functions: 1244 | ```lua 1245 | vim.keymap.set('i', '', function() 1246 | return vim.fn.pumvisible == 1 and '' or '' 1247 | end, {expr = true}) 1248 | ``` 1249 | 1250 | See also: 1251 | - |recursive_mapping| 1252 | 1253 | `vim.keymap.del()` works the same way but deletes mappings instead: 1254 | 1255 | > 1256 | vim.keymap.del('n', 'ex1') 1257 | vim.keymap.del({'n', 'c'}, 'ex2', {buffer = true}) 1258 | < 1259 | 1260 | ============================================================================== 1261 | DEFINING USER COMMANDS 1262 | *luaguide-defining-user-commands* 1263 | 1264 | WARNING: The API functions discussed in this section are only available 1265 | in Neovim 0.7.0+ 1266 | 1267 | Neovim provides API functions for user-defined commands: 1268 | 1269 | - Global user commands: 1270 | - |nvim_create_user_command()| 1271 | - |nvim_del_user_command()| 1272 | - Buffer-local user commands: 1273 | - |nvim_buf_create_user_command()| 1274 | - |nvim_buf_del_user_command()| 1275 | 1276 | Let's start with `vim.api.nvim_create_user_command()` 1277 | 1278 | The first argument passed to this function is the name of the command 1279 | (which must start with an uppercase letter). 1280 | 1281 | The second argument is the code to execute when invoking said command. It 1282 | can either be: 1283 | 1284 | A string (in which case it will be executed as Vimscript). You can use 1285 | escape sequences like ``, ``, etc. like you would with 1286 | `:command` 1287 | > 1288 | vim.api.nvim_create_user_command('Upper', 'echo toupper()', 1289 | { nargs = 1 }) 1290 | -- :command! -nargs=1 Upper echo toupper() 1291 | 1292 | vim.cmd('Upper hello world') -- prints "HELLO WORLD" 1293 | < 1294 | 1295 | Or a Lua function. It receives a dictionary-like table that 1296 | contains the data normally provided by escape sequences (see 1297 | |nvim_create_user_command()| 1298 | > 1299 | vim.api.nvim_create_user_command( 1300 | 'Upper', 1301 | function(opts) 1302 | print(string.upper(opts.args)) 1303 | end, 1304 | { nargs = 1 } 1305 | ) 1306 | < 1307 | 1308 | The third argument lets you pass command attributes as a table (see 1309 | |command-attributes|`. Since you can already define buffer-local user commands 1310 | with |nvim_buf_create_user_command()|, `-buffer` is not a valid attribute. 1311 | 1312 | Two additional attributes are available: 1313 | - `desc` allows you to control what gets displayed when you run `:command 1314 | {cmd}` on a command defined as a Lua callback. Similarly to keymaps, it 1315 | is recommended to add a `desc` key to commands defined as Lua functions. 1316 | - `force` is equivalent to calling `:command!` and replaces a command 1317 | if one with the same name already exists. It is true by default, unlike 1318 | its Vimscript equivalent. 1319 | 1320 | The `-complete` attribute can take a Lua function in addition to the 1321 | attributes listed in |:command-complete|. 1322 | 1323 | > 1324 | vim.api.nvim_create_user_command('Upper', function() end, { 1325 | nargs = 1, 1326 | complete = function(ArgLead, CmdLine, CursorPos) 1327 | -- return completion candidates as a list-like table 1328 | return { 'foo', 'bar', 'baz' } 1329 | end, 1330 | }) 1331 | < 1332 | 1333 | Buffer-local user commands also take a buffer number as their first 1334 | argument. This is an advantage over `-buffer` which can only define a 1335 | command for the current buffer. 1336 | 1337 | > 1338 | vim.api.nvim_buf_create_user_command(4, 'Upper', function() end, {}) 1339 | < 1340 | 1341 | `vim.api.nvim_del_user_command()` takes a command name. 1342 | 1343 | > 1344 | vim.api.nvim_del_user_command('Upper') 1345 | -- :delcommand Upper 1346 | < 1347 | 1348 | Again, `vim.api.nvim_buf_del_user_command()`, takes a buffer number as 1349 | its first argument, with `0` representing the current buffer. 1350 | 1351 | > 1352 | vim.api.nvim_buf_del_user_command(4, 'Upper') 1353 | < 1354 | 1355 | See also: 1356 | - |nvim_create_user_command()| 1357 | - |40.2| 1358 | - |command-attributes| 1359 | 1360 | Caveats~ 1361 | 1362 | The `-complete=custom` attribute automatically filters completion 1363 | candidates and has built-in wildcard (|wildcard| support: 1364 | 1365 | > 1366 | function! s:completion_function(ArgLead, CmdLine, CursorPos) abort 1367 | return join([ 1368 | \ 'strawberry', 1369 | \ 'star', 1370 | \ 'stellar', 1371 | \ ], "\n") 1372 | endfunction 1373 | 1374 | command! -nargs=1 -complete=custom,s:completion_function Test echo 1375 | 1376 | " Typing `:Test st[ae]` returns "star" and "stellar" 1377 | < 1378 | 1379 | Passing a Lua function to `complete` makes it behave like `customlist` 1380 | which leaves filtering up to the user: 1381 | 1382 | > 1383 | vim.api.nvim_create_user_command('Test', function() end, { 1384 | nargs = 1, 1385 | complete = function(ArgLead, CmdLine, CursorPos) 1386 | return { 1387 | 'strawberry', 1388 | 'star', 1389 | 'stellar', 1390 | } 1391 | end, 1392 | }) 1393 | 1394 | -- Typing `:Test z` returns all the completion results because 1395 | the list was not filtered 1396 | < 1397 | 1398 | ============================================================================== 1399 | DEFINING AUTOCOMMANDS 1400 | *luaguide-defining-autocommands* 1401 | 1402 | (this section is a work in progress) 1403 | 1404 | Neovim 0.7.0 has API functions for autocommands. See `:help api-autocmd` 1405 | for details 1406 | 1407 | - Pull request #14661: https://github.com/neovim/neovim/pull/14661 lua: 1408 | autocmds take 2 1409 | 1410 | ============================================================================== 1411 | DEFINING HIGHLIGHTS 1412 | *luaguide-defining-highlights* 1413 | 1414 | (this section is a work in progress) 1415 | 1416 | Neovim 0.7.0 has API functions for highlight groups. See also: 1417 | 1418 | - |nvim_set_hl()| 1419 | - |nvim_get_hl_by_id()| 1420 | - |nvim_get_hl_by_name()| 1421 | 1422 | ============================================================================== 1423 | GENERAL TIPS AND RECOMMENDATIONS 1424 | *luaguide-general-tips-and-recommendations* 1425 | 1426 | Reloading cached modules~ 1427 | 1428 | In Lua, the `require()` function caches modules. This is a good thing 1429 | for performance, but it can make working on plugins a bit cumbersome 1430 | because modules are not updated on subsequent `require()` calls. 1431 | 1432 | If you'd like to refresh the cache for a particular module, you have to 1433 | modify the `package.loaded` global table: 1434 | 1435 | > 1436 | package.loaded['modname'] = nil 1437 | require('modname') -- loads an updated version of module 'modname' 1438 | < 1439 | 1440 | The nvim-lua/plenary.nvim: 1441 | https://github.com/nvim-lua/plenary.nvim plugin has a custom function: 1442 | https://github.com/nvim-lua/plenary.nvim/blob/master/lua/plenary/reload.lua 1443 | that does this for you. 1444 | 1445 | Don't pad Lua strings!~ 1446 | 1447 | When using double bracketed strings, resist the temptation to pad 1448 | them! While it is fine to do in contexts where spaces are ignored, 1449 | it can cause hard to debug issues when whitespace is significant: 1450 | 1451 | > 1452 | vim.api.nvim_set_keymap('n', 'f', [[ call foo() 1453 | ]], {noremap = true}) 1454 | < 1455 | 1456 | In the above example, `f` is mapped to `call 1457 | foo()` instead of `call foo()`. 1458 | 1459 | Notes about Vimscript <-> Lua type conversion~ 1460 | 1461 | Converting a variable creates a copy:~ 1462 | You can't directly interact with the reference to a Vim object from Lua 1463 | or a Lua object from Vimscript. 1464 | For example, the `map()` function in Vimscript modifies a variable 1465 | in place: 1466 | 1467 | > 1468 | let s:list = [1, 2, 3] 1469 | let s:newlist = map(s:list, {_, v -> v * 2}) 1470 | 1471 | echo s:list 1472 | " [2, 4, 6] 1473 | echo s:newlist 1474 | " [2, 4, 6] 1475 | echo s:list is# s:newlist 1476 | " 1 1477 | < 1478 | 1479 | Using this function from Lua creates a copy instead: 1480 | 1481 | > 1482 | local tbl = {1, 2, 3} 1483 | local newtbl = vim.fn.map(tbl, function(_, v) return v * 2 end) 1484 | 1485 | print(vim.inspect(tbl)) -- { 1, 2, 3 } 1486 | print(vim.inspect(newtbl)) -- { 2, 4, 6 } 1487 | print(tbl == newtbl) -- false 1488 | < 1489 | 1490 | Conversion is not always possible~ 1491 | This mostly affects functions and tables: 1492 | 1493 | Lua tables that are a mix between a List and a Dictionary can't be 1494 | converted: 1495 | 1496 | > 1497 | print(vim.fn.count({1, 1, number = 1}, 1)) 1498 | -- E5100: Cannot convert given lua table: table should either have 1499 | a sequence of positive integer keys or contain only string keys 1500 | < 1501 | 1502 | While you can call Vim functions in Lua with `vim.fn`, you can't hold 1503 | references to them. This can cause surprising behaviors: 1504 | 1505 | > 1506 | local FugitiveHead = vim.fn.funcref('FugitiveHead') 1507 | print(FugitiveHead) -- vim.NIL 1508 | 1509 | vim.cmd("let g:test_dict = {'test_lambda': {-> 1}}") 1510 | print(vim.g.test_dict.test_lambda) -- nil 1511 | print(vim.inspect(vim.g.test_dict)) -- {} 1512 | < 1513 | 1514 | Passing Lua functions to Vim functions is OK, storing them in Vim 1515 | variables is not (fixed in Neovim 0.7.0+): 1516 | 1517 | > 1518 | -- This works: 1519 | vim.fn.jobstart({'ls'}, { 1520 | on_stdout = function(chan_id, data, name) 1521 | print(vim.inspect(data)) 1522 | end 1523 | }) 1524 | 1525 | -- This doesn't: 1526 | vim.g.test_dict = {test_lambda = function() return 1 end} -- Error: 1527 | Cannot convert given lua type 1528 | < 1529 | 1530 | Note however that doing the same from Vimscript with `luaeval()` 1531 | **does** work: 1532 | 1533 | > 1534 | let g:test_dict = {'test_lambda': luaeval('function() return 1 end')} 1535 | echo g:test_dict 1536 | " {'test_lambda': function('4714')} 1537 | < 1538 | 1539 | Vim booleans~ 1540 | A common pattern in Vim scripts is to use `1` or `0` instead of proper 1541 | booleans. Indeed, Vim did not have a separate boolean type until version 1542 | 7.4.1154. 1543 | 1544 | Lua booleans are converted to actual booleans in Vimscript, not numbers: 1545 | 1546 | > 1547 | lua vim.g.lua_true = true 1548 | echo g:lua_true 1549 | " v:true 1550 | lua vim.g.lua_false = false 1551 | echo g:lua_false 1552 | " v:false 1553 | < 1554 | 1555 | Setting up linters/language servers~ 1556 | 1557 | If you're using linters and/or language servers to get diagnostics and 1558 | autocompletion for Lua projects, you may have to configure Neovim-specific 1559 | settings for them. Here are a few recommended settings for popular tools: 1560 | 1561 | luacheck~ 1562 | 1563 | You can get luacheck: https://github.com/mpeterv/luacheck/ to recognize 1564 | the `vim` global by putting this configuration in `~/.luacheckrc` or 1565 | `$XDG_CONFIG_HOME/luacheck/.luacheckrc` : 1566 | 1567 | > 1568 | globals = { 1569 | "vim", 1570 | } 1571 | < 1572 | 1573 | The Alloyed/lua-lsp: https://github.com/Alloyed/lua-lsp/ language 1574 | server uses `luacheck` to provide linting and reads the same file. 1575 | 1576 | For more information on how to configure `luacheck`, please refer to 1577 | its documentation: https://luacheck.readthedocs.io/en/stable/config.html 1578 | 1579 | sumneko/lua-language-server~ 1580 | 1581 | The nvim-lspconfig: https://github.com/neovim/nvim-lspconfig/ repository 1582 | contains instructions to configure sumneko/lua-language-server: 1583 | https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#sumneko_lua 1584 | the example uses the built-in LSP client but the configuration should 1585 | be identical for other LSP client implementations . 1586 | 1587 | For more information on how to configure sumneko/lua-language-server: 1588 | https://github.com/sumneko/lua-language-server/ see "Setting": 1589 | https://github.com/sumneko/lua-language-server/wiki/Setting 1590 | 1591 | coc.nvim~ 1592 | 1593 | The rafcamlet/coc-nvim-lua: https://github.com/rafcamlet/coc-nvim-lua/ 1594 | completion source for coc.nvim: https://github.com/neoclide/coc.nvim/ 1595 | provides completion items for the Neovim stdlib. 1596 | 1597 | Debugging Lua code~ 1598 | 1599 | You can debug Lua code running in a separate Neovim 1600 | instance with jbyuki/one-small-step-for-vimkind: 1601 | https://github.com/jbyuki/one-small-step-for-vimkind 1602 | 1603 | The plugin uses the Debug Adapter Protocol: 1604 | https://microsoft.github.io/debug-adapter-protocol/ . Connecting to 1605 | a debug adapter requires a DAP client like mfussenegger/nvim-dap: 1606 | https://github.com/mfussenegger/nvim-dap/ or puremourning/vimspector: 1607 | https://github.com/puremourning/vimspector/ . 1608 | 1609 | Debugging Lua mappings/commands/autocommands~ 1610 | 1611 | The `:verbose` command allows you to see where a 1612 | mapping/command/autocommand was defined: 1613 | 1614 | > 1615 | :verbose map m 1616 | < 1617 | 1618 | > 1619 | n m_ * echo 'example' 1620 | Last set from ~/.config/nvim/init.vim line 26 1621 | < 1622 | 1623 | By default, this feature is disabled in Lua for performance reasons. You 1624 | can enable it by starting Neovim with a verbose level greater than 0: 1625 | 1626 | > 1627 | nvim -V1 1628 | < 1629 | 1630 | See also: 1631 | - |'verbose'| 1632 | - |-V| 1633 | - neovim/neovim#15079: https://github.com/neovim/neovim/pull/15079 1634 | 1635 | Testing Lua code~ 1636 | 1637 | - plenary.nvim: test harness: 1638 | https://github.com/nvim-lua/plenary.nvim/#plenarytest_harness 1639 | - notomo/vusted: https://github.com/notomo/vusted 1640 | 1641 | Using Luarocks packages~ 1642 | 1643 | wbthomason/packer.nvim: https://github.com/wbthomason/packer.nvim 1644 | supports Luarocks packages. Instructions for 1645 | how to set this up are available in the README: 1646 | https://github.com/wbthomason/packer.nvim/#luarocks-support 1647 | 1648 | ============================================================================== 1649 | MISCELLANEOUS 1650 | *luaguide-miscellaneous* 1651 | 1652 | vim.loop~ 1653 | 1654 | `vim.loop` is the module that exposes the LibUV API. Some resources: 1655 | 1656 | - Official documentation for LibUV: https://docs.libuv.org/en/v1.x/ 1657 | - Luv documentation: https://github.com/luvit/luv/blob/master/docs.md 1658 | - teukka.tech - Using LibUV in Neovim: 1659 | https://teukka.tech/posts/2020-01-07-vimloop/ 1660 | 1661 | See also: 1662 | - |vim.loop| 1663 | 1664 | vim.lsp~ 1665 | 1666 | `vim.lsp` is the module that controls the built-in LSP client. The 1667 | neovim/nvim-lspconfig: https://github.com/neovim/nvim-lspconfig/ 1668 | repository contains default configurations for popular language servers. 1669 | 1670 | The behavior of the client can be configured using "lsp-handlers". For 1671 | more information: 1672 | - |lsp-handler| 1673 | - neovim/neovim#12655: https://github.com/neovim/neovim/pull/12655 1674 | - How to migrate from diagnostic-nvim: 1675 | https://github.com/nvim-lua/diagnostic-nvim/issues/73#issue-737897078 1676 | 1677 | You may also want to take a look at plugins built around the LSP client: 1678 | https://github.com/rockerBOO/awesome-neovim#lsp 1679 | 1680 | See also: 1681 | - |lsp| 1682 | 1683 | vim.treesitter~ 1684 | 1685 | `vim.treesitter` is the module that controls the integration of the 1686 | Tree-sitter: https://tree-sitter.github.io/tree-sitter/ library in 1687 | Neovim. If you want to know more about Tree-sitter, you may be interested 1688 | in this presentation 38:37 : https://www.youtube.com/watch?v=Jes3bD6P0To 1689 | . 1690 | 1691 | The nvim-treesitter: https://github.com/nvim-treesitter/ organisation 1692 | hosts various plugins taking advantage of the library. 1693 | 1694 | See also: 1695 | - |lua-treesitter| 1696 | 1697 | Transpilers~ 1698 | 1699 | One advantage of using Lua is that you don't actually have to write Lua 1700 | code! There is a multitude of transpilers available for the language. 1701 | 1702 | - Moonscript: https://moonscript.org/ 1703 | 1704 | Probably one of the most well-known transpilers for 1705 | Lua. Adds a lots of convenient features like classes, list 1706 | comprehensions or function literals. The svermeulen/nvim-moonmaker: 1707 | https://github.com/svermeulen/nvim-moonmaker plugin allows you to write 1708 | Neovim plugins and configuration directly in Moonscript. 1709 | 1710 | - Fennel: https://fennel-lang.org/ 1711 | 1712 | A lisp that compiles to Lua. You can write configuration 1713 | and plugins for Neovim in Fennel with the Olical/aniseed: 1714 | https://github.com/Olical/aniseed or the Hotpot: 1715 | https://github.com/rktjmp/hotpot.nvim plugin. Additionally, the 1716 | Olical/conjure: https://github.com/Olical/conjure plugin provides an 1717 | interactive development environment that supports Fennel among other 1718 | languages . 1719 | 1720 | - Teal: https://github.com/teal-language/tl 1721 | 1722 | The name Teal comes from pronouncing TL typed lua . This is exactly 1723 | what it tries to do - add strong typing to lua while otherwise 1724 | remaining close to standard lua syntax. The nvim-teal-maker: 1725 | https://github.com/svermeulen/nvim-teal-maker plugin can be used to 1726 | write Neovim plugins or configuration files directly in Teal 1727 | 1728 | Other interesting projects: 1729 | - TypeScriptToLua/TypeScriptToLua: 1730 | https://github.com/TypeScriptToLua/TypeScriptToLua 1731 | - Haxe: https://haxe.org/ 1732 | - SwadicalRag/wasm2lua: https://github.com/SwadicalRag/wasm2lua 1733 | - hengestone/lua-languages: https://github.com/hengestone/lua-languages 1734 | 1735 | vim:tw=78:ts=8:noet:ft=help:norl: 1736 | -------------------------------------------------------------------------------- /scripts/docgen.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ./to_vimdoc.sed ../README.md | fmt -s | ./sections_tags.awk > ../doc/nvim-lua-guide.txt 4 | ./to_vimdocja.sed ../README.ja.md | fmt -s | ./sections_tags.awk > ../doc/nvim-lua-guide.jax 5 | -------------------------------------------------------------------------------- /scripts/sections_tags.awk: -------------------------------------------------------------------------------- 1 | #!/usr/bin/awk -f 2 | { 3 | if (lastline ~ /^=+$/) { 4 | tag = tolower($0) 5 | gsub(/[^A-Za-z]/, "-", tag) 6 | print $0 7 | printf("%80s", "*" "luaguide-" tag "*") 8 | print "" 9 | } 10 | else { 11 | print 12 | } 13 | } 14 | 15 | { lastline = $0 } 16 | -------------------------------------------------------------------------------- /scripts/to_vimdoc.sed: -------------------------------------------------------------------------------- 1 | #!/bin/sed -f 2 | 3 | # Title 4 | /^# / { 5 | s/# /*nvim-lua-guide.txt* / 6 | } 7 | 8 | # Sections 9 | /^## / { 10 | s/[a-z]/\u&/g 11 | s/## // 12 | i============================================================================== 13 | } 14 | 15 | # Sub-sections, tips and caveats 16 | /^####\? / { 17 | s/####\? // 18 | s/.*/&~/ 19 | } 20 | 21 | # Help links 22 | s/\[`vim\.api\.\(.*\)`\](.*)/|\1|/ 23 | s/\[`:help \(.*\)`\](.*)/|\1|/ 24 | s/\[`\(.*\)`\](.*)/|\1|/ 25 | 26 | # Markdown links 27 | /\[.*\](http.*)/ { 28 | y/[]()/ : / 29 | } 30 | 31 | # Todos 32 | s/\*\*TODO\*\*: /\t*Todo\t/g 33 | 34 | # Warnings 35 | s/\*\*\(WARNING\)\*\*/\1/ 36 | 37 | # Code blocks 38 | /^```.*$/,/^```$/{ 39 | s/.*/ &/ 40 | s/```.\+/>/ 41 | s/\s*```$// 35 | s/\s*```$/