From d6f92542f1c96d520972a8153fb1b03d360f2cc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=B3n=C3=A1n=20Carrigan?= Date: Wed, 20 Dec 2023 15:07:38 +0000 Subject: [PATCH] feat: initial plugin --- .github/FUNDING.yml | 3 + .github/ISSUE_TEMPLATE/bug_report.md | 103 + .github/workflows/docgen.yaml | 55 + .github/workflows/issues.yaml | 16 + .github/workflows/luarocks-release.yaml | 29 + .github/workflows/workflow.yaml | 77 + .gitignore | 4 + .releaserc.json | 12 + LICENCE.md | 21 + README.md | 178 ++ doc/nio.txt | 556 +++++ lua/nio/control.lua | 304 +++ lua/nio/init.lua | 197 ++ lua/nio/logger.lua | 103 + lua/nio/lsp-types.lua | 3024 +++++++++++++++++++++++ lua/nio/lsp.lua | 112 + lua/nio/tasks.lua | 212 ++ lua/nio/tests.lua | 64 + lua/nio/ui.lua | 50 + lua/nio/uv.lua | 169 ++ scripts/docgen | 3 + scripts/gendocs.lua | 854 +++++++ scripts/generate_lsp_types.lua | 535 ++++ scripts/style | 3 + scripts/test | 20 + stylua.toml | 5 + test.lua | 16 + tests/control_spec.lua | 145 ++ tests/init.vim | 1 + tests/init_spec.lua | 118 + tests/lsp_spec.lua | 96 + tests/minimal_init.lua | 9 + tests/tasks_spec.lua | 120 + tests/uv_spec.lua | 31 + 34 files changed, 7245 insertions(+) create mode 100644 .github/FUNDING.yml create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/workflows/docgen.yaml create mode 100644 .github/workflows/issues.yaml create mode 100644 .github/workflows/luarocks-release.yaml create mode 100644 .github/workflows/workflow.yaml create mode 100644 .gitignore create mode 100644 .releaserc.json create mode 100644 LICENCE.md create mode 100644 doc/nio.txt create mode 100644 lua/nio/control.lua create mode 100644 lua/nio/init.lua create mode 100644 lua/nio/logger.lua create mode 100644 lua/nio/lsp-types.lua create mode 100644 lua/nio/lsp.lua create mode 100644 lua/nio/tasks.lua create mode 100644 lua/nio/tests.lua create mode 100644 lua/nio/ui.lua create mode 100644 lua/nio/uv.lua create mode 100755 scripts/docgen create mode 100644 scripts/gendocs.lua create mode 100644 scripts/generate_lsp_types.lua create mode 100755 scripts/style create mode 100755 scripts/test create mode 100644 stylua.toml create mode 100644 test.lua create mode 100644 tests/control_spec.lua create mode 100644 tests/init.vim create mode 100644 tests/init_spec.lua create mode 100644 tests/lsp_spec.lua create mode 100644 tests/minimal_init.lua create mode 100644 tests/tasks_spec.lua create mode 100644 tests/uv_spec.lua diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..9c63df5 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: rcarriga diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..28a705c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,103 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: '' +assignees: rcarriga + +--- + +**NeoVim Version** +Output of `nvim --version` + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Please provide a minimal `init.lua` to reproduce which can be run as the following: +```sh +nvim --clean -u minimal.lua +``` + +You can edit the following example file to include your adapters and other required setup. +```lua +-- ignore default config and plugins +vim.opt.runtimepath:remove(vim.fn.expand("~/.config/nvim")) +vim.opt.packpath:remove(vim.fn.expand("~/.local/share/nvim/site")) +vim.opt.termguicolors = true + +-- append test directory +local test_dir = "/tmp/nvim-config" +vim.opt.runtimepath:append(vim.fn.expand(test_dir)) +vim.opt.packpath:append(vim.fn.expand(test_dir)) + +-- install packer +local install_path = test_dir .. "/pack/packer/start/packer.nvim" +local install_plugins = false + +if vim.fn.empty(vim.fn.glob(install_path)) > 0 then + vim.cmd("!git clone https://github.com/wbthomason/packer.nvim " .. install_path) + vim.cmd("packadd packer.nvim") + install_plugins = true +end + +local packer = require("packer") + +packer.init({ + package_root = test_dir .. "/pack", + compile_path = test_dir .. "/plugin/packer_compiled.lua", +}) + +packer.startup(function(use) + use("wbthomason/packer.nvim") + + use({ + "nvim-neotest/neotest", + requires = { + "vim-test/vim-test", + "nvim-lua/plenary.nvim", + "nvim-treesitter/nvim-treesitter", + "antoinemadec/FixCursorHold.nvim", + }, + config = function() + require("neotest").setup({ + adapters = {}, + }) + end, + }) + + if install_plugins then + packer.sync() + end +end) + +vim.cmd([[ +command! NeotestSummary lua require("neotest").summary.toggle() +command! NeotestFile lua require("neotest").run.run(vim.fn.expand("%")) +command! Neotest lua require("neotest").run.run(vim.fn.getcwd()) +command! NeotestNearest lua require("neotest").run.run() +command! NeotestDebug lua require("neotest").run.run({ strategy = "dap" }) +command! NeotestAttach lua require("neotest").run.attach() +command! NeotestOutput lua require("neotest").output.open() +]]) +``` + +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +Please provide example test files to reproduce. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Logs** +1. Wipe the `neotest.log` file in `stdpath("log")` or `stdpath("data")`. +2. Set `log_level = vim.log.levels.DEBUG` in your neotest setup config. +3. Reproduce the issue. +4. Provide the new logs. + +**Additional context** +Add any other context about the problem here. diff --git a/.github/workflows/docgen.yaml b/.github/workflows/docgen.yaml new file mode 100644 index 0000000..c5ca0bb --- /dev/null +++ b/.github/workflows/docgen.yaml @@ -0,0 +1,55 @@ +# Taken from telescope +name: Generate docs + +on: + push: + branches-ignore: + - master + pull_request: ~ + +jobs: + build-sources: + name: Generate docs + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-20.04 + url: https://github.com/neovim/neovim/releases/download/v0.5.1/nvim-linux64.tar.gz + steps: + - uses: actions/checkout@v2 + - run: date +%F > todays-date + - name: Restore cache for today's nightly. + uses: actions/cache@v2 + with: + path: _neovim + key: ${{ runner.os }}-${{ matrix.url }}-${{ hashFiles('todays-date') }} + + - name: Prepare + run: | + test -d _neovim || { + mkdir -p _neovim + curl -sL ${{ matrix.url }} | tar xzf - --strip-components=1 -C "${PWD}/_neovim" + } + mkdir -p ~/.local/share/nvim/site/pack/vendor/start + git clone --depth 1 https://github.com/echasnovski/mini.nvim ~/.local/share/nvim/site/pack/vendor/start/mini.nvim + - name: Generating docs + run: | + export PATH="${PWD}/_neovim/bin:${PATH}" + export VIM="${PWD}/_neovim/share/nvim/runtime" + nvim --version + ./scripts/docgen + - name: Update documentation + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + COMMIT_MSG: | + docs: update doc/neotest.txt + skip-checks: true + run: | + git config user.email "actions@github" + git config user.name "Github Actions" + git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git + git add doc/ + # Only commit and push if we have changes + git diff --quiet && git diff --staged --quiet || (git commit -m "${COMMIT_MSG}"; git push origin HEAD:${GITHUB_REF}) diff --git a/.github/workflows/issues.yaml b/.github/workflows/issues.yaml new file mode 100644 index 0000000..bc024b5 --- /dev/null +++ b/.github/workflows/issues.yaml @@ -0,0 +1,16 @@ +name: Add issues to tracking project + +on: + issues: + types: + - opened + +jobs: + add-to-project: + name: Add issue to project + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@v0.3.0 + with: + project-url: https://github.com/orgs/nvim-neotest/projects/1 + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/luarocks-release.yaml b/.github/workflows/luarocks-release.yaml new file mode 100644 index 0000000..a11cb9e --- /dev/null +++ b/.github/workflows/luarocks-release.yaml @@ -0,0 +1,29 @@ +--- +on: + release: + types: + - created + push: + tags: + - '*' + workflow_dispatch: # Allow manual trigger + pull_request: # Tests the luarocks installation without releasing on PR + +jobs: + luarocks-upload: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Get Version + # tags do not trigger the workflow when they are created by other workflows or releases + run: echo "LUAROCKS_VERSION=$(git describe --abbrev=0 --tags)" >> $GITHUB_ENV + - name: LuaRocks Upload + uses: nvim-neorocks/luarocks-tag-release@v5 + env: + LUAROCKS_API_KEY: ${{ secrets.LUAROCKS_API_KEY }} + with: + version: ${{ env.LUAROCKS_VERSION }} + dependencies: | + plenary.nvim diff --git a/.github/workflows/workflow.yaml b/.github/workflows/workflow.yaml new file mode 100644 index 0000000..3872842 --- /dev/null +++ b/.github/workflows/workflow.yaml @@ -0,0 +1,77 @@ +name: neotest Workflow +on: + push: + branches: + - master + pull_request: ~ +jobs: + style: + name: style + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + - uses: JohnnyMorganz/stylua-action@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + version: latest + args: --check lua/ tests/ + + tests: + name: tests + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-22.04 + rev: nightly/nvim-linux64.tar.gz + - os: ubuntu-22.04 + rev: v0.9.1/nvim-linux64.tar.gz + steps: + - uses: actions/checkout@v3 + - run: date +%F > todays-date + - name: Restore cache for today's nightly. + uses: actions/cache@v3 + with: + path: _neovim + key: ${{ runner.os }}-${{ matrix.rev }}-${{ hashFiles('todays-date') }} + + - name: Prepare dependencies + run: | + test -d _neovim || { + mkdir -p _neovim + curl -sL "https://github.com/neovim/neovim/releases/download/${{ matrix.rev }}" | tar xzf - --strip-components=1 -C "${PWD}/_neovim" + } + mkdir -p ~/.local/share/nvim/site/pack/vendor/start + git clone --depth 1 https://github.com/nvim-lua/plenary.nvim ~/.local/share/nvim/site/pack/vendor/start/plenary.nvim + ln -s $(pwd) ~/.local/share/nvim/site/pack/vendor/start + export PATH="${PWD}/_neovim/bin:${PATH}" + export VIM="${PWD}/_neovim/share/nvim/runtime" + + - name: Run tests + run: | + export PATH="${PWD}/_neovim/bin:${PATH}" + export VIM="${PWD}/_neovim/share/nvim/runtime" + nvim --version + ./scripts/test + + release: + name: release + if: ${{ github.ref == 'refs/heads/master' }} + needs: + - style + - tests + runs-on: ubuntu-22.04 + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: Setup Node.js + uses: actions/setup-node@v1 + with: + node-version: 18 + - name: Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: npx semantic-release diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1366906 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +neovim/ +plenary.nvim/ +doc/tags +Session.vim diff --git a/.releaserc.json b/.releaserc.json new file mode 100644 index 0000000..cba54f7 --- /dev/null +++ b/.releaserc.json @@ -0,0 +1,12 @@ +{ + "plugins": [ + "@semantic-release/commit-analyzer", + "@semantic-release/release-notes-generator", + [ + "@semantic-release/github", + { + "successComment": false + } + ] + ] +} diff --git a/LICENCE.md b/LICENCE.md new file mode 100644 index 0000000..2a81858 --- /dev/null +++ b/LICENCE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Rónán Carrigan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index e69de29..e7b5bea 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,178 @@ +# nvim-nio + +A library for asynchronous IO in Neovim, inspired by the asyncio library in Python. The library focuses on providing +both common asynchronous primitives and asynchronous APIs for Neovim's core. + +## Motivation + +Work has been ongoing around async libraries in Neovim for years, with a lot of discussion around a [Neovim core +implementation](https://github.com/neovim/neovim/issues/19624). A lot of the motivation behind this library can be seen +in that discussion. + +nvim-nio aims to provide a simple interface to Lua coroutines that doesn't feel like it gets in the way of your actual +logic. You won't even know you're using them. An example of this is error handling. With other libraries, a custom +`pcall` or some other custom handling must be used to catch errors. With nvim-nio, Lua's built-in `pcall` works exactly +as you'd expect. + +nvim-nio is focused on providing a great developer experience. The API is well documented with examples and full type +annotations, which can all be used by the Lua LSP. It's recommended to use +[neodev.nvim](https://github.com/folke/neodev.nvim) to get LSP support. + +![image](https://github.com/nvim-lua/plenary.nvim/assets/24252670/0dda462c-0b5c-4300-8e65-b7218e3d2c1e) + +Credit to the async library in [plenary.nvim](https://github.com/nvim-lua/plenary.nvim) and +[async.nvim](https://github.com/lewis6991/async.nvim) for inspiring nvim-nio and its implementation. +If Neovim core integrates an async library, nvim-nio will aim to maintain compatibility with it if possible. + +## Installation + +Install with your favourite package manager + +[lazy.nvim](https://github.com/folke/lazy.nvim) + +```lua +{ "nvim-neotest/nvim-nio" } +``` + +[dein](https://github.com/Shougo/dein.vim): + +```vim +call dein#add("nvim-neotest/nvim-nio") +``` + +[vim-plug](https://github.com/junegunn/vim-plug) + +```vim +Plug 'nvim-neotest/nvim-nio' +``` + +[packer.nvim](https://github.com/wbthomason/packer.nvim) + +```lua +use { "nvim-neotest/nvim-nio" } +``` + +## Configuration + +There are no configuration options currently available. + +## Usage + +nvim-nio is based on the concept of tasks. These tasks represent a series of asynchronous actions that run in a single +context. Under the hood, each task is running on a separate lua coroutine. + +Tasks are created by providing an async function to `nio.run`. All async +functions must be called from a task. + +```lua +local nio = require("nio") + +local task = nio.run(function() + nio.sleep(10) + print("Hello world") +end) +``` + +For simple use cases tasks won't be too important but they support features such as cancelling and retrieving stack traces. + +nvim-nio comes with built-in modules to help with writing async code. See `:help nvim-nio` for extensive documentation. + +`nio.control`: Primitives for flow control in async functions + +```lua +local event = nio.control.event() + +local worker = nio.tasks.run(function() + nio.sleep(1000) + event.set() +end) + +local listeners = { + nio.tasks.run(function() + event.wait() + print("First listener notified") + end), + nio.tasks.run(function() + event.wait() + print("Second listener notified") + end), +} +``` + +`nio.lsp`: A fully typed and documented async LSP client library, generated from the LSP specification. + +```lua +local client = nio.lsp.get_clients({ name = "lua_ls" })[1] + +local err, response = client.request.textDocument_semanticTokens_full({ + textDocument = { uri = vim.uri_from_bufnr(0) }, +}) + +assert(not err, err) + +for _, token in pairs(response.data) do + print(token) +end +``` + +`nio.uv`: Async versions of `vim.loop` functions + +```lua +local file_path = "README.md" + +local open_err, file_fd = nio.uv.fs_open(file_path, "r", 438) +assert(not open_err, open_err) + +local stat_err, stat = nio.uv.fs_fstat(file_fd) +assert(not stat_err, stat_err) + +local read_err, data = nio.uv.fs_read(file_fd, stat.size, 0) +assert(not read_err, read_err) + +local close_err = nio.uv.fs_close(file_fd) +assert(not close_err, close_err) + +print(data) +``` + +`nio.ui`: Async versions of vim.ui functions + +```lua +local value = nio.ui.input({ prompt = "Enter something: " }) +print(("You entered: %s"):format(value)) +``` + +`nio.tests`: Async versions of plenary.nvim's test functions + +```lua +nio.tests.it("notifies listeners", function() + local event = nio.control.event() + local notified = 0 + for _ = 1, 10 do + nio.run(function() + event.wait() + notified = notified + 1 + end) + end + + event.set() + nio.sleep(10) + assert.equals(10, notified) +end) +``` + +It is also easy to wrap callback style functions to make them asynchronous using `nio.wrap`, which allows easily +integrating third-party APIs with nvim-nio. + +```lua +local nio = require("nio") + +local sleep = nio.wrap(function(ms, cb) + vim.defer_fn(cb, ms) +end, 2) + +nio.run(function() + sleep(10) + print("Slept for 10ms") +end) +``` diff --git a/doc/nio.txt b/doc/nio.txt new file mode 100644 index 0000000..c128846 --- /dev/null +++ b/doc/nio.txt @@ -0,0 +1,556 @@ +*nvim-nio.txt* A library for asynchronous IO in Neovim + +============================================================================== +nvim-nio *nvim-nio* + + nio....................................................................|nio| + nio.control....................................................|nio.control| + nio.lsp............................................................|nio.lsp| + nio.uv..............................................................|nio.uv| + nio.ui..............................................................|nio.ui| + nio.tests........................................................|nio.tests| + + +A library for asynchronous IO in Neovim, inspired by the asyncio library in +Python. The library focuses on providing both common asynchronous primitives +and asynchronous APIs for Neovim's core. + +nio *nio* + + + *nio.run()* +`run`({func}, {cb}) + +Run a function in an async context. This is the entrypoint to all async +functionality. +>lua + local nio = require("nio") + nio.run(function() + nio.sleep(10) + print("Hello world") + end) +< +Parameters~ +{func} `(function)` +{cb?} `(fun(success: boolean,...))` Callback to invoke when the task is +complete. If success is false then the parameters will be an error message and +a traceback of the error, otherwise it will be the result of the async +function. +Return~ +`(nio.tasks.Task)` + + *nio.wrap()* +`wrap`({func}, {argc}) + +Creates an async function with a callback style function. +>lua + local nio = require("nio") + local sleep = nio.wrap(function(ms, cb) + vim.defer_fn(cb, ms) + end, 2) + + nio.run(function() + sleep(10) + print("Slept for 10ms") + end) +< +Parameters~ +{func} `(function)` A callback style function to be converted. The last +argument must be the callback. +{argc} `(integer)` The number of arguments of func. Must be included. +Return~ +`(function)` Returns an async function + + *nio.create()* +`create`({func}, {argc}) + +Takes an async function and returns a function that can run in both async +and non async contexts. When running in an async context, the function can +return values, but when run in a non-async context, a Task object is +returned and an extra callback argument can be supplied to receive the +result, with the same signature as the callback for `nio.run`. + +This is useful for APIs where users don't want to create async +contexts but which are still used in async contexts internally. +Parameters~ +{func} `(async fun(...))` +{argc?} `(integer)` The number of arguments of func. Must be included if there +are arguments. + + *nio.gather()* +`gather`({functions}) + +Run a collection of async functions concurrently and return when +all have finished. +If any of the functions fail, all pending tasks will be cancelled and the +error will be re-raised + +Parameters~ +{functions} `(function[])` +Return~ +`(any[])` Results of all functions + + *nio.first()* +`first`({functions}) + +Run a collection of async functions concurrently and return the result of +the first to finish. + +Parameters~ +{functions} `(function[])` +Return~ +`(any)` + + *nio.sleep()* +`sleep`({ms}) + +Suspend the current task for given time. +Parameters~ +{ms} `(number)` Time in milliseconds + + *nio.scheduler()* +`scheduler`() + +Yields to the Neovim scheduler to be able to call the API. + + +nio.api *nio.api* + +Safely proxies calls to the vim.api module while in an async context. + +nio.fn *nio.fn* + +Safely proxies calls to the vim.fn module while in an async context. + + +============================================================================== +nio.control *nio.control* + + +Provides primitives for flow control in async functions + + *nio.control.event()* +`event`() + +Create a new event + +An event can signal to multiple listeners to resume execution +The event can be set from a non-async context. + +>lua + local event = nio.control.event() + + local worker = nio.tasks.run(function() + nio.sleep(1000) + event.set() + end) + + local listeners = { + nio.tasks.run(function() + event.wait() + print("First listener notified") + end), + nio.tasks.run(function() + event.wait() + print("Second listener notified") + end), + } +< +Return~ +`(nio.control.Event)` + + *nio.control.Event* +Fields~ +{set} `(fun(max_woken?: integer): nil)` Set the event and signal to all (or +limited number of) listeners that the event has occurred. If max_woken is +provided and there are more listeners then the event is cleared immediately +{wait} `(async fun(): nil)` Wait for the event to occur, returning immediately +if +already set +{clear} `(fun(): nil)` Clear the event +{is_set} `(fun(): boolean)` Returns true if the event is set + + *nio.control.future()* +`future`() + +Create a new future + +An future represents a value that will be available at some point and can be awaited upon. +The future result can be set from a non-async context. +>lua + local future = nio.control.future() + + nio.run(function() + nio.sleep(100 * math.random(1, 10)) + if not future.is_set() then + future.set("Success!") + end + end) + nio.run(function() + nio.sleep(100 * math.random(1, 10)) + if not future.is_set() then + future.set_error("Failed!") + end + end) + + local success, value = pcall(future.wait) + print(("%s: %s"):format(success, value)) +< +Return~ +`(nio.control.Future)` + + *nio.control.Future* +Fields~ +{set} `(fun(value): nil)` Set the future value and wake all waiters. +{set_error} `(fun(message): nil)` Set the error for this future to raise to +waiters +{wait} `(async fun(): any)` Wait for the value to be set, returning +immediately if already set +{is_set} `(fun(): boolean)` Returns true if the future is set + + *nio.control.queue()* +`queue`({max_size}) + +Create a new FIFO queue with async support. +>lua + local queue = nio.control.queue() + + local producer = nio.tasks.run(function() + for i = 1, 10 do + nio.sleep(100) + queue.put(i) + end + queue.put(nil) + end) + + while true do + local value = queue.get() + if value == nil then + break + end + print(value) + end + print("Done") +< +Parameters~ +{max_size?} `(integer)` The maximum number of items in the queue, defaults to +no limit +Return~ +`(nio.control.Queue)` + + *nio.control.Queue* +Fields~ +{size} `(fun(): number)` Returns the number of items in the queue +{max_size} `(fun(): number|nil)` Returns the maximum number of items in the +queue +{get} `(async fun(): any)` Get a value from the queue, blocking if the queue +is empty +{get_nowait} `(fun(): any)` Get a value from the queue, erroring if queue is +empty. +{put} `(async fun(value: any): nil)` Put a value into the queue +{put_nowait} `(fun(value: any): nil)` Put a value into the queue, erroring if +queue is full. + + *nio.control.semaphore()* +`semaphore`({value}) + +Create an async semaphore that allows up to a given number of acquisitions. + +>lua + local semaphore = nio.control.semaphore(2) + + local value = 0 + for _ = 1, 10 do + nio.run(function() + semaphore.with(function() + value = value + 1 + + nio.sleep(10) + print(value) -- Never more than 2 + + value = value - 1 + end) + end) + end +< +Parameters~ +{value} `(integer)` The number of allowed concurrent acquisitions +Return~ +`(nio.control.Semaphore)` + + *nio.control.Semaphore* +Fields~ +{with} `(async fun(callback: fun(): nil): nil)` Run the callback with the +semaphore acquired +{acquire} `(async fun(): nil)` Acquire the semaphore +{release} `(fun(): nil)` Release the semaphore + + +============================================================================== +nio.lsp *nio.lsp* + + + *nio.lsp.Client* +Fields~ +{request} `(nio.lsp.RequestClient)` Interface to all requests that can be sent +by the client +{notify} `(nio.lsp.NotifyClient)` Interface to all notifications that can be +sent by the client +{server_capabilities} `(nio.lsp.types.ServerCapabilities)` + + *nio.lsp.get_clients()* +`get_clients`({filters}) + +Get active clients, optionally matching the given filters +Equivalent to |vim.lsp.get_clients| +Parameters~ +{filters?} `(nio.lsp.GetClientsFilters)` +Return~ +`(nio.lsp.Client[])` + + *nio.lsp.GetClientsFilters* +Fields~ +{id?} `(integer)` +{name?} `(string)` +{bufnr?} `(integer)` +{method?} `(string)` + + *nio.lsp.client()* +`client`({client_id}) + +an async client for the given client id +Parameters~ +{client_id} `(integer)` +Return~ +`(nio.lsp.Client)` + + +============================================================================== +nio.uv *nio.uv* + + +Provides asynchronous versions of vim.loop functions. +See corresponding function documentation for parameter and return +information. +>lua + local file_path = "README.md" + + local open_err, file_fd = nio.uv.fs_open(file_path, "r", 438) + assert(not open_err, open_err) + + local stat_err, stat = nio.uv.fs_fstat(file_fd) + assert(not stat_err, stat_err) + + local read_err, data = nio.uv.fs_read(file_fd, stat.size, 0) + assert(not read_err, read_err) + + local close_err = nio.uv.fs_close(file_fd) + assert(not close_err, close_err) + + print(data) +< + +Fields~ +{close} `(async fun(handle: nio.uv.Handle))` +{fs_open} `(async fun(path: any, flags: any, mode: any): +(string|nil,integer|nil))` +{fs_read} `(async fun(fd: integer, size: integer, offset?: integer): +(string|nil,string|nil))` +{fs_close} `(async fun(fd: integer): (string|nil,boolean|nil))` +{fs_unlink} `(async fun(path: string): (string|nil,boolean|nil))` +{fs_write} `(async fun(fd: any, data: any, offset?: any): +(string|nil,integer|nil))` +{fs_mkdir} `(async fun(path: string, mode: integer): +(string|nil,boolean|nil))` +{fs_mkdtemp} `(async fun(template: string): (string|nil,string|nil))` +{fs_rmdir} `(async fun(path: string): (string|nil,boolean|nil))` +{fs_stat} `(async fun(path: string): (string|nil,nio.uv.Stat|nil))` +{fs_fstat} `(async fun(fd: integer): (string|nil,nio.uv.Stat|nil))` +{fs_lstat} `(async fun(path: string): (string|nil,nio.uv.Stat|nil))` +{fs_statfs} `(async fun(path: string): (string|nil,nio.uv.StatFs|nil))` +{fs_rename} `(async fun(old_path: string, new_path: string): +(string|nil,boolean|nil))` +{fs_fsync} `(async fun(fd: integer): (string|nil,boolean|nil))` +{fs_fdatasync} `(async fun(fd: integer): (string|nil,boolean|nil))` +{fs_ftruncate} `(async fun(fd: integer, offset: integer): +(string|nil,boolean|nil))` +{fs_sendfile} `(async fun(out_fd: integer, in_fd: integer, in_offset: integer, +length: integer): (string|nil,integer|nil))` +{fs_access} `(async fun(path: string, mode: integer): +(string|nil,boolean|nil))` +{fs_chmod} `(async fun(path: string, mode: integer): +(string|nil,boolean|nil))` +{fs_fchmod} `(async fun(fd: integer, mode: integer): +(string|nil,boolean|nil))` +{fs_utime} `(async fun(path: string, atime: number, mtime: number): +(string|nil,boolean|nil))` +{fs_futime} `(async fun(fd: integer, atime: number, mtime: number): +(string|nil,boolean|nil))` +{fs_link} `(async fun(path: string, new_path: string): +(string|nil,boolean|nil))` +{fs_symlink} `(async fun(path: string, new_path: string, flags?: integer): +(string|nil,boolean|nil))` +{fs_readlink} `(async fun(path: string): (string|nil,string|nil))` +{fs_realpath} `(async fun(path: string): (string|nil,string|nil))` +{fs_chown} `(async fun(path: string, uid: integer, gid: integer): +(string|nil,boolean|nil))` +{fs_fchown} `(async fun(fd: integer, uid: integer, gid: integer): +(string|nil,boolean|nil))` +{fs_lchown} `(async fun(path: string, uid: integer, gid: integer): +(string|nil,boolean|nil))` +{fs_copyfile} `(async fun(path: any, new_path: any, flags?: any): +(string|nil,boolean|nil))` +{fs_opendir} `(async fun(path: string, entries?: integer): +(string|nil,nio.uv.Dir|nil))` +{fs_readdir} `(async fun(dir: nio.uv.Dir): +(string|nil,nio.uv.DirEntry[]|nil))` +{fs_closedir} `(async fun(dir: nio.uv.Dir): (string|nil,boolean|nil))` +{fs_scandir} `(async fun(path: string): (string|nil,nio.uv.DirEntry[]|nil))` +{shutdown} `(async fun(stream: nio.uv.Stream): string|nil)` +{listen} `(async fun(stream: nio.uv.Stream, backlog: integer): string|nil)` +{write} `(async fun(stream: nio.uv.Stream, data: string|string[]): +string|nil)` +{write2} `(async fun(stream: nio.uv.Stream, data: string|string[], +send_handle: nio.uv.Stream): string|nil)` + + *nio.uv.Handle* + + *nio.uv.Stream* +Inherits: `nio.uv.Handle` + + + *nio.uv.Stat* +Fields~ +{dev} `(integer)` +{mode} `(integer)` +{nlink} `(integer)` +{uid} `(integer)` +{gid} `(integer)` +{rdev} `(integer)` +{ino} `(integer)` +{size} `(integer)` +{blksize} `(integer)` +{blocks} `(integer)` +{flags} `(integer)` +{gen} `(integer)` +{atime} `(nio.uv.StatTime)` +{mtime} `(nio.uv.StatTime)` +{ctime} `(nio.uv.StatTime)` +{birthtime} `(nio.uv.StatTime)` +{type} `(string)` + + *nio.uv.StatTime* +Fields~ +{sec} `(integer)` +{nsec} `(integer)` + + *nio.uv.StatFs* +Fields~ +{type} `(integer)` +{bsize} `(integer)` +{blocks} `(integer)` +{bfree} `(integer)` +{bavail} `(integer)` +{files} `(integer)` +{ffree} `(integer)` + + *nio.uv.Dir* + + *nio.uv.DirEntry* + + +============================================================================== +nio.ui *nio.ui* + + +Async versions of vim.ui functions. + + *nio.ui.input()* +`input`({args}) + +Prompt the user for input. +See |vim.ui.input()| for details. +>lua + local value = nio.ui.input({ prompt = "Enter something: " }) + print(("You entered: %s"):format(value)) +< + +Parameters~ +{args} `(nio.ui.InputArgs)` + + *nio.ui.InputArgs* +Fields~ +{prompt} `(string|nil)` Text of the prompt +{default} `(string|nil)` Default reply to the input +{completion} `(string|nil)` Specifies type of completion supported for input. +Supported types are the same that can be supplied to a user-defined command +using the "-complete=" argument. See |:command-completion| +{highlight} `(function)` Function that will be used for highlighting user +inputs. + + *nio.ui.select()* +`select`({items}, {args}) + +Prompts the user to pick from a list of items +See |vim.ui.select()| for details. +< + local value = nio.ui.select({ "foo", "bar", "baz" }, { prompt = "Select something: " }) + print(("You entered: %s"):format(value)) +< + +Parameters~ +{items} `(any[])` +{args} `(nio.ui.SelectArgs)` + + *nio.ui.SelectArgs* +Fields~ +{prompt} `(string|nil)` Text of the prompt. Defaults to `Select one of:` +{format_item} `(function|nil)` Function to format an individual item from +`items`. Defaults to `tostring`. +{kind} `(string|nil)` Arbitrary hint string indicating the item shape. Plugins +reimplementing `vim.ui.select` may wish to use this to infer the structure or +semantics of `items`, or the context in which select() was called. + + +============================================================================== +nio.tests *nio.tests* + + +Wrappers around plenary.nvim's test functions for writing async tests +>lua + a.it("notifies listeners", function() + local event = nio.control.event() + local notified = 0 + for _ = 1, 10 do + nio.run(function() + event.wait() + notified = notified + 1 + end) + end + + event.set() + nio.sleep(10) + assert.equals(10, notified) + end) + + *nio.tests.it()* +`it`({name}, {async_func}) + +Parameters~ +{name} `(string)` +{async_func} `(function)` + + *nio.tests.before_each()* +`before_each`({async_func}) + +Parameters~ +{async_func} `(function)` + + *nio.tests.after_each()* +`after_each`({async_func}) + +Parameters~ +{async_func} `(function)` + + + vim:tw=78:ts=8:noet:ft=help:norl: \ No newline at end of file diff --git a/lua/nio/control.lua b/lua/nio/control.lua new file mode 100644 index 0000000..73f20cf --- /dev/null +++ b/lua/nio/control.lua @@ -0,0 +1,304 @@ +local tasks = require("nio.tasks") + +local nio = {} + +---@toc_entry nio.control +---@text +--- Provides primitives for flow control in async functions +---@class nio.control +nio.control = {} + +--- Create a new event +--- +--- An event can signal to multiple listeners to resume execution +--- The event can be set from a non-async context. +--- +--- ```lua +--- local event = nio.control.event() +--- +--- local worker = nio.tasks.run(function() +--- nio.sleep(1000) +--- event.set() +--- end) +--- +--- local listeners = { +--- nio.tasks.run(function() +--- event.wait() +--- print("First listener notified") +--- end), +--- nio.tasks.run(function() +--- event.wait() +--- print("Second listener notified") +--- end), +--- } +--- ``` +---@return nio.control.Event +function nio.control.event() + local waiters = {} + local is_set = false + return { + is_set = function() + return is_set + end, + set = function(max_woken) + if is_set then + return + end + is_set = true + local waiters_to_notify = {} + max_woken = max_woken or #waiters + while #waiters > 0 and #waiters_to_notify < max_woken do + waiters_to_notify[#waiters_to_notify + 1] = table.remove(waiters) + end + if #waiters > 0 then + is_set = false + end + for _, waiter in ipairs(waiters_to_notify) do + waiter() + end + end, + wait = tasks.wrap(function(callback) + if is_set then + callback() + else + waiters[#waiters + 1] = callback + end + end, 1), + clear = function() + is_set = false + end, + } +end + +---@class nio.control.Event +---@field set fun(max_woken?: integer): nil Set the event and signal to all (or limited number of) listeners that the event has occurred. If max_woken is provided and there are more listeners then the event is cleared immediately +---@field wait async fun(): nil Wait for the event to occur, returning immediately if +--- already set +---@field clear fun(): nil Clear the event +---@field is_set fun(): boolean Returns true if the event is set + +--- Create a new future +--- +--- An future represents a value that will be available at some point and can be awaited upon. +--- The future result can be set from a non-async context. +--- ```lua +--- local future = nio.control.future() +--- +--- nio.run(function() +--- nio.sleep(100 * math.random(1, 10)) +--- if not future.is_set() then +--- future.set("Success!") +--- end +--- end) +--- nio.run(function() +--- nio.sleep(100 * math.random(1, 10)) +--- if not future.is_set() then +--- future.set_error("Failed!") +--- end +--- end) +--- +--- local success, value = pcall(future.wait) +--- print(("%s: %s"):format(success, value)) +--- ``` +---@return nio.control.Future +function nio.control.future() + local waiters = {} + local result, err, is_set + local wait = tasks.wrap(function(callback) + if is_set then + callback() + else + waiters[#waiters + 1] = callback + end + end, 1) + local wake = function() + for _, waiter in ipairs(waiters) do + waiter() + end + end + return { + is_set = function() + return is_set + end, + set = function(value) + if is_set then + error("Future already set") + end + result = value + is_set = true + wake() + end, + set_error = function(message) + if is_set then + error("Future already set") + end + err = message + is_set = true + wake() + end, + wait = function() + if not is_set then + wait() + end + + if err then + error(err) + end + return result + end, + } +end + +---@class nio.control.Future +---@field set fun(value): nil Set the future value and wake all waiters. +---@field set_error fun(message): nil Set the error for this future to raise to +---the waiters +---@field wait async fun(): any Wait for the value to be set, returning immediately if already set +---@field is_set fun(): boolean Returns true if the future is set + +--- Create a new FIFO queue with async support. +--- ```lua +--- local queue = nio.control.queue() +--- +--- local producer = nio.tasks.run(function() +--- for i = 1, 10 do +--- nio.sleep(100) +--- queue.put(i) +--- end +--- queue.put(nil) +--- end) +--- +--- while true do +--- local value = queue.get() +--- if value == nil then +--- break +--- end +--- print(value) +--- end +--- print("Done") +--- ``` +---@param max_size? integer The maximum number of items in the queue, defaults to no limit +---@return nio.control.Queue +function nio.control.queue(max_size) + local items = {} + local left_i = 0 + local right_i = 0 + local non_empty = nio.control.event() + local non_full = nio.control.event() + non_full.set() + + local queue = {} + + function queue.size() + return right_i - left_i + end + + function queue.max_size() + return max_size + end + + function queue.put(value) + non_full.wait() + queue.put_nowait(value) + end + + function queue.get() + non_empty.wait() + return queue.get_nowait() + end + + function queue.get_nowait() + if queue.size() == 0 then + error("Queue is empty") + end + left_i = left_i + 1 + local item = items[left_i] + items[left_i] = nil + if left_i == right_i then + non_empty.clear() + end + non_full.set(1) + return item + end + + function queue.put_nowait(value) + if queue.size() == max_size then + error("Queue is full") + end + right_i = right_i + 1 + items[right_i] = value + non_empty.set(1) + if queue.size() == max_size then + non_full.clear() + end + end + + return queue +end + +---@class nio.control.Queue +---@field size fun(): number Returns the number of items in the queue +---@field max_size fun(): number|nil Returns the maximum number of items in the queue +---@field get async fun(): any Get a value from the queue, blocking if the queue is empty +---@field get_nowait fun(): any Get a value from the queue, erroring if queue is empty. +---@field put async fun(value: any): nil Put a value into the queue +---@field put_nowait fun(value: any): nil Put a value into the queue, erroring if queue is full. + +--- Create an async semaphore that allows up to a given number of acquisitions. +--- +--- ```lua +--- local semaphore = nio.control.semaphore(2) +--- +--- local value = 0 +--- for _ = 1, 10 do +--- nio.run(function() +--- semaphore.with(function() +--- value = value + 1 +--- +--- nio.sleep(10) +--- print(value) -- Never more than 2 +--- +--- value = value - 1 +--- end) +--- end) +--- end +--- ``` +---@param value integer The number of allowed concurrent acquisitions +---@return nio.control.Semaphore +function nio.control.semaphore(value) + value = value or 1 + local released_event = nio.control.event() + released_event.set() + local acquire = function() + released_event.wait() + value = value - 1 + assert(value >= 0, "Semaphore value is negative") + if value == 0 then + released_event.clear() + end + end + local release = function() + value = value + 1 + released_event.set(1) + end + return { + acquire = acquire, + release = release, + + with = function(cb) + acquire() + local success, err = pcall(cb) + release() + if not success then + error(err) + end + end, + } +end + +---@class nio.control.Semaphore +---@field with async fun(callback: fun(): nil): nil Run the callback with the semaphore acquired +---@field acquire async fun(): nil Acquire the semaphore +---@field release fun(): nil Release the semaphore + +return nio.control diff --git a/lua/nio/init.lua b/lua/nio/init.lua new file mode 100644 index 0000000..c2e5502 --- /dev/null +++ b/lua/nio/init.lua @@ -0,0 +1,197 @@ +local nio = {} +local tasks = require("nio.tasks") +local control = require("nio.control") +local uv = require("nio.uv") +local tests = require("nio.tests") +local ui = require("nio.ui") +local lsp = require("nio.lsp") + +---@tag nvim-nio + +---@toc + +---@text +--- +--- A library for asynchronous IO in Neovim, inspired by the asyncio library in +--- Python. The library focuses on providing both common asynchronous primitives +--- and asynchronous APIs for Neovim's core. + +---@toc_entry nio +---@class nio +nio = {} + +nio.control = control +nio.uv = uv +nio.ui = ui +nio.tests = tests +nio.tasks = tasks +nio.lsp = lsp + +--- Run a function in an async context. This is the entrypoint to all async +--- functionality. +--- ```lua +--- local nio = require("nio") +--- nio.run(function() +--- nio.sleep(10) +--- print("Hello world") +--- end) +--- ``` +---@param func function +---@param cb? fun(success: boolean,...) Callback to invoke when the task is complete. If success is false then the parameters will be an error message and a traceback of the error, otherwise it will be the result of the async function. +---@return nio.tasks.Task +function nio.run(func, cb) + return tasks.run(func, cb) +end + +--- Creates an async function with a callback style function. +--- ```lua +--- local nio = require("nio") +--- local sleep = nio.wrap(function(ms, cb) +--- vim.defer_fn(cb, ms) +--- end, 2) +--- +--- nio.run(function() +--- sleep(10) +--- print("Slept for 10ms") +--- end) +--- ``` +---@param func function A callback style function to be converted. The last argument must be the callback. +---@param argc integer The number of arguments of func. Must be included. +---@return function Returns an async function +function nio.wrap(func, argc) + return tasks.wrap(func, argc) +end + +--- Takes an async function and returns a function that can run in both async +--- and non async contexts. When running in an async context, the function can +--- return values, but when run in a non-async context, a Task object is +--- returned and an extra callback argument can be supplied to receive the +--- result, with the same signature as the callback for `nio.run`. +--- +--- This is useful for APIs where users don't want to create async +--- contexts but which are still used in async contexts internally. +---@param func async fun(...) +---@param argc? integer The number of arguments of func. Must be included if there are arguments. +function nio.create(func, argc) + return tasks.create(func, argc) +end + +--- Run a collection of async functions concurrently and return when +--- all have finished. +--- If any of the functions fail, all pending tasks will be cancelled and the +--- error will be re-raised +---@async +---@param functions function[] +---@return any[] Results of all functions +function nio.gather(functions) + local results = {} + + local done_event = control.event() + + local err + local running = {} + for i, func in ipairs(functions) do + local task = tasks.run(func, function(success, ...) + if not success then + err = ... + done_event.set() + end + results[#results + 1] = { i = i, success = success, result = ... } + if #results == #functions then + done_event.set() + end + end) + running[#running + 1] = task + end + done_event.wait() + if err then + for _, task in ipairs(running) do + task.cancel() + end + error(err) + end + local sorted = {} + for _, result in ipairs(results) do + sorted[result.i] = result.result + end + return sorted +end + +--- Run a collection of async functions concurrently and return the result of +--- the first to finish. +---@async +---@param functions function[] +---@return any +function nio.first(functions) + local running_tasks = {} + local event = control.event() + local failed, result + + for _, func in ipairs(functions) do + local task = tasks.run(func, function(success, ...) + if event.is_set() then + return + end + failed = not success + result = { ... } + event.set() + end) + table.insert(running_tasks, task) + end + event.wait() + for _, task in ipairs(running_tasks) do + task.cancel() + end + if failed then + error(unpack(result)) + end + return unpack(result) +end + +local async_defer = nio.wrap(function(time, cb) + assert(cb, "Cannot call sleep from non-async context") + vim.defer_fn(cb, time) +end, 2) + +--- Suspend the current task for given time. +---@param ms number Time in milliseconds +function nio.sleep(ms) + async_defer(ms) +end + +local wrapped_schedule = nio.wrap(vim.schedule, 1) + +--- Yields to the Neovim scheduler to be able to call the API. +---@async +function nio.scheduler() + wrapped_schedule() +end + +---@nodoc +local function proxy_vim(prop) + return setmetatable({}, { + __index = function(_, k) + return function(...) + -- if we are in a fast event await the scheduler + if vim.in_fast_event() then + nio.scheduler() + end + + return vim[prop][k](...) + end + end, + }) +end + +--- Safely proxies calls to the vim.api module while in an async context. +nio.api = proxy_vim("api") +--- Safely proxies calls to the vim.fn module while in an async context. +nio.fn = proxy_vim("fn") + +-- For type checking +if false then + nio.api = vim.api + nio.fn = vim.fn +end + +return nio diff --git a/lua/nio/logger.lua b/lua/nio/logger.lua new file mode 100644 index 0000000..5db3e64 --- /dev/null +++ b/lua/nio/logger.lua @@ -0,0 +1,103 @@ +local loggers = {} + +local log_date_format = "%FT%H:%M:%SZ%z" + +---@class nio.Logger +---@field trace function +---@field debug function +---@field info function +---@field warn function +---@field error function +local Logger = {} + +local LARGE = 1e9 + +---@return nio.Logger +function Logger.new(filename, opts) + opts = opts or {} + local logger = loggers[filename] + if logger then + return logger + end + logger = {} + setmetatable(logger, { __index = Logger }) + loggers[filename] = logger + local path_sep = (function() + if jit then + local os = string.lower(jit.os) + if os == "linux" or os == "osx" or os == "bsd" then + return "/" + else + return "\\" + end + else + return package.config:sub(1, 1) + end + end)() + + local function path_join(...) + return table.concat(vim.tbl_flatten({ ... }), path_sep) + end + + logger._level = opts.level or vim.log.levels.WARN + local ok, logpath = pcall(vim.fn.stdpath, "log") + if not ok then + logpath = vim.fn.stdpath("cache") + end + logger._filename = path_join(logpath, filename .. ".log") + + vim.fn.mkdir(logpath, "p") + local logfile = assert(io.open(logger._filename, "a+")) + + local log_info = vim.loop.fs_stat(logger._filename) + if log_info and log_info.size > LARGE then + local warn_msg = + string.format("Nio log is large (%d MB): %s", log_info.size / (1000 * 1000), logger._filename) + vim.notify(warn_msg, vim.log.levels.WARN) + end + + for level, levelnr in pairs(vim.log.levels) do + logger[level:lower()] = function(...) + local argc = select("#", ...) + if levelnr < logger._level then + return false + end + if argc == 0 then + return true + end + local info = debug.getinfo(2, "Sl") + local fileinfo = string.format("%s:%s", info.short_src, info.currentline) + local parts = { + table.concat({ level, "|", os.date(log_date_format), "|", fileinfo, "|" }, " "), + } + for i = 1, argc do + local arg = select(i, ...) + if arg == nil then + table.insert(parts, "") + elseif type(arg) == "string" then + table.insert(parts, arg) + elseif type(arg) == "table" and arg.__tostring then + table.insert(parts, arg.__tostring(arg)) + else + table.insert(parts, vim.inspect(arg)) + end + end + logfile:write(table.concat(parts, " "), "\n") + logfile:flush() + end + end + return logger +end + +function Logger:set_level(level) + self._level = assert( + type(level) == "number" and level or vim.log.levels[tostring(level):upper()], + string.format("Log level must be one of (trace, debug, info, warn, error), got: %q", level) + ) +end + +function Logger:get_filename() + return self._filename +end + +return Logger.new("nio") diff --git a/lua/nio/lsp-types.lua b/lua/nio/lsp-types.lua new file mode 100644 index 0000000..9a35e1e --- /dev/null +++ b/lua/nio/lsp-types.lua @@ -0,0 +1,3024 @@ +---Generated on 2023-12-20-15:46:43 GMT + +---@class nio.lsp.RequestClient +local LSPRequestClient = {} +---@class nio.lsp.RequestOpts +---@field timeout integer Timeout of request in milliseconds +---@class nio.lsp.types.ResponseError +---@field code number A number indicating the error type that occurred. +---@field message string A string providing a short description of the error. +---@field data any A Primitive or Structured value that contains additional information about the error. Can be omitted. + +--- A request to resolve the implementation locations of a symbol at a given text +--- document position. The request's parameter is of type {@link TextDocumentPositionParams} +--- the response is of type {@link Definition} or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.ImplementationParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.Definition|nio.lsp.types.DefinitionLink[]|nil result The result of the request +function LSPRequestClient.textDocument_implementation(args, bufnr, opts) end + +--- A request to resolve the type definition locations of a symbol at a given text +--- document position. The request's parameter is of type {@link TextDocumentPositionParams} +--- the response is of type {@link Definition} or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.TypeDefinitionParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.Definition|nio.lsp.types.DefinitionLink[]|nil result The result of the request +function LSPRequestClient.textDocument_typeDefinition(args, bufnr, opts) end + +--- A request to list all color symbols found in a given text document. The request's +--- parameter is of type {@link DocumentColorParams} the +--- response is of type {@link ColorInformation ColorInformation[]} or a Thenable +--- that resolves to such. +---@async +---@param args nio.lsp.types.DocumentColorParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.ColorInformation[]|nil result The result of the request +function LSPRequestClient.textDocument_documentColor(args, bufnr, opts) end + +--- A request to list all presentation for a color. The request's +--- parameter is of type {@link ColorPresentationParams} the +--- response is of type {@link ColorInformation ColorInformation[]} or a Thenable +--- that resolves to such. +---@async +---@param args nio.lsp.types.ColorPresentationParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.ColorPresentation[]|nil result The result of the request +function LSPRequestClient.textDocument_colorPresentation(args, bufnr, opts) end + +--- A request to provide folding ranges in a document. The request's +--- parameter is of type {@link FoldingRangeParams}, the +--- response is of type {@link FoldingRangeList} or a Thenable +--- that resolves to such. +---@async +---@param args nio.lsp.types.FoldingRangeParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.FoldingRange[]|nil result The result of the request +function LSPRequestClient.textDocument_foldingRange(args, bufnr, opts) end + +--- A request to resolve the type definition locations of a symbol at a given text +--- document position. The request's parameter is of type {@link TextDocumentPositionParams} +--- the response is of type {@link Declaration} or a typed array of {@link DeclarationLink} +--- or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.DeclarationParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.Declaration|nio.lsp.types.DeclarationLink[]|nil result The result of the request +function LSPRequestClient.textDocument_declaration(args, bufnr, opts) end + +--- A request to provide selection ranges in a document. The request's +--- parameter is of type {@link SelectionRangeParams}, the +--- response is of type {@link SelectionRange SelectionRange[]} or a Thenable +--- that resolves to such. +---@async +---@param args nio.lsp.types.SelectionRangeParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.SelectionRange[]|nil result The result of the request +function LSPRequestClient.textDocument_selectionRange(args, bufnr, opts) end + +--- A request to result a `CallHierarchyItem` in a document at a given position. +--- Can be used as an input to an incoming or outgoing call hierarchy. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.CallHierarchyPrepareParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.CallHierarchyItem[]|nil result The result of the request +function LSPRequestClient.textDocument_prepareCallHierarchy(args, bufnr, opts) end + +--- A request to resolve the incoming calls for a given `CallHierarchyItem`. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.CallHierarchyIncomingCallsParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.CallHierarchyIncomingCall[]|nil result The result of the request +function LSPRequestClient.callHierarchy_incomingCalls(args, bufnr, opts) end + +--- A request to resolve the outgoing calls for a given `CallHierarchyItem`. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.CallHierarchyOutgoingCallsParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.CallHierarchyOutgoingCall[]|nil result The result of the request +function LSPRequestClient.callHierarchy_outgoingCalls(args, bufnr, opts) end + +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.SemanticTokensParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.SemanticTokens|nil result The result of the request +function LSPRequestClient.textDocument_semanticTokens_full(args, bufnr, opts) end + +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.SemanticTokensDeltaParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.SemanticTokens|nio.lsp.types.SemanticTokensDelta|nil result The result of the request +function LSPRequestClient.textDocument_semanticTokens_full_delta(args, bufnr, opts) end + +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.SemanticTokensRangeParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.SemanticTokens|nil result The result of the request +function LSPRequestClient.textDocument_semanticTokens_range(args, bufnr, opts) end + +--- A request to provide ranges that can be edited together. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.LinkedEditingRangeParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.LinkedEditingRanges|nil result The result of the request +function LSPRequestClient.textDocument_linkedEditingRange(args, bufnr, opts) end + +--- The will create files request is sent from the client to the server before files are actually +--- created as long as the creation is triggered from within the client. +--- +--- The request can return a `WorkspaceEdit` which will be applied to workspace before the +--- files are created. Hence the `WorkspaceEdit` can not manipulate the content of the file +--- to be created. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.CreateFilesParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.WorkspaceEdit|nil result The result of the request +function LSPRequestClient.workspace_willCreateFiles(args, bufnr, opts) end + +--- The will rename files request is sent from the client to the server before files are actually +--- renamed as long as the rename is triggered from within the client. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.RenameFilesParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.WorkspaceEdit|nil result The result of the request +function LSPRequestClient.workspace_willRenameFiles(args, bufnr, opts) end + +--- The did delete files notification is sent from the client to the server when +--- files were deleted from within the client. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.DeleteFilesParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.WorkspaceEdit|nil result The result of the request +function LSPRequestClient.workspace_willDeleteFiles(args, bufnr, opts) end + +--- A request to get the moniker of a symbol at a given text document position. +--- The request parameter is of type {@link TextDocumentPositionParams}. +--- The response is of type {@link Moniker Moniker[]} or `null`. +---@async +---@param args nio.lsp.types.MonikerParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.Moniker[]|nil result The result of the request +function LSPRequestClient.textDocument_moniker(args, bufnr, opts) end + +--- A request to result a `TypeHierarchyItem` in a document at a given position. +--- Can be used as an input to a subtypes or supertypes type hierarchy. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.TypeHierarchyPrepareParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.TypeHierarchyItem[]|nil result The result of the request +function LSPRequestClient.textDocument_prepareTypeHierarchy(args, bufnr, opts) end + +--- A request to resolve the supertypes for a given `TypeHierarchyItem`. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.TypeHierarchySupertypesParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.TypeHierarchyItem[]|nil result The result of the request +function LSPRequestClient.typeHierarchy_supertypes(args, bufnr, opts) end + +--- A request to resolve the subtypes for a given `TypeHierarchyItem`. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.TypeHierarchySubtypesParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.TypeHierarchyItem[]|nil result The result of the request +function LSPRequestClient.typeHierarchy_subtypes(args, bufnr, opts) end + +--- A request to provide inline values in a document. The request's parameter is of +--- type {@link InlineValueParams}, the response is of type +--- {@link InlineValue InlineValue[]} or a Thenable that resolves to such. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.InlineValueParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.InlineValue[]|nil result The result of the request +function LSPRequestClient.textDocument_inlineValue(args, bufnr, opts) end + +--- A request to provide inlay hints in a document. The request's parameter is of +--- type {@link InlayHintsParams}, the response is of type +--- {@link InlayHint InlayHint[]} or a Thenable that resolves to such. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.InlayHintParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.InlayHint[]|nil result The result of the request +function LSPRequestClient.textDocument_inlayHint(args, bufnr, opts) end + +--- A request to resolve additional properties for an inlay hint. +--- The request's parameter is of type {@link InlayHint}, the response is +--- of type {@link InlayHint} or a Thenable that resolves to such. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.InlayHint Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.InlayHint|nil result The result of the request +function LSPRequestClient.inlayHint_resolve(args, bufnr, opts) end + +--- The document diagnostic request definition. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.DocumentDiagnosticParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.DocumentDiagnosticReport|nil result The result of the request +function LSPRequestClient.textDocument_diagnostic(args, bufnr, opts) end + +--- The workspace diagnostic request definition. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.WorkspaceDiagnosticParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.WorkspaceDiagnosticReport|nil result The result of the request +function LSPRequestClient.workspace_diagnostic(args, bufnr, opts) end + +--- A request to provide inline completions in a document. The request's parameter is of +--- type {@link InlineCompletionParams}, the response is of type +--- {@link InlineCompletion InlineCompletion[]} or a Thenable that resolves to such. +--- +--- @since 3.18.0 +--- @proposed +---@async +---@param args nio.lsp.types.InlineCompletionParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.InlineCompletionList|nio.lsp.types.InlineCompletionItem[]|nil result The result of the request +function LSPRequestClient.textDocument_inlineCompletion(args, bufnr, opts) end + +--- The initialize request is sent from the client to the server. +--- It is sent once as the request after starting up the server. +--- The requests parameter is of type {@link InitializeParams} +--- the response if of type {@link InitializeResult} of a Thenable that +--- resolves to such. +---@async +---@param args nio.lsp.types.InitializeParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.InitializeResult|nil result The result of the request +function LSPRequestClient.initialize(args, bufnr, opts) end + +--- A shutdown request is sent from the client to the server. +--- It is sent once when the client decides to shutdown the +--- server. The only notification that is sent after a shutdown request +--- is the exit event. +---@async +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nil|nil result The result of the request +function LSPRequestClient.shutdown(bufnr, opts) end + +--- A document will save request is sent from the client to the server before +--- the document is actually saved. The request can return an array of TextEdits +--- which will be applied to the text document before it is saved. Please note that +--- clients might drop results if computing the text edits took too long or if a +--- server constantly fails on this request. This is done to keep the save fast and +--- reliable. +---@async +---@param args nio.lsp.types.WillSaveTextDocumentParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.TextEdit[]|nil result The result of the request +function LSPRequestClient.textDocument_willSaveWaitUntil(args, bufnr, opts) end + +--- Request to request completion at a given text document position. The request's +--- parameter is of type {@link TextDocumentPosition} the response +--- is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList} +--- or a Thenable that resolves to such. +--- +--- The request can delay the computation of the {@link CompletionItem.detail `detail`} +--- and {@link CompletionItem.documentation `documentation`} properties to the `completionItem/resolve` +--- request. However, properties that are needed for the initial sorting and filtering, like `sortText`, +--- `filterText`, `insertText`, and `textEdit`, must not be changed during resolve. +---@async +---@param args nio.lsp.types.CompletionParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.CompletionItem[]|nio.lsp.types.CompletionList|nil result The result of the request +function LSPRequestClient.textDocument_completion(args, bufnr, opts) end + +--- Request to resolve additional information for a given completion item.The request's +--- parameter is of type {@link CompletionItem} the response +--- is of type {@link CompletionItem} or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.CompletionItem Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.CompletionItem|nil result The result of the request +function LSPRequestClient.completionItem_resolve(args, bufnr, opts) end + +--- Request to request hover information at a given text document position. The request's +--- parameter is of type {@link TextDocumentPosition} the response is of +--- type {@link Hover} or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.HoverParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.Hover|nil result The result of the request +function LSPRequestClient.textDocument_hover(args, bufnr, opts) end + +---@async +---@param args nio.lsp.types.SignatureHelpParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.SignatureHelp|nil result The result of the request +function LSPRequestClient.textDocument_signatureHelp(args, bufnr, opts) end + +--- A request to resolve the definition location of a symbol at a given text +--- document position. The request's parameter is of type {@link TextDocumentPosition} +--- the response is of either type {@link Definition} or a typed array of +--- {@link DefinitionLink} or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.DefinitionParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.Definition|nio.lsp.types.DefinitionLink[]|nil result The result of the request +function LSPRequestClient.textDocument_definition(args, bufnr, opts) end + +--- A request to resolve project-wide references for the symbol denoted +--- by the given text document position. The request's parameter is of +--- type {@link ReferenceParams} the response is of type +--- {@link Location Location[]} or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.ReferenceParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.Location[]|nil result The result of the request +function LSPRequestClient.textDocument_references(args, bufnr, opts) end + +--- Request to resolve a {@link DocumentHighlight} for a given +--- text document position. The request's parameter is of type {@link TextDocumentPosition} +--- the request response is an array of type {@link DocumentHighlight} +--- or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.DocumentHighlightParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.DocumentHighlight[]|nil result The result of the request +function LSPRequestClient.textDocument_documentHighlight(args, bufnr, opts) end + +--- A request to list all symbols found in a given text document. The request's +--- parameter is of type {@link TextDocumentIdentifier} the +--- response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable +--- that resolves to such. +---@async +---@param args nio.lsp.types.DocumentSymbolParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.SymbolInformation[]|nio.lsp.types.DocumentSymbol[]|nil result The result of the request +function LSPRequestClient.textDocument_documentSymbol(args, bufnr, opts) end + +--- A request to provide commands for the given text document and range. +---@async +---@param args nio.lsp.types.CodeActionParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.Command|nio.lsp.types.CodeAction[]|nil result The result of the request +function LSPRequestClient.textDocument_codeAction(args, bufnr, opts) end + +--- Request to resolve additional information for a given code action.The request's +--- parameter is of type {@link CodeAction} the response +--- is of type {@link CodeAction} or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.CodeAction Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.CodeAction|nil result The result of the request +function LSPRequestClient.codeAction_resolve(args, bufnr, opts) end + +--- A request to list project-wide symbols matching the query string given +--- by the {@link WorkspaceSymbolParams}. The response is +--- of type {@link SymbolInformation SymbolInformation[]} or a Thenable that +--- resolves to such. +--- +--- @since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients +--- need to advertise support for WorkspaceSymbols via the client capability +--- `workspace.symbol.resolveSupport`. +--- +---@async +---@param args nio.lsp.types.WorkspaceSymbolParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.SymbolInformation[]|nio.lsp.types.WorkspaceSymbol[]|nil result The result of the request +function LSPRequestClient.workspace_symbol(args, bufnr, opts) end + +--- A request to resolve the range inside the workspace +--- symbol's location. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.WorkspaceSymbol Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.WorkspaceSymbol|nil result The result of the request +function LSPRequestClient.workspaceSymbol_resolve(args, bufnr, opts) end + +--- A request to provide code lens for the given text document. +---@async +---@param args nio.lsp.types.CodeLensParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.CodeLens[]|nil result The result of the request +function LSPRequestClient.textDocument_codeLens(args, bufnr, opts) end + +--- A request to resolve a command for a given code lens. +---@async +---@param args nio.lsp.types.CodeLens Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.CodeLens|nil result The result of the request +function LSPRequestClient.codeLens_resolve(args, bufnr, opts) end + +--- A request to provide document links +---@async +---@param args nio.lsp.types.DocumentLinkParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.DocumentLink[]|nil result The result of the request +function LSPRequestClient.textDocument_documentLink(args, bufnr, opts) end + +--- Request to resolve additional information for a given document link. The request's +--- parameter is of type {@link DocumentLink} the response +--- is of type {@link DocumentLink} or a Thenable that resolves to such. +---@async +---@param args nio.lsp.types.DocumentLink Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.DocumentLink|nil result The result of the request +function LSPRequestClient.documentLink_resolve(args, bufnr, opts) end + +--- A request to format a whole document. +---@async +---@param args nio.lsp.types.DocumentFormattingParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.TextEdit[]|nil result The result of the request +function LSPRequestClient.textDocument_formatting(args, bufnr, opts) end + +--- A request to format a range in a document. +---@async +---@param args nio.lsp.types.DocumentRangeFormattingParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.TextEdit[]|nil result The result of the request +function LSPRequestClient.textDocument_rangeFormatting(args, bufnr, opts) end + +--- A request to format ranges in a document. +--- +--- @since 3.18.0 +--- @proposed +---@async +---@param args nio.lsp.types.DocumentRangesFormattingParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.TextEdit[]|nil result The result of the request +function LSPRequestClient.textDocument_rangesFormatting(args, bufnr, opts) end + +--- A request to format a document on type. +---@async +---@param args nio.lsp.types.DocumentOnTypeFormattingParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.TextEdit[]|nil result The result of the request +function LSPRequestClient.textDocument_onTypeFormatting(args, bufnr, opts) end + +--- A request to rename a symbol. +---@async +---@param args nio.lsp.types.RenameParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.WorkspaceEdit|nil result The result of the request +function LSPRequestClient.textDocument_rename(args, bufnr, opts) end + +--- A request to test and perform the setup necessary for a rename. +--- +--- @since 3.16 - support for default behavior +---@async +---@param args nio.lsp.types.PrepareRenameParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.PrepareRenameResult|nil result The result of the request +function LSPRequestClient.textDocument_prepareRename(args, bufnr, opts) end + +--- A request send from the client to the server to execute a command. The request might return +--- a workspace edit which the client will apply to the workspace. +---@async +---@param args nio.lsp.types.ExecuteCommandParams Arguments to the request +---@param bufnr integer? Buffer number (0 for current buffer) +---@param opts? nio.lsp.RequestOpts Options for the request handling +---@return nio.lsp.types.ResponseError|nil error The error object in case a request fails. +---@return nio.lsp.types.LSPAny|nil result The result of the request +function LSPRequestClient.workspace_executeCommand(args, bufnr, opts) end + +---@class nio.lsp.NotifyClient +local LSPNotifyClient = {} + +--- The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace +--- folder configuration changes. +---@async +---@param args nio.lsp.types.DidChangeWorkspaceFoldersParams +function LSPNotifyClient.workspace_didChangeWorkspaceFolders(args) end + +--- The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress +--- initiated on the server side. +---@async +---@param args nio.lsp.types.WorkDoneProgressCancelParams +function LSPNotifyClient.window_workDoneProgress_cancel(args) end + +--- The did create files notification is sent from the client to the server when +--- files were created from within the client. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.CreateFilesParams +function LSPNotifyClient.workspace_didCreateFiles(args) end + +--- The did rename files notification is sent from the client to the server when +--- files were renamed from within the client. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.RenameFilesParams +function LSPNotifyClient.workspace_didRenameFiles(args) end + +--- The will delete files request is sent from the client to the server before files are actually +--- deleted as long as the deletion is triggered from within the client. +--- +--- @since 3.16.0 +---@async +---@param args nio.lsp.types.DeleteFilesParams +function LSPNotifyClient.workspace_didDeleteFiles(args) end + +--- A notification sent when a notebook opens. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.DidOpenNotebookDocumentParams +function LSPNotifyClient.notebookDocument_didOpen(args) end + +---@async +---@param args nio.lsp.types.DidChangeNotebookDocumentParams +function LSPNotifyClient.notebookDocument_didChange(args) end + +--- A notification sent when a notebook document is saved. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.DidSaveNotebookDocumentParams +function LSPNotifyClient.notebookDocument_didSave(args) end + +--- A notification sent when a notebook closes. +--- +--- @since 3.17.0 +---@async +---@param args nio.lsp.types.DidCloseNotebookDocumentParams +function LSPNotifyClient.notebookDocument_didClose(args) end + +--- The initialized notification is sent from the client to the +--- server after the client is fully initialized and the server +--- is allowed to send requests from the server to the client. +---@async +---@param args nio.lsp.types.InitializedParams +function LSPNotifyClient.initialized(args) end + +--- The exit event is sent from the client to the server to +--- ask the server to exit its process. +---@async +--- The configuration change notification is sent from the client to the server +--- when the client's configuration has changed. The notification contains +--- the changed configuration as defined by the language client. +---@async +---@param args nio.lsp.types.DidChangeConfigurationParams +function LSPNotifyClient.workspace_didChangeConfiguration(args) end + +--- The document open notification is sent from the client to the server to signal +--- newly opened text documents. The document's truth is now managed by the client +--- and the server must not try to read the document's truth using the document's +--- uri. Open in this sense means it is managed by the client. It doesn't necessarily +--- mean that its content is presented in an editor. An open notification must not +--- be sent more than once without a corresponding close notification send before. +--- This means open and close notification must be balanced and the max open count +--- is one. +---@async +---@param args nio.lsp.types.DidOpenTextDocumentParams +function LSPNotifyClient.textDocument_didOpen(args) end + +--- The document change notification is sent from the client to the server to signal +--- changes to a text document. +---@async +---@param args nio.lsp.types.DidChangeTextDocumentParams +function LSPNotifyClient.textDocument_didChange(args) end + +--- The document close notification is sent from the client to the server when +--- the document got closed in the client. The document's truth now exists where +--- the document's uri points to (e.g. if the document's uri is a file uri the +--- truth now exists on disk). As with the open notification the close notification +--- is about managing the document's content. Receiving a close notification +--- doesn't mean that the document was open in an editor before. A close +--- notification requires a previous open notification to be sent. +---@async +---@param args nio.lsp.types.DidCloseTextDocumentParams +function LSPNotifyClient.textDocument_didClose(args) end + +--- The document save notification is sent from the client to the server when +--- the document got saved in the client. +---@async +---@param args nio.lsp.types.DidSaveTextDocumentParams +function LSPNotifyClient.textDocument_didSave(args) end + +--- A document will save notification is sent from the client to the server before +--- the document is actually saved. +---@async +---@param args nio.lsp.types.WillSaveTextDocumentParams +function LSPNotifyClient.textDocument_willSave(args) end + +--- The watched files notification is sent from the client to the server when +--- the client detects changes to file watched by the language client. +---@async +---@param args nio.lsp.types.DidChangeWatchedFilesParams +function LSPNotifyClient.workspace_didChangeWatchedFiles(args) end + +---@async +---@param args nio.lsp.types.SetTraceParams +function LSPNotifyClient.__setTrace(args) end + +---@async +---@param args nio.lsp.types.CancelParams +function LSPNotifyClient.__cancelRequest(args) end + +---@async +---@param args nio.lsp.types.ProgressParams +function LSPNotifyClient.__progress(args) end + +---@alias nio.lsp.types.URI string +---@alias nio.lsp.types.DocumentUri string + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensDeltaParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. +---@field previousResultId string The result id of a previous response. The result Id can either point to a full response or a delta response depending on what was received last. + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensDeltaPartialResult +---@field edits nio.lsp.types.SemanticTokensEdit[] + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensRangeParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. +---@field range nio.lsp.types.Range The range the semantic tokens are requested for. + +--- The result of a showDocument request. +--- +--- @since 3.16.0 +---@class nio.lsp.types.ShowDocumentResult +---@field success boolean A boolean indicating if the show was successful. + +--- Params to show a resource in the UI. +--- +--- @since 3.16.0 +---@class nio.lsp.types.ShowDocumentParams +---@field uri nio.lsp.types.URI The uri to show. +---@field external? boolean Indicates to show the resource in an external program. To show, for example, `https://code.visualstudio.com/` in the default WEB browser set `external` to `true`. +---@field takeFocus? boolean An optional property to indicate whether the editor showing the document should take focus or not. Clients might ignore this property if an external program is started. +---@field selection? nio.lsp.types.Range An optional selection range if the document is a text document. Clients might ignore the property if an external program is started or the file is not a text file. + +--- Provide an inline value through an expression evaluation. +--- If only a range is specified, the expression will be extracted from the underlying document. +--- An optional expression can be used to override the extracted expression. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueEvaluatableExpression +---@field range nio.lsp.types.Range The document range for which the inline value applies. The range is used to extract the evaluatable expression from the underlying document. +---@field expression? string If specified the expression overrides the extracted expression. + +--- The result of a linked editing range request. +--- +--- @since 3.16.0 +---@class nio.lsp.types.LinkedEditingRanges +---@field ranges nio.lsp.types.Range[] A list of ranges that can be edited together. The ranges must have identical length and contain identical text content. The ranges cannot overlap. +---@field wordPattern? string An optional word pattern (regular expression) that describes valid contents for the given ranges. If no pattern is provided, the client configuration's word pattern will be used. + +---@class nio.lsp.types.LinkedEditingRangeParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams + +---@class nio.lsp.types.LinkedEditingRangeRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.LinkedEditingRangeOptions,nio.lsp.types.StaticRegistrationOptions + +--- A workspace edit represents changes to many resources managed in the workspace. The edit +--- should either provide `changes` or `documentChanges`. If documentChanges are present +--- they are preferred over `changes` if the client can handle versioned document edits. +--- +--- Since version 3.13.0 a workspace edit can contain resource operations as well. If resource +--- operations are present clients need to execute the operations in the order in which they +--- are provided. So a workspace edit for example can consist of the following two changes: +--- (1) a create file a.txt and (2) a text document edit which insert text into file a.txt. +--- +--- An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will +--- cause failure of the operation. How the client recovers from the failure is described by +--- the client capability: `workspace.workspaceEdit.failureHandling` +---@class nio.lsp.types.WorkspaceEdit +---@field changes? table Holds changes to existing resources. +---@field documentChanges? nio.lsp.types.TextDocumentEdit|nio.lsp.types.CreateFile|nio.lsp.types.RenameFile|nio.lsp.types.DeleteFile[] Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes are either an array of `TextDocumentEdit`s to express changes to n different text documents where each text document edit addresses a specific version of a text document. Or it can contain above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations. Whether a client supports versioned document edits is expressed via `workspace.workspaceEdit.documentChanges` client capability. If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then only plain `TextEdit`s using the `changes` property are supported. +---@field changeAnnotations? table A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and delete file / folder operations. Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`. @since 3.16.0 + +--- The parameters sent in notifications/requests for user-initiated creation of +--- files. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CreateFilesParams +---@field files nio.lsp.types.FileCreate[] An array of all files/folders created in this operation. + +--- The options to register for file operations. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileOperationRegistrationOptions +---@field filters nio.lsp.types.FileOperationFilter[] The actual filters. + +--- The parameters sent in notifications/requests for user-initiated renames of +--- files. +--- +--- @since 3.16.0 +---@class nio.lsp.types.RenameFilesParams +---@field files nio.lsp.types.FileRename[] An array of all files/folders renamed in this operation. When a folder is renamed, only the folder will be included, and not its children. + +--- A document link is a range in a text document that links to an internal or external resource, like another +--- text document or a web site. +---@class nio.lsp.types.DocumentLink +---@field range nio.lsp.types.Range The range this link applies to. +---@field target? nio.lsp.types.URI The uri this link points to. If missing a resolve request is sent later. +---@field tooltip? string The tooltip text when you hover over this link. If a tooltip is provided, is will be displayed in a string that includes instructions on how to trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS, user settings, and localization. @since 3.15.0 +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved on a document link between a DocumentLinkRequest and a DocumentLinkResolveRequest. + +--- The parameters sent in notifications/requests for user-initiated deletes of +--- files. +--- +--- @since 3.16.0 +---@class nio.lsp.types.DeleteFilesParams +---@field files nio.lsp.types.FileDelete[] An array of all files/folders deleted in this operation. + +--- Registration options for a {@link DocumentLinkRequest}. +---@class nio.lsp.types.DocumentLinkRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DocumentLinkOptions + +--- Moniker definition to match LSIF 0.5 moniker definition. +--- +--- @since 3.16.0 +---@class nio.lsp.types.Moniker +---@field scheme string The scheme of the moniker. For example tsc or .Net +---@field identifier string The identifier of the moniker. The value is opaque in LSIF however schema owners are allowed to define the structure if they want. +---@field unique nio.lsp.types.UniquenessLevel The scope in which the moniker is unique +---@field kind? nio.lsp.types.MonikerKind The moniker kind if known. + +---@class nio.lsp.types.MonikerParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams + +---@class nio.lsp.types.MonikerRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.MonikerOptions + +--- Registration options for a {@link DocumentFormattingRequest}. +---@class nio.lsp.types.DocumentFormattingRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DocumentFormattingOptions + +--- @since 3.17.0 +---@class nio.lsp.types.TypeHierarchyItem +---@field name string The name of this item. +---@field kind nio.lsp.types.SymbolKind The kind of this item. +---@field tags? nio.lsp.types.SymbolTag[] Tags for this item. +---@field detail? string More detail for this item, e.g. the signature of a function. +---@field uri nio.lsp.types.DocumentUri The resource identifier of this item. +---@field range nio.lsp.types.Range The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. +---@field selectionRange nio.lsp.types.Range The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. Must be contained by the {@link TypeHierarchyItem.range `range`}. +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved between a type hierarchy prepare and supertypes or subtypes requests. It could also be used to identify the type hierarchy in the server, helping improve the performance on resolving supertypes and subtypes. + +--- The parameter of a `textDocument/prepareTypeHierarchy` request. +--- +--- @since 3.17.0 +---@class nio.lsp.types.TypeHierarchyPrepareParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams + +--- Type hierarchy options used during static or dynamic registration. +--- +--- @since 3.17.0 +---@class nio.lsp.types.TypeHierarchyRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.TypeHierarchyOptions,nio.lsp.types.StaticRegistrationOptions + +--- The parameter of a `typeHierarchy/supertypes` request. +--- +--- @since 3.17.0 +---@class nio.lsp.types.TypeHierarchySupertypesParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field item nio.lsp.types.TypeHierarchyItem +--- How a signature help was triggered. +--- +--- @since 3.15.0 +---@alias nio.lsp.types.SignatureHelpTriggerKind 1|2|3 + +--- The parameter of a `typeHierarchy/subtypes` request. +--- +--- @since 3.17.0 +---@class nio.lsp.types.TypeHierarchySubtypesParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field item nio.lsp.types.TypeHierarchyItem + +--- Registration options for a {@link DocumentOnTypeFormattingRequest}. +---@class nio.lsp.types.DocumentOnTypeFormattingRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DocumentOnTypeFormattingOptions +---@alias nio.lsp.types.InlineValue nio.lsp.types.InlineValueText|nio.lsp.types.InlineValueVariableLookup|nio.lsp.types.InlineValueEvaluatableExpression + +--- A parameter literal used in inline value requests. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueParams : nio.lsp.types.WorkDoneProgressParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. +---@field range nio.lsp.types.Range The document range for which inline values should be computed. +---@field context nio.lsp.types.InlineValueContext Additional information about the context in which inline values were requested. + +--- Inline value options used during static or dynamic registration. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueRegistrationOptions : nio.lsp.types.InlineValueOptions,nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.StaticRegistrationOptions +---@alias nio.lsp.types.PrepareRenameResult nio.lsp.types.Range|nio.lsp.types.Structure0|nio.lsp.types.Structure1 + +--- Inlay hint information. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlayHint +---@field position nio.lsp.types.Position The position of this hint. If multiple hints have the same position, they will be shown in the order they appear in the response. +---@field label string|nio.lsp.types.InlayHintLabelPart[] The label of this hint. A human readable string or an array of InlayHintLabelPart label parts. *Note* that neither the string nor the label part can be empty. +---@field kind? nio.lsp.types.InlayHintKind The kind of this hint. Can be omitted in which case the client should fall back to a reasonable default. +---@field textEdits? nio.lsp.types.TextEdit[] Optional text edits that are performed when accepting this inlay hint. *Note* that edits are expected to change the document so that the inlay hint (or its nearest variant) is now part of the document and the inlay hint itself is now obsolete. +---@field tooltip? string|nio.lsp.types.MarkupContent The tooltip text when you hover over this item. +---@field paddingLeft? boolean Render padding before the hint. Note: Padding should use the editor's background color, not the background color of the hint itself. That means padding can be used to visually align/separate an inlay hint. +---@field paddingRight? boolean Render padding after the hint. Note: Padding should use the editor's background color, not the background color of the hint itself. That means padding can be used to visually align/separate an inlay hint. +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved on an inlay hint between a `textDocument/inlayHint` and a `inlayHint/resolve` request. + +--- A parameter literal used in inlay hint requests. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlayHintParams : nio.lsp.types.WorkDoneProgressParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. +---@field range nio.lsp.types.Range The document range for which inlay hints should be computed. + +--- Inlay hint options used during static or dynamic registration. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlayHintRegistrationOptions : nio.lsp.types.InlayHintOptions,nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.StaticRegistrationOptions + +--- The parameters of a {@link ExecuteCommandRequest}. +---@class nio.lsp.types.ExecuteCommandParams : nio.lsp.types.WorkDoneProgressParams +---@field command string The identifier of the actual command handler. +---@field arguments? nio.lsp.types.LSPAny[] Arguments that the command should be invoked with. + +--- Registration options for a {@link ExecuteCommandRequest}. +---@class nio.lsp.types.ExecuteCommandRegistrationOptions : nio.lsp.types.ExecuteCommandOptions +---@alias nio.lsp.types.DocumentDiagnosticReport nio.lsp.types.RelatedFullDocumentDiagnosticReport|nio.lsp.types.RelatedUnchangedDocumentDiagnosticReport + +--- Parameters of the document diagnostic request. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DocumentDiagnosticParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. +---@field identifier? string The additional identifier provided during registration. +---@field previousResultId? string The result id of a previous response if provided. + +--- A partial result for a document diagnostic report. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DocumentDiagnosticReportPartialResult +---@field relatedDocuments table + +--- The parameters of a `workspace/didChangeWorkspaceFolders` notification. +---@class nio.lsp.types.DidChangeWorkspaceFoldersParams +---@field event nio.lsp.types.WorkspaceFoldersChangeEvent The actual workspace folder change event. + +--- Diagnostic registration options. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DiagnosticRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DiagnosticOptions,nio.lsp.types.StaticRegistrationOptions + +---@class nio.lsp.types.WorkDoneProgressCancelParams +---@field token nio.lsp.types.ProgressToken The token to be used to report progress. + +--- A workspace diagnostic report. +--- +--- @since 3.17.0 +---@class nio.lsp.types.WorkspaceDiagnosticReport +---@field items nio.lsp.types.WorkspaceDocumentDiagnosticReport[] + +--- A notebook cell. +--- +--- A cell's document URI must be unique across ALL notebook +--- cells and can therefore be used to uniquely identify a +--- notebook cell or the cell's text document. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookCell +---@field kind nio.lsp.types.NotebookCellKind The cell's kind +---@field document nio.lsp.types.DocumentUri The URI of the cell's text document content. +---@field metadata? nio.lsp.types.LSPObject Additional metadata stored with the cell. Note: should always be an object literal (e.g. LSPObject) +---@field executionSummary? nio.lsp.types.ExecutionSummary Additional execution summary information if supported by the client. + +--- A partial result for a workspace diagnostic report. +--- +--- @since 3.17.0 +---@class nio.lsp.types.WorkspaceDiagnosticReportPartialResult +---@field items nio.lsp.types.WorkspaceDocumentDiagnosticReport[] + +--- The params sent in an open notebook document notification. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DidOpenNotebookDocumentParams +---@field notebookDocument nio.lsp.types.NotebookDocument The notebook document that got opened. +---@field cellTextDocuments nio.lsp.types.TextDocumentItem[] The text documents that represent the content of a notebook cell. + +--- Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.InlineCompletionList +---@field items nio.lsp.types.InlineCompletionItem[] The inline completion items + +--- An inline completion item represents a text snippet that is proposed inline to complete text that is being typed. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.InlineCompletionItem +---@field insertText string|nio.lsp.types.StringValue The text to replace the range with. Must be set. +---@field filterText? string A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used. +---@field range? nio.lsp.types.Range The range to replace. Must begin and end on the same line. +---@field command? nio.lsp.types.Command An optional {@link Command} that is executed *after* inserting this completion. + +--- A parameter literal used in inline completion requests. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.InlineCompletionParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams +---@field context nio.lsp.types.InlineCompletionContext Additional information about the context in which inline completions were requested. + +--- The params sent in a save notebook document notification. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DidSaveNotebookDocumentParams +---@field notebookDocument nio.lsp.types.NotebookDocumentIdentifier The notebook document that got saved. + +--- The params sent in a close notebook document notification. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DidCloseNotebookDocumentParams +---@field notebookDocument nio.lsp.types.NotebookDocumentIdentifier The notebook document that got closed. +---@field cellTextDocuments nio.lsp.types.TextDocumentIdentifier[] The text documents that represent the content of a notebook cell that got closed. + +---@class nio.lsp.types.UnregistrationParams +---@field unregisterations nio.lsp.types.Unregistration[] + +--- The result returned from an initialize request. +---@class nio.lsp.types.InitializeResult +---@field capabilities nio.lsp.types.ServerCapabilities The capabilities the language server provides. +---@field serverInfo? nio.lsp.types.Structure2 Information about the server. @since 3.15.0 + +---@class nio.lsp.types.InitializeParams : nio.lsp.types._InitializeParams,nio.lsp.types.WorkspaceFoldersInitializeParams + +---@class nio.lsp.types.DidChangeConfigurationRegistrationOptions +---@field section? string|string[] + +--- The parameters of a notification message. +---@class nio.lsp.types.ShowMessageParams +---@field type nio.lsp.types.MessageType The message type. See {@link MessageType} +---@field message string The actual message. + +---@class nio.lsp.types.ShowMessageRequestParams +---@field type nio.lsp.types.MessageType The message type. See {@link MessageType} +---@field message string The actual message. +---@field actions? nio.lsp.types.MessageActionItem[] The message action items to present. + +--- The log message parameters. +---@class nio.lsp.types.LogMessageParams +---@field type nio.lsp.types.MessageType The message type. See {@link MessageType} +---@field message string The actual message. + +--- A text edit applicable to a text document. +---@class nio.lsp.types.TextEdit +---@field range nio.lsp.types.Range The range of the text document to be manipulated. To insert text into a document create a range where start === end. +---@field newText string The string to be inserted. For delete operations use an empty string. + +--- The parameters sent in a will save text document notification. +---@class nio.lsp.types.WillSaveTextDocumentParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document that will be saved. +---@field reason nio.lsp.types.TextDocumentSaveReason The 'TextDocumentSaveReason'. + +--- The parameters sent in an open text document notification +---@class nio.lsp.types.DidOpenTextDocumentParams +---@field textDocument nio.lsp.types.TextDocumentItem The document that was opened. + +--- A completion item represents a text snippet that is +--- proposed to complete text that is being typed. +---@class nio.lsp.types.CompletionItem +---@field label string The label of this completion item. The label property is also by default the text that is inserted when selecting this completion. If label details are provided the label itself should be an unqualified name of the completion item. +---@field labelDetails? nio.lsp.types.CompletionItemLabelDetails Additional details for the label @since 3.17.0 +---@field kind? nio.lsp.types.CompletionItemKind The kind of this completion item. Based of the kind an icon is chosen by the editor. +---@field tags? nio.lsp.types.CompletionItemTag[] Tags for this completion item. @since 3.15.0 +---@field detail? string A human-readable string with additional information about this item, like type or symbol information. +---@field documentation? string|nio.lsp.types.MarkupContent A human-readable string that represents a doc-comment. +---@field deprecated? boolean Indicates if this item is deprecated. @deprecated Use `tags` instead. +---@field preselect? boolean Select this item when showing. *Note* that only one completion item can be selected and that the tool / client decides which item that is. The rule is that the *first* item of those that match best is selected. +---@field sortText? string A string that should be used when comparing this item with other items. When `falsy` the {@link CompletionItem.label label} is used. +---@field filterText? string A string that should be used when filtering a set of completion items. When `falsy` the {@link CompletionItem.label label} is used. +---@field insertText? string A string that should be inserted into a document when selecting this completion. When `falsy` the {@link CompletionItem.label label} is used. The `insertText` is subject to interpretation by the client side. Some tools might not take the string literally. For example VS Code when code complete is requested in this example `con` and a completion item with an `insertText` of `console` is provided it will only insert `sole`. Therefore it is recommended to use `textEdit` instead since it avoids additional client side interpretation. +---@field insertTextFormat? nio.lsp.types.InsertTextFormat The format of the insert text. The format applies to both the `insertText` property and the `newText` property of a provided `textEdit`. If omitted defaults to `InsertTextFormat.PlainText`. Please note that the insertTextFormat doesn't apply to `additionalTextEdits`. +---@field insertTextMode? nio.lsp.types.InsertTextMode How whitespace and indentation is handled during completion item insertion. If not provided the clients default value depends on the `textDocument.completion.insertTextMode` client capability. @since 3.16.0 +---@field textEdit? nio.lsp.types.TextEdit|nio.lsp.types.InsertReplaceEdit An {@link TextEdit edit} which is applied to a document when selecting this completion. When an edit is provided the value of {@link CompletionItem.insertText insertText} is ignored. Most editors support two different operations when accepting a completion item. One is to insert a completion text and the other is to replace an existing text with a completion text. Since this can usually not be predetermined by a server it can report both ranges. Clients need to signal support for `InsertReplaceEdits` via the `textDocument.completion.insertReplaceSupport` client capability property. *Note 1:* The text edit's range as well as both ranges from an insert replace edit must be a [single line] and they must contain the position at which completion has been requested. *Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range must be a prefix of the edit's replace range, that means it must be contained and starting at the same position. @since 3.16.0 additional type `InsertReplaceEdit` +---@field textEditText? string The edit text used if the completion item is part of a CompletionList and CompletionList defines an item default for the text edit range. Clients will only honor this property if they opt into completion list item defaults using the capability `completionList.itemDefaults`. If not provided and a list's default range is provided the label property is used as a text. @since 3.17.0 +---@field additionalTextEdits? nio.lsp.types.TextEdit[] An optional array of additional {@link TextEdit text edits} that are applied when selecting this completion. Edits must not overlap (including the same insert position) with the main {@link CompletionItem.textEdit edit} nor with themselves. Additional text edits should be used to change text unrelated to the current cursor position (for example adding an import statement at the top of the file if the completion item will insert an unqualified type). +---@field commitCharacters? string[] An optional set of characters that when pressed while this completion is active will accept it first and then type that character. *Note* that all commit characters should have `length=1` and that superfluous characters will be ignored. +---@field command? nio.lsp.types.Command An optional {@link Command command} that is executed *after* inserting this completion. *Note* that additional modifications to the current document should be described with the {@link CompletionItem.additionalTextEdits additionalTextEdits}-property. +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved on a completion item between a {@link CompletionRequest} and a {@link CompletionResolveRequest}. + +--- The change text document notification's parameters. +---@class nio.lsp.types.DidChangeTextDocumentParams +---@field textDocument nio.lsp.types.VersionedTextDocumentIdentifier The document that did change. The version number points to the version after all provided content changes have been applied. +---@field contentChanges nio.lsp.types.TextDocumentContentChangeEvent[] The actual content changes. The content changes describe single state changes to the document. So if there are two content changes c1 (at array index 0) and c2 (at array index 1) for a document in state S then c1 moves the document from S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed on the state S'. To mirror the content of a document using change events use the following approach: - start with the same initial content - apply the 'textDocument/didChange' notifications in the order you receive them. - apply the `TextDocumentContentChangeEvent`s in a single notification in the order you receive them. + +--- Describe options to be used when registered for text document change events. +---@class nio.lsp.types.TextDocumentChangeRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions +---@field syncKind nio.lsp.types.TextDocumentSyncKind How documents are synced to the server. + +--- Registration options for a {@link CompletionRequest}. +---@class nio.lsp.types.CompletionRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.CompletionOptions + +--- The parameters sent in a close text document notification +---@class nio.lsp.types.DidCloseTextDocumentParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document that was closed. +--- The kind of a completion entry. +---@alias nio.lsp.types.CompletionItemKind 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25 + +--- The result of a hover request. +---@class nio.lsp.types.Hover +---@field contents nio.lsp.types.MarkupContent|nio.lsp.types.MarkedString|nio.lsp.types.MarkedString[] The hover's content +---@field range? nio.lsp.types.Range An optional range inside the text document that is used to visualize the hover, e.g. by changing the background color. + +--- Parameters for a {@link HoverRequest}. +---@class nio.lsp.types.HoverParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams + +--- Registration options for a {@link HoverRequest}. +---@class nio.lsp.types.HoverRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.HoverOptions + +--- The watched files change notification's parameters. +---@class nio.lsp.types.DidChangeWatchedFilesParams +---@field changes nio.lsp.types.FileEvent[] The actual file events. + +--- Describe options to be used when registered for text document change events. +---@class nio.lsp.types.DidChangeWatchedFilesRegistrationOptions +---@field watchers nio.lsp.types.FileSystemWatcher[] The watchers to register. + +--- The publish diagnostic notification's parameters. +---@class nio.lsp.types.PublishDiagnosticsParams +---@field uri nio.lsp.types.DocumentUri The URI for which diagnostic information is reported. +---@field version? integer Optional the version number of the document the diagnostics are published for. @since 3.15.0 +---@field diagnostics nio.lsp.types.Diagnostic[] An array of diagnostic information items. + +---@class nio.lsp.types.SetTraceParams +---@field value nio.lsp.types.TraceValues + +---@class nio.lsp.types.LogTraceParams +---@field message string +---@field verbose? string + +---@class nio.lsp.types.CancelParams +---@field id integer|string The request id to cancel. + +---@class nio.lsp.types.ProgressParams +---@field token nio.lsp.types.ProgressToken The progress token provided by the client or server. +---@field value nio.lsp.types.LSPAny The progress data. + +--- A parameter literal used in requests to pass a text document and a position inside that +--- document. +---@class nio.lsp.types.TextDocumentPositionParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. +---@field position nio.lsp.types.Position The position inside the text document. + +---@class nio.lsp.types.WorkDoneProgressParams +---@field workDoneToken? nio.lsp.types.ProgressToken An optional token that a server can use to report work done progress. + +---@class nio.lsp.types.PartialResultParams +---@field partialResultToken? nio.lsp.types.ProgressToken An optional token that a server can use to report partial results (e.g. streaming) to the client. + +---@class nio.lsp.types.ImplementationOptions : nio.lsp.types.WorkDoneProgressOptions + +--- Static registration options to be returned in the initialize +--- request. +---@class nio.lsp.types.StaticRegistrationOptions +---@field id? string The id used to register the request. The id can be used to deregister the request again. See also Registration#id. + +---@class nio.lsp.types.TypeDefinitionOptions : nio.lsp.types.WorkDoneProgressOptions + +---@class nio.lsp.types.Structure5 +---@field delta? boolean The server supports deltas for full documents. + +--- The workspace folder change event. +---@class nio.lsp.types.WorkspaceFoldersChangeEvent +---@field added nio.lsp.types.WorkspaceFolder[] The array of added workspace folders +---@field removed nio.lsp.types.WorkspaceFolder[] The array of the removed workspace folders + +---@class nio.lsp.types.ConfigurationItem +---@field scopeUri? nio.lsp.types.URI The scope to get the configuration section for. +---@field section? string The configuration section asked for. +--- A set of predefined position encoding kinds. +--- +--- @since 3.17.0 +---@alias nio.lsp.types.PositionEncodingKind "utf-8"|"utf-16"|"utf-32" + +--- A literal to identify a text document in the client. +---@class nio.lsp.types.TextDocumentIdentifier +---@field uri nio.lsp.types.DocumentUri The text document's uri. + +--- Position in a text document expressed as zero-based line and character +--- offset. Prior to 3.17 the offsets were always based on a UTF-16 string +--- representation. So a string of the form `a𐐀b` the character offset of the +--- character `a` is 0, the character offset of `𐐀` is 1 and the character +--- offset of b is 3 since `𐐀` is represented using two code units in UTF-16. +--- Since 3.17 clients and servers can agree on a different string encoding +--- representation (e.g. UTF-8). The client announces it's supported encoding +--- via the client capability [`general.positionEncodings`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#clientCapabilities). +--- The value is an array of position encodings the client supports, with +--- decreasing preference (e.g. the encoding at index `0` is the most preferred +--- one). To stay backwards compatible the only mandatory encoding is UTF-16 +--- represented via the string `utf-16`. The server can pick one of the +--- encodings offered by the client and signals that encoding back to the +--- client via the initialize result's property +--- [`capabilities.positionEncoding`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#serverCapabilities). If the string value +--- `utf-16` is missing from the client's capability `general.positionEncodings` +--- servers can safely assume that the client supports UTF-16. If the server +--- omits the position encoding in its initialize result the encoding defaults +--- to the string value `utf-16`. Implementation considerations: since the +--- conversion from one encoding into another requires the content of the +--- file / line the conversion is best done where the file is read which is +--- usually on the server side. +--- +--- Positions are line end character agnostic. So you can not specify a position +--- that denotes `\r|\n` or `\n|` where `|` represents the character offset. +--- +--- @since 3.17.0 - support for negotiated position encoding. +---@class nio.lsp.types.Position +---@field line integer Line position in a document (zero-based). If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document. If a line number is negative, it defaults to 0. +---@field character integer Character offset on a line in a document (zero-based). The meaning of this offset is determined by the negotiated `PositionEncodingKind`. If the character value is greater than the line length it defaults back to the line length. +--- A notebook cell kind. +--- +--- @since 3.17.0 +---@alias nio.lsp.types.NotebookCellKind 1|2 + +--- Represents a diagnostic, such as a compiler error or warning. Diagnostic objects +--- are only valid in the scope of a resource. +---@class nio.lsp.types.Diagnostic +---@field range nio.lsp.types.Range The range at which the message applies +---@field severity? nio.lsp.types.DiagnosticSeverity The diagnostic's severity. Can be omitted. If omitted it is up to the client to interpret diagnostics as error, warning, info or hint. +---@field code? integer|string The diagnostic's code, which usually appear in the user interface. +---@field codeDescription? nio.lsp.types.CodeDescription An optional property to describe the error code. Requires the code field (above) to be present/not null. @since 3.16.0 +---@field source? string A human-readable string describing the source of this diagnostic, e.g. 'typescript' or 'super lint'. It usually appears in the user interface. +---@field message string The diagnostic's message. It usually appears in the user interface +---@field tags? nio.lsp.types.DiagnosticTag[] Additional metadata about the diagnostic. @since 3.15.0 +---@field relatedInformation? nio.lsp.types.DiagnosticRelatedInformation[] An array of related diagnostic information, e.g. when symbol-names within a scope collide all definitions can be marked via this property. +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved between a `textDocument/publishDiagnostics` notification and `textDocument/codeAction` request. @since 3.16.0 + +---@class nio.lsp.types.DocumentColorOptions : nio.lsp.types.WorkDoneProgressOptions +--- How whitespace and indentation is handled during completion +--- item insertion. +--- +--- @since 3.16.0 +---@alias nio.lsp.types.InsertTextMode 1|2 + +--- A range in a text document expressed as (zero-based) start and end positions. +--- +--- If you want to specify a range that contains a line including the line ending +--- character(s) then use an end position denoting the start of the next line. +--- For example: +--- ```ts +--- { +--- start: { line: 5, character: 23 } +--- end : { line 6, character : 0 } +--- } +--- ``` +---@class nio.lsp.types.Range +---@field start nio.lsp.types.Position The range's start position. +---@field end nio.lsp.types.Position The range's end position. +--- A pattern kind describing if a glob pattern matches a file a folder or +--- both. +--- +--- @since 3.16.0 +---@alias nio.lsp.types.FileOperationPatternKind "file"|"folder" + +--- Matching options for the file operation pattern. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileOperationPatternOptions +---@field ignoreCase? boolean The pattern should be matched ignoring casing. +---@alias nio.lsp.types.Definition nio.lsp.types.Location|nio.lsp.types.Location[] +---@alias nio.lsp.types.DefinitionLink nio.lsp.types.LocationLink + +--- A full document diagnostic report for a workspace diagnostic result. +--- +--- @since 3.17.0 +---@class nio.lsp.types.WorkspaceFullDocumentDiagnosticReport : nio.lsp.types.FullDocumentDiagnosticReport +---@field uri nio.lsp.types.DocumentUri The URI for which diagnostic information is reported. +---@field version integer|nil The version number for which the diagnostics are reported. If the document is not marked as open `null` can be provided. +--- Describes the content type that a client supports in various +--- result literals like `Hover`, `ParameterInfo` or `CompletionItem`. +--- +--- Please note that `MarkupKinds` must not start with a `$`. This kinds +--- are reserved for internal usage. +---@alias nio.lsp.types.MarkupKind "plaintext"|"markdown" + +--- An unchanged document diagnostic report for a workspace diagnostic result. +--- +--- @since 3.17.0 +---@class nio.lsp.types.WorkspaceUnchangedDocumentDiagnosticReport : nio.lsp.types.UnchangedDocumentDiagnosticReport +---@field uri nio.lsp.types.DocumentUri The URI for which diagnostic information is reported. +---@field version integer|nil The version number for which the diagnostics are reported. If the document is not marked as open `null` can be provided. + +---@class nio.lsp.types.TypeDefinitionParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams + +---@class nio.lsp.types.TypeDefinitionRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.TypeDefinitionOptions,nio.lsp.types.StaticRegistrationOptions + +--- Capabilities specific to the notebook document support. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookDocumentClientCapabilities +---@field synchronization nio.lsp.types.NotebookDocumentSyncClientCapabilities Capabilities specific to notebook document synchronization @since 3.17.0 + +--- A workspace folder inside a client. +---@class nio.lsp.types.WorkspaceFolder +---@field uri nio.lsp.types.URI The associated URI for this workspace folder. +---@field name string The name of the workspace folder. Used to refer to this workspace folder in the user interface. + +---@class nio.lsp.types.WindowClientCapabilities +---@field workDoneProgress? boolean It indicates whether the client supports server initiated progress using the `window/workDoneProgress/create` request. The capability also controls Whether client supports handling of progress notifications. If set servers are allowed to report a `workDoneProgress` property in the request specific server capabilities. @since 3.15.0 +---@field showMessage? nio.lsp.types.ShowMessageRequestClientCapabilities Capabilities specific to the showMessage request. @since 3.16.0 +---@field showDocument? nio.lsp.types.ShowDocumentClientCapabilities Capabilities specific to the showDocument request. @since 3.16.0 + +--- General client capabilities. +--- +--- @since 3.16.0 +---@class nio.lsp.types.GeneralClientCapabilities +---@field staleRequestSupport? nio.lsp.types.Structure3 Client capability that signals how the client handles stale requests (e.g. a request for which the client will not process the response anymore since the information is outdated). @since 3.17.0 +---@field regularExpressions? nio.lsp.types.RegularExpressionsClientCapabilities Client capabilities specific to regular expressions. @since 3.16.0 +---@field markdown? nio.lsp.types.MarkdownClientCapabilities Client capabilities specific to the client's markdown parser. @since 3.16.0 +---@field positionEncodings? nio.lsp.types.PositionEncodingKind[] The position encodings supported by the client. Client and server have to agree on the same position encoding to ensure that offsets (e.g. character position in a line) are interpreted the same on both sides. To keep the protocol backwards compatible the following applies: if the value 'utf-16' is missing from the array of position encodings servers can assume that the client supports UTF-16. UTF-16 is therefore a mandatory encoding. If omitted it defaults to ['utf-16']. Implementation considerations: since the conversion from one encoding into another requires the content of the file / line the conversion is best done where the file is read which is usually on the server side. @since 3.17.0 + +--- The parameters of a configuration request. +---@class nio.lsp.types.ConfigurationParams +---@field items nio.lsp.types.ConfigurationItem[] + +---@class nio.lsp.types.FoldingRangeOptions : nio.lsp.types.WorkDoneProgressOptions + +--- Parameters for a {@link DocumentColorRequest}. +---@class nio.lsp.types.DocumentColorParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. + +---@class nio.lsp.types.DocumentColorRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DocumentColorOptions,nio.lsp.types.StaticRegistrationOptions + +---@class nio.lsp.types.ColorPresentation +---@field label string The label of this color presentation. It will be shown on the color picker header. By default this is also the text that is inserted when selecting this color presentation. +---@field textEdit? nio.lsp.types.TextEdit An {@link TextEdit edit} which is applied to a document when selecting this presentation for the color. When `falsy` the {@link ColorPresentation.label label} is used. +---@field additionalTextEdits? nio.lsp.types.TextEdit[] An optional array of additional {@link TextEdit text edits} that are applied when selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves. + +--- Parameters for a {@link ColorPresentationRequest}. +---@class nio.lsp.types.ColorPresentationParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. +---@field color nio.lsp.types.Color The color to request presentations for. +---@field range nio.lsp.types.Range The range where the color would be inserted. Serves as a context. + +---@class nio.lsp.types.Structure8 +---@field workspaceFolders? nio.lsp.types.WorkspaceFoldersServerCapabilities The server supports workspace folder. @since 3.6.0 +---@field fileOperations? nio.lsp.types.FileOperationOptions The server is interested in notifications/requests for operations on files. @since 3.16.0 + +---@class nio.lsp.types.SelectionRangeOptions : nio.lsp.types.WorkDoneProgressOptions +---@alias nio.lsp.types.ProgressToken integer|string +---@alias nio.lsp.types.PrepareSupportDefaultBehavior 1 + +--- Symbol tags are extra annotations that tweak the rendering of a symbol. +--- +--- @since 3.16 +---@alias nio.lsp.types.SymbolTag 1 + +--- Call hierarchy options used during static registration. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyOptions : nio.lsp.types.WorkDoneProgressOptions +---@alias nio.lsp.types.ChangeAnnotationIdentifier string + +--- Additional information that describes document changes. +--- +--- @since 3.16.0 +---@class nio.lsp.types.ChangeAnnotation +---@field label string A human-readable string describing the actual change. The string is rendered prominent in the user interface. +---@field needsConfirmation? boolean A flag which indicates that user confirmation is needed before applying the change. +---@field description? string A human-readable string which is rendered less prominent in the user interface. + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensOptions : nio.lsp.types.WorkDoneProgressOptions +---@field legend nio.lsp.types.SemanticTokensLegend The legend used by the server +---@field range? boolean|nio.lsp.types.Structure4 Server supports providing semantic tokens for a specific range of a document. +---@field full? boolean|nio.lsp.types.Structure5 Server supports providing semantic tokens for a full document. + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensEdit +---@field start integer The start offset of the edit. +---@field deleteCount integer The count of elements to remove. +---@field data? integer[] The elements to insert. + +--- Represents information on a file/folder rename. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileRename +---@field oldUri string A file:// URI for the original location of the file/folder being renamed. +---@field newUri string A file:// URI for the new location of the file/folder being renamed. +---@alias nio.lsp.types.TokenFormat "relative" + +--- Represents information on a file/folder delete. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileDelete +---@field uri string A file:// URI for the location of the file/folder being deleted. +--- Moniker uniqueness level to define scope of the moniker. +--- +--- @since 3.16.0 +---@alias nio.lsp.types.UniquenessLevel "document"|"project"|"group"|"scheme"|"global" + +--- The moniker kind. +--- +--- @since 3.16.0 +---@alias nio.lsp.types.MonikerKind "import"|"export"|"local" + +---@class nio.lsp.types.LinkedEditingRangeOptions : nio.lsp.types.WorkDoneProgressOptions + +--- Represents information on a file/folder create. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileCreate +---@field uri string A file:// URI for the location of the file/folder being created. + +--- Describes textual changes on a text document. A TextDocumentEdit describes all changes +--- on a document version Si and after they are applied move the document to version Si+1. +--- So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any +--- kind of ordering. However the edits must be non overlapping. +---@class nio.lsp.types.TextDocumentEdit +---@field textDocument nio.lsp.types.OptionalVersionedTextDocumentIdentifier The text document to change. +---@field edits nio.lsp.types.TextEdit|nio.lsp.types.AnnotatedTextEdit[] The edits to be applied. @since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a client capability. + +--- Type hierarchy options used during static registration. +--- +--- @since 3.17.0 +---@class nio.lsp.types.TypeHierarchyOptions : nio.lsp.types.WorkDoneProgressOptions + +--- Rename file operation +---@class nio.lsp.types.RenameFile : nio.lsp.types.ResourceOperation +---@field kind 'rename' A rename +---@field oldUri nio.lsp.types.DocumentUri The old (existing) location. +---@field newUri nio.lsp.types.DocumentUri The new location. +---@field options? nio.lsp.types.RenameFileOptions Rename options. + +--- Delete file operation +---@class nio.lsp.types.DeleteFile : nio.lsp.types.ResourceOperation +---@field kind 'delete' A delete +---@field uri nio.lsp.types.DocumentUri The file to delete. +---@field options? nio.lsp.types.DeleteFileOptions Delete options. + +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueContext +---@field frameId integer The stack frame (as a DAP Id) where the execution has stopped. +---@field stoppedLocation nio.lsp.types.Range The document range where execution has stopped. Typically the end position of the range denotes the line where the inline values are shown. + +--- Inline value options used during static registration. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueOptions : nio.lsp.types.WorkDoneProgressOptions + +--- An inlay hint label part allows for interactive and composite labels +--- of inlay hints. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlayHintLabelPart +---@field value string The value of this label part. +---@field tooltip? string|nio.lsp.types.MarkupContent The tooltip text when you hover over this label part. Depending on the client capability `inlayHint.resolveSupport` clients might resolve this property late using the resolve request. +---@field location? nio.lsp.types.Location An optional source code location that represents this label part. The editor will use this location for the hover and for code navigation features: This part will become a clickable link that resolves to the definition of the symbol at the given location (not necessarily the location itself), it shows the hover that shows at the given location, and it shows a context menu with further code navigation commands. Depending on the client capability `inlayHint.resolveSupport` clients might resolve this property late using the resolve request. +---@field command? nio.lsp.types.Command An optional command for this label part. Depending on the client capability `inlayHint.resolveSupport` clients might resolve this property late using the resolve request. +--- Inlay hint kinds. +--- +--- @since 3.17.0 +---@alias nio.lsp.types.InlayHintKind 1|2 + +--- A `MarkupContent` literal represents a string value which content is interpreted base on its +--- kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. +--- +--- If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. +--- See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting +--- +--- Here is an example how such a string can be constructed using JavaScript / TypeScript: +--- ```ts +--- let markdown: MarkdownContent = { +--- kind: MarkupKind.Markdown, +--- value: [ +--- '# Header', +--- 'Some text', +--- '```typescript', +--- 'someCode();', +--- '```' +--- ].join('\n') +--- }; +--- ``` +--- +--- *Please Note* that clients might sanitize the return markdown. A client could decide to +--- remove HTML from the markdown to avoid script execution. +---@class nio.lsp.types.MarkupContent +---@field kind nio.lsp.types.MarkupKind The type of the Markup +---@field value string The content itself +--- A set of predefined token modifiers. This set is not fixed +--- an clients can specify additional token types via the +--- corresponding client capabilities. +--- +--- @since 3.16.0 +---@alias nio.lsp.types.SemanticTokenModifiers "declaration"|"definition"|"readonly"|"static"|"deprecated"|"abstract"|"async"|"modification"|"documentation"|"defaultLibrary" + +--- Inlay hint options used during static registration. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlayHintOptions : nio.lsp.types.WorkDoneProgressOptions +---@field resolveProvider? boolean The server provides support to resolve additional information for an inlay hint item. + +---@class nio.lsp.types.Structure25 +---@field valueSet? nio.lsp.types.FoldingRangeKind[] The folding range kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown. + +--- A diagnostic report with a full set of problems. +--- +--- @since 3.17.0 +---@class nio.lsp.types.FullDocumentDiagnosticReport +---@field kind 'full' A full document diagnostic report. +---@field resultId? string An optional result id. If provided it will be sent on the next diagnostic request for the same document. +---@field items nio.lsp.types.Diagnostic[] The actual items. + +--- A diagnostic report indicating that the last returned +--- report is still accurate. +--- +--- @since 3.17.0 +---@class nio.lsp.types.UnchangedDocumentDiagnosticReport +---@field kind 'unchanged' A document diagnostic report indicating no changes to the last result. A server can only return `unchanged` if result ids are provided. +---@field resultId string A result id which will be sent on the next diagnostic request for the same document. + +---@class nio.lsp.types.Structure26 +---@field collapsedText? boolean If set, the client signals that it supports setting collapsedText on folding ranges to display custom labels instead of the default text. @since 3.17.0 + +--- Diagnostic options. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DiagnosticOptions : nio.lsp.types.WorkDoneProgressOptions +---@field identifier? string An optional identifier under which the diagnostics are managed by the client. +---@field interFileDependencies boolean Whether the language has inter file dependencies meaning that editing code in one file can result in a different diagnostic set in another file. Inter file dependencies are common for most programming languages and typically uncommon for linters. +---@field workspaceDiagnostics boolean The server provides support for workspace diagnostics as well. + +--- A previous result id in a workspace pull request. +--- +--- @since 3.17.0 +---@class nio.lsp.types.PreviousResultId +---@field uri nio.lsp.types.DocumentUri The URI for which the client knowns a result id. +---@field value string The value of the previous result id. +---@alias nio.lsp.types.WorkspaceDocumentDiagnosticReport nio.lsp.types.WorkspaceFullDocumentDiagnosticReport|nio.lsp.types.WorkspaceUnchangedDocumentDiagnosticReport + +---@class nio.lsp.types.Structure42 +---@field commitCharacters? string[] A default commit character set. @since 3.17.0 +---@field editRange? nio.lsp.types.Range|nio.lsp.types.Structure43 A default edit range. @since 3.17.0 +---@field insertTextFormat? nio.lsp.types.InsertTextFormat A default insert text format. @since 3.17.0 +---@field insertTextMode? nio.lsp.types.InsertTextMode A default insert text mode. @since 3.17.0 +---@field data? nio.lsp.types.LSPAny A default data value. @since 3.17.0 + +--- A notebook document. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookDocument +---@field uri nio.lsp.types.URI The notebook document's uri. +---@field notebookType string The type of the notebook. +---@field version integer The version number of this document (it will increase after each change, including undo/redo). +---@field metadata? nio.lsp.types.LSPObject Additional metadata stored with the notebook document. Note: should always be an object literal (e.g. LSPObject) +---@field cells nio.lsp.types.NotebookCell[] The cells of a notebook. + +---@class nio.lsp.types.Structure36 +---@field range nio.lsp.types.Range The range of the document that changed. +---@field rangeLength? integer The optional length of the range that got replaced. @deprecated use range instead. +---@field text string The new text for the provided range. + +---@class nio.lsp.types.Structure41 +---@field notebook? string|nio.lsp.types.NotebookDocumentFilter The notebook to be synced If a string value is provided it matches against the notebook type. '*' matches every notebook. +---@field cells nio.lsp.types.Structure44[] The cells of the matching notebook to be synced. + +--- An item to transfer a text document from the client to the +--- server. +---@class nio.lsp.types.TextDocumentItem +---@field uri nio.lsp.types.DocumentUri The text document's uri. +---@field languageId string The text document's language identifier. +---@field version integer The version number of this document (it will increase after each change, including undo/redo). +---@field text string The content of the opened text document. + +---@class nio.lsp.types.Structure37 +---@field text string The new text of the whole document. +--- Defines how the host (editor) should sync +--- document changes to the language server. +---@alias nio.lsp.types.TextDocumentSyncKind 0|1|2 + +--- A versioned notebook document identifier. +--- +--- @since 3.17.0 +---@class nio.lsp.types.VersionedNotebookDocumentIdentifier +---@field version integer The version number of this notebook document. +---@field uri nio.lsp.types.URI The notebook document's uri. + +---@class nio.lsp.types.Structure40 +---@field notebook string|nio.lsp.types.NotebookDocumentFilter The notebook to be synced If a string value is provided it matches against the notebook type. '*' matches every notebook. +---@field cells? nio.lsp.types.Structure45[] The cells of the matching notebook to be synced. + +--- A change event for a notebook document. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookDocumentChangeEvent +---@field metadata? nio.lsp.types.LSPObject The changed meta data if any. Note: should always be an object literal (e.g. LSPObject) +---@field cells? nio.lsp.types.Structure6 Changes to cells + +---@class nio.lsp.types.Structure39 +---@field range? boolean|nio.lsp.types.Structure46 The client will send the `textDocument/semanticTokens/range` request if the server provides a corresponding handler. +---@field full? boolean|nio.lsp.types.Structure47 The client will send the `textDocument/semanticTokens/full` request if the server provides a corresponding handler. + +---@class nio.lsp.types.Structure38 +---@field properties string[] The properties that a client can resolve lazily. + +--- A literal to identify a notebook document in the client. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookDocumentIdentifier +---@field uri nio.lsp.types.URI The notebook document's uri. + +---@class nio.lsp.types.Structure35 +---@field language string +---@field value string + +---@class nio.lsp.types.Structure34 +---@field additionalPropertiesSupport? boolean Whether the client supports additional attributes which are preserved and send back to the server in the request's response. + +---@class nio.lsp.types.Structure33 +---@field language? string A language id, like `typescript`. +---@field scheme? string A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field pattern string A glob pattern, like **​/*.{ts,js}. See TextDocumentFilter for examples. + +--- The initialize parameters +---@class nio.lsp.types._InitializeParams : nio.lsp.types.WorkDoneProgressParams +---@field processId integer|nil The process Id of the parent process that started the server. Is `null` if the process has not been started by another process. If the parent process is not alive then the server should exit. +---@field clientInfo? nio.lsp.types.Structure7 Information about the client @since 3.15.0 +---@field locale? string The locale the client is currently showing the user interface in. This must not necessarily be the locale of the operating system. Uses IETF language tags as the value's syntax (See https://en.wikipedia.org/wiki/IETF_language_tag) @since 3.16.0 +---@field rootPath? string|nil The rootPath of the workspace. Is null if no folder is open. @deprecated in favour of rootUri. +---@field rootUri nio.lsp.types.DocumentUri|nil The rootUri of the workspace. Is null if no folder is open. If both `rootPath` and `rootUri` are set `rootUri` wins. @deprecated in favour of workspaceFolders. +---@field capabilities nio.lsp.types.ClientCapabilities The capabilities provided by the client (editor or tool) +---@field initializationOptions? nio.lsp.types.LSPAny User provided initialization options. +---@field trace? nio.lsp.types.TraceValues The initial trace setting. If omitted trace is disabled ('off'). + +---@class nio.lsp.types.WorkspaceFoldersInitializeParams +---@field workspaceFolders? nio.lsp.types.WorkspaceFolder[]|nil The workspace folders configured in the client when the server starts. This property is only available if the client supports workspace folders. It can be `null` if the client supports workspace folders but none are configured. @since 3.6.0 + +--- Defines the capabilities provided by a language +--- server. +---@class nio.lsp.types.ServerCapabilities +---@field positionEncoding? nio.lsp.types.PositionEncodingKind The position encoding the server picked from the encodings offered by the client via the client capability `general.positionEncodings`. If the client didn't provide any position encodings the only valid value that a server can return is 'utf-16'. If omitted it defaults to 'utf-16'. @since 3.17.0 +---@field textDocumentSync? nio.lsp.types.TextDocumentSyncOptions|nio.lsp.types.TextDocumentSyncKind Defines how text documents are synced. Is either a detailed structure defining each notification or for backwards compatibility the TextDocumentSyncKind number. +---@field notebookDocumentSync? nio.lsp.types.NotebookDocumentSyncOptions|nio.lsp.types.NotebookDocumentSyncRegistrationOptions Defines how notebook documents are synced. @since 3.17.0 +---@field completionProvider? nio.lsp.types.CompletionOptions The server provides completion support. +---@field hoverProvider? boolean|nio.lsp.types.HoverOptions The server provides hover support. +---@field signatureHelpProvider? nio.lsp.types.SignatureHelpOptions The server provides signature help support. +---@field declarationProvider? boolean|nio.lsp.types.DeclarationOptions|nio.lsp.types.DeclarationRegistrationOptions The server provides Goto Declaration support. +---@field definitionProvider? boolean|nio.lsp.types.DefinitionOptions The server provides goto definition support. +---@field typeDefinitionProvider? boolean|nio.lsp.types.TypeDefinitionOptions|nio.lsp.types.TypeDefinitionRegistrationOptions The server provides Goto Type Definition support. +---@field implementationProvider? boolean|nio.lsp.types.ImplementationOptions|nio.lsp.types.ImplementationRegistrationOptions The server provides Goto Implementation support. +---@field referencesProvider? boolean|nio.lsp.types.ReferenceOptions The server provides find references support. +---@field documentHighlightProvider? boolean|nio.lsp.types.DocumentHighlightOptions The server provides document highlight support. +---@field documentSymbolProvider? boolean|nio.lsp.types.DocumentSymbolOptions The server provides document symbol support. +---@field codeActionProvider? boolean|nio.lsp.types.CodeActionOptions The server provides code actions. CodeActionOptions may only be specified if the client states that it supports `codeActionLiteralSupport` in its initial `initialize` request. +---@field codeLensProvider? nio.lsp.types.CodeLensOptions The server provides code lens. +---@field documentLinkProvider? nio.lsp.types.DocumentLinkOptions The server provides document link support. +---@field colorProvider? boolean|nio.lsp.types.DocumentColorOptions|nio.lsp.types.DocumentColorRegistrationOptions The server provides color provider support. +---@field workspaceSymbolProvider? boolean|nio.lsp.types.WorkspaceSymbolOptions The server provides workspace symbol support. +---@field documentFormattingProvider? boolean|nio.lsp.types.DocumentFormattingOptions The server provides document formatting. +---@field documentRangeFormattingProvider? boolean|nio.lsp.types.DocumentRangeFormattingOptions The server provides document range formatting. +---@field documentOnTypeFormattingProvider? nio.lsp.types.DocumentOnTypeFormattingOptions The server provides document formatting on typing. +---@field renameProvider? boolean|nio.lsp.types.RenameOptions The server provides rename support. RenameOptions may only be specified if the client states that it supports `prepareSupport` in its initial `initialize` request. +---@field foldingRangeProvider? boolean|nio.lsp.types.FoldingRangeOptions|nio.lsp.types.FoldingRangeRegistrationOptions The server provides folding provider support. +---@field selectionRangeProvider? boolean|nio.lsp.types.SelectionRangeOptions|nio.lsp.types.SelectionRangeRegistrationOptions The server provides selection range support. +---@field executeCommandProvider? nio.lsp.types.ExecuteCommandOptions The server provides execute command support. +---@field callHierarchyProvider? boolean|nio.lsp.types.CallHierarchyOptions|nio.lsp.types.CallHierarchyRegistrationOptions The server provides call hierarchy support. @since 3.16.0 +---@field linkedEditingRangeProvider? boolean|nio.lsp.types.LinkedEditingRangeOptions|nio.lsp.types.LinkedEditingRangeRegistrationOptions The server provides linked editing range support. @since 3.16.0 +---@field semanticTokensProvider? nio.lsp.types.SemanticTokensOptions|nio.lsp.types.SemanticTokensRegistrationOptions The server provides semantic tokens support. @since 3.16.0 +---@field monikerProvider? boolean|nio.lsp.types.MonikerOptions|nio.lsp.types.MonikerRegistrationOptions The server provides moniker support. @since 3.16.0 +---@field typeHierarchyProvider? boolean|nio.lsp.types.TypeHierarchyOptions|nio.lsp.types.TypeHierarchyRegistrationOptions The server provides type hierarchy support. @since 3.17.0 +---@field inlineValueProvider? boolean|nio.lsp.types.InlineValueOptions|nio.lsp.types.InlineValueRegistrationOptions The server provides inline values. @since 3.17.0 +---@field inlayHintProvider? boolean|nio.lsp.types.InlayHintOptions|nio.lsp.types.InlayHintRegistrationOptions The server provides inlay hints. @since 3.17.0 +---@field diagnosticProvider? nio.lsp.types.DiagnosticOptions|nio.lsp.types.DiagnosticRegistrationOptions The server has support for pull model diagnostics. @since 3.17.0 +---@field inlineCompletionProvider? boolean|nio.lsp.types.InlineCompletionOptions Inline completion options used during static registration. @since 3.18.0 @proposed +---@field workspace? nio.lsp.types.Structure8 Workspace specific server capabilities. +---@field experimental? nio.lsp.types.LSPAny Experimental server capabilities. + +---@class nio.lsp.types.Structure32 +---@field language? string A language id, like `typescript`. +---@field scheme string A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field pattern? string A glob pattern, like **​/*.{ts,js}. See TextDocumentFilter for examples. + +---@class nio.lsp.types.Structure31 +---@field language string A language id, like `typescript`. +---@field scheme? string A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field pattern? string A glob pattern, like **​/*.{ts,js}. See TextDocumentFilter for examples. + +--- Create file operation. +---@class nio.lsp.types.CreateFile : nio.lsp.types.ResourceOperation +---@field kind 'create' A create +---@field uri nio.lsp.types.DocumentUri The resource to create. +---@field options? nio.lsp.types.CreateFileOptions Additional options + +---@class nio.lsp.types.Structure18 +---@field documentationFormat? nio.lsp.types.MarkupKind[] Client supports the following content formats for the documentation property. The order describes the preferred format of the client. +---@field parameterInformation? nio.lsp.types.Structure48 Client capabilities specific to parameter information. +---@field activeParameterSupport? boolean The client supports the `activeParameter` property on `SignatureInformation` literal. @since 3.16.0 + +--- A string value used as a snippet is a template which allows to insert text +--- and to control the editor cursor when insertion happens. +--- +--- A snippet can define tab stops and placeholders with `$1`, `$2` +--- and `${3:foo}`. `$0` defines the final tab stop, it defaults to +--- the end of the snippet. Variables are defined with `$name` and +--- `${name:default value}`. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.StringValue +---@field kind 'snippet' The kind of string value. +---@field value string The snippet string. + +---@class nio.lsp.types.ExecutionSummary +---@field executionOrder integer A strict monotonically increasing value indicating the execution order of a cell inside a notebook. +---@field success? boolean Whether the execution was successful or not if known by the client. + +---@class nio.lsp.types.Structure22 +---@field codeActionKind nio.lsp.types.Structure49 The code action kind is support with the following value set. + +--- A notebook cell text document filter denotes a cell text +--- document by different properties. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookCellTextDocumentFilter +---@field notebook string|nio.lsp.types.NotebookDocumentFilter A filter that matches against the notebook containing the notebook cell. If a string value is provided it matches against the notebook type. '*' matches every notebook. +---@field language? string A language id like `python`. Will be matched against the language id of the notebook cell document. '*' matches every language. + +---@class nio.lsp.types.Structure24 +---@field labelDetailsSupport? boolean The server has support for completion item label details (see also `CompletionItemLabelDetails`) when receiving a completion item in a resolve call. @since 3.17.0 + +---@class nio.lsp.types.Structure44 +---@field language string + +--- Inline completion options used during static registration. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.InlineCompletionOptions : nio.lsp.types.WorkDoneProgressOptions + +---@class nio.lsp.types.Structure27 +---@field notebookType string The type of the enclosing notebook. +---@field scheme? string A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field pattern? string A glob pattern. + +--- General parameters to register for a notification or to register a provider. +---@class nio.lsp.types.Registration +---@field id string The id used to register the request. The id can be used to deregister the request again. +---@field method string The method / capability to register for. +---@field registerOptions? nio.lsp.types.LSPAny Options necessary for the registration. + +--- General parameters to unregister a request or notification. +---@class nio.lsp.types.Unregistration +---@field id string The id used to unregister the request or notification. Usually an id provided during the register request. +---@field method string The method to unregister for. + +---@class nio.lsp.types.Structure28 +---@field notebookType? string The type of the enclosing notebook. +---@field scheme string A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field pattern? string A glob pattern. + +--- Client capabilities specific to the moniker request. +--- +--- @since 3.16.0 +---@class nio.lsp.types.MonikerClientCapabilities +---@field dynamicRegistration? boolean Whether moniker supports dynamic registration. If this is set to `true` the client supports the new `MonikerRegistrationOptions` return value for the corresponding server capability as well. + +--- A special workspace symbol that supports locations without a range. +--- +--- See also SymbolInformation. +--- +--- @since 3.17.0 +---@class nio.lsp.types.WorkspaceSymbol : nio.lsp.types.BaseSymbolInformation +---@field location nio.lsp.types.Location|nio.lsp.types.Structure50 The location of the symbol. Whether a server is allowed to return a location without a range depends on the client capability `workspace.symbol.resolveSupport`. See SymbolInformation#location for more details. +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved on a workspace symbol between a workspace symbol request and a workspace symbol resolve request. + +---@class nio.lsp.types.Structure29 +---@field notebookType? string The type of the enclosing notebook. +---@field scheme? string A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field pattern string A glob pattern. + +---@class nio.lsp.types.WorkspaceEditClientCapabilities +---@field documentChanges? boolean The client supports versioned document changes in `WorkspaceEdit`s +---@field resourceOperations? nio.lsp.types.ResourceOperationKind[] The resource operations the client supports. Clients should at least support 'create', 'rename' and 'delete' files and folders. @since 3.13.0 +---@field failureHandling? nio.lsp.types.FailureHandlingKind The failure handling strategy of a client if applying the workspace edit fails. @since 3.13.0 +---@field normalizesLineEndings? boolean Whether the client normalizes line endings to the client specific setting. If set to `true` the client will normalize line ending characters in a workspace edit to the client-specified new line character. @since 3.16.0 +---@field changeAnnotationSupport? nio.lsp.types.Structure9 Whether the client in general supports change annotations on text edits, create file, rename file and delete file changes. @since 3.16.0 + +--- A text document identifier to denote a specific version of a text document. +---@class nio.lsp.types.VersionedTextDocumentIdentifier : nio.lsp.types.TextDocumentIdentifier +---@field version integer The version number of this document. + +---@class nio.lsp.types.Structure3 +---@field cancel boolean The client will actively cancel the request. +---@field retryOnContentModified string[] The list of requests for which the client will retry the request if it receives a response with error code `ContentModified` + +---@class nio.lsp.types.DidChangeConfigurationClientCapabilities +---@field dynamicRegistration? boolean Did change configuration notification supports dynamic registration. + +---@class nio.lsp.types.Structure17 +---@field itemDefaults? string[] The client supports the following itemDefaults on a completion list. The value lists the supported property names of the `CompletionList.itemDefaults` object. If omitted no properties are supported. @since 3.17.0 + +---@class nio.lsp.types.DidChangeWatchedFilesClientCapabilities +---@field dynamicRegistration? boolean Did change watched files notification supports dynamic registration. Please note that the current protocol doesn't support static configuration for file changes from the server side. +---@field relativePatternSupport? boolean Whether the client has support for {@link RelativePattern relative pattern} or not. @since 3.17.0 + +---@class nio.lsp.types.Structure16 +---@field valueSet? nio.lsp.types.CompletionItemKind[] The completion item kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown. If this property is not present the client only supports the completion items kinds from `Text` to `Reference` as defined in the initial version of the protocol. + +--- Client capabilities for a {@link WorkspaceSymbolRequest}. +---@class nio.lsp.types.WorkspaceSymbolClientCapabilities +---@field dynamicRegistration? boolean Symbol request supports dynamic registration. +---@field symbolKind? nio.lsp.types.Structure10 Specific capabilities for the `SymbolKind` in the `workspace/symbol` request. +---@field tagSupport? nio.lsp.types.Structure11 The client supports tags on `SymbolInformation`. Clients supporting tags have to handle unknown tags gracefully. @since 3.16.0 +---@field resolveSupport? nio.lsp.types.Structure12 The client support partial workspace symbols. The client will send the request `workspaceSymbol/resolve` to the server to resolve additional properties. @since 3.17.0 + +---@class nio.lsp.types.Structure46 + +---@class nio.lsp.types.Structure14 +---@field document nio.lsp.types.VersionedTextDocumentIdentifier +---@field changes nio.lsp.types.TextDocumentContentChangeEvent[] + +--- The client capabilities of a {@link ExecuteCommandRequest}. +---@class nio.lsp.types.ExecuteCommandClientCapabilities +---@field dynamicRegistration? boolean Execute command supports dynamic registration. + +---@class nio.lsp.types.Structure13 +---@field array nio.lsp.types.NotebookCellArrayChange The change to the cell array. +---@field didOpen? nio.lsp.types.TextDocumentItem[] Additional opened cell text documents. +---@field didClose? nio.lsp.types.TextDocumentIdentifier[] Additional closed cell text documents. + +--- Client capabilities specific to diagnostic pull requests. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DiagnosticClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well. +---@field relatedDocumentSupport? boolean Whether the clients supports related documents for document diagnostic pulls. + +---@class nio.lsp.types.Structure11 +---@field valueSet nio.lsp.types.SymbolTag[] The tags supported by the client. + +--- Save options. +---@class nio.lsp.types.SaveOptions +---@field includeText? boolean The client is supposed to include the content on save. + +---@class nio.lsp.types.Structure10 +---@field valueSet? nio.lsp.types.SymbolKind[] The symbol kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown. If this property is not present the client only supports the symbol kinds from `File` to `Array` as defined in the initial version of the protocol. + +--- The parameters of a {@link DocumentOnTypeFormattingRequest}. +---@class nio.lsp.types.DocumentOnTypeFormattingParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document to format. +---@field position nio.lsp.types.Position The position around which the on type formatting should happen. This is not necessarily the exact position where the character denoted by the property `ch` got typed. +---@field ch string The character that has been typed that triggered the formatting on type request. That is not necessarily the last character that got inserted into the document since the client could auto insert characters as well (e.g. like automatic brace completion). +---@field options nio.lsp.types.FormattingOptions The formatting options. + +--- @since 3.16.0 +---@class nio.lsp.types.CodeLensWorkspaceClientCapabilities +---@field refreshSupport? boolean Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all code lenses currently shown. It should be used with absolute care and is useful for situation where a server for example detect a project wide change that requires such a calculation. + +---@class nio.lsp.types.Structure7 +---@field name string The name of the client as defined by the client. +---@field version? string The client's version as defined by the client. + +--- Capabilities relating to events from file operations by the user in the client. +--- +--- These events do not come from the file system, they come from user operations +--- like renaming a file in the UI. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileOperationClientCapabilities +---@field dynamicRegistration? boolean Whether the client supports dynamic registration for file requests/notifications. +---@field didCreate? boolean The client has support for sending didCreateFiles notifications. +---@field willCreate? boolean The client has support for sending willCreateFiles requests. +---@field didRename? boolean The client has support for sending didRenameFiles notifications. +---@field willRename? boolean The client has support for sending willRenameFiles requests. +---@field didDelete? boolean The client has support for sending didDeleteFiles notifications. +---@field willDelete? boolean The client has support for sending willDeleteFiles requests. + +---@class nio.lsp.types.Structure6 +---@field structure? nio.lsp.types.Structure13 Changes to the cell structure to add or remove cells. +---@field data? nio.lsp.types.NotebookCell[] Changes to notebook cells properties like its kind, execution summary or metadata. +---@field textContent? nio.lsp.types.Structure14[] Changes to the text content of notebook cells. + +---@class nio.lsp.types.Structure4 + +--- An event describing a file change. +---@class nio.lsp.types.FileEvent +---@field uri nio.lsp.types.DocumentUri The file's uri. +---@field type nio.lsp.types.FileChangeType The change type. + +--- Provides information about the context in which an inline completion was requested. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.InlineCompletionContext +---@field triggerKind nio.lsp.types.InlineCompletionTriggerKind Describes how the inline completion was triggered. +---@field selectedCompletionInfo? nio.lsp.types.SelectedCompletionInfo Provides information about the currently selected item in the autocomplete widget if it is visible. +--- A set of predefined code action kinds +---@alias nio.lsp.types.CodeActionKind ""|"quickfix"|"refactor"|"refactor.extract"|"refactor.inline"|"refactor.rewrite"|"source"|"source.organizeImports"|"source.fixAll" + +---@class nio.lsp.types.FileSystemWatcher +---@field globPattern nio.lsp.types.GlobPattern The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail. @since 3.17.0 support for relative patterns. +---@field kind? nio.lsp.types.WatchKind The kind of events of interest. If omitted it defaults to WatchKind.Create | WatchKind.Change | WatchKind.Delete which is 7. + +---@class nio.lsp.types.Structure0 +---@field range nio.lsp.types.Range +---@field placeholder string + +--- Workspace client capabilities specific to diagnostic pull requests. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DiagnosticWorkspaceClientCapabilities +---@field refreshSupport? boolean Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all pulled diagnostics currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation. +---@alias nio.lsp.types.DocumentSelector nio.lsp.types.DocumentFilter[] + +--- Client workspace capabilities specific to folding ranges +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.FoldingRangeWorkspaceClientCapabilities +---@field refreshSupport? boolean Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all folding ranges currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation. @since 3.18.0 @proposed + +--- Notebook specific client capabilities. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookDocumentSyncClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well. +---@field executionSummarySupport? boolean The client supports sending execution summary data per cell. + +--- Contains additional information about the context in which a completion request is triggered. +---@class nio.lsp.types.CompletionContext +---@field triggerKind nio.lsp.types.CompletionTriggerKind How the completion was triggered. +---@field triggerCharacter? string The trigger character (a single character) that has trigger code complete. Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` +--- Predefined error codes. +---@alias nio.lsp.types.ErrorCodes -32700|-32600|-32601|-32602|-32603|-32002|-32001 + +--- Completion client capabilities +---@class nio.lsp.types.CompletionClientCapabilities +---@field dynamicRegistration? boolean Whether completion supports dynamic registration. +---@field completionItem? nio.lsp.types.Structure15 The client supports the following `CompletionItem` specific capabilities. +---@field completionItemKind? nio.lsp.types.Structure16 +---@field insertTextMode? nio.lsp.types.InsertTextMode Defines how the client handles whitespace and indentation when accepting a completion item that uses multi line text in either `insertText` or `textEdit`. @since 3.17.0 +---@field contextSupport? boolean The client supports to send additional context information for a `textDocument/completion` request. +---@field completionList? nio.lsp.types.Structure17 The client supports the following `CompletionList` specific capabilities. @since 3.17.0 +--- The reason why code actions were requested. +--- +--- @since 3.17.0 +---@alias nio.lsp.types.CodeActionTriggerKind 1|2 + +--- Additional details for a completion item label. +--- +--- @since 3.17.0 +---@class nio.lsp.types.CompletionItemLabelDetails +---@field detail? string An optional string which is rendered less prominently directly after {@link CompletionItem.label label}, without any spacing. Should be used for function signatures and type annotations. +---@field description? string An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used for fully qualified names and file paths. + +--- Client workspace capabilities specific to inlay hints. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlayHintWorkspaceClientCapabilities +---@field refreshSupport? boolean Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all inlay hints currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation. + +--- Client Capabilities for a {@link SignatureHelpRequest}. +---@class nio.lsp.types.SignatureHelpClientCapabilities +---@field dynamicRegistration? boolean Whether signature help supports dynamic registration. +---@field signatureInformation? nio.lsp.types.Structure18 The client supports the following `SignatureInformation` specific properties. +---@field contextSupport? boolean The client supports to send additional context information for a `textDocument/signatureHelp` request. A client that opts into contextSupport will also support the `retriggerCharacters` on `SignatureHelpOptions`. @since 3.15.0 +--- The diagnostic tags. +--- +--- @since 3.15.0 +---@alias nio.lsp.types.DiagnosticTag 1|2 + +--- @since 3.14.0 +---@class nio.lsp.types.DeclarationClientCapabilities +---@field dynamicRegistration? boolean Whether declaration supports dynamic registration. If this is set to `true` the client supports the new `DeclarationRegistrationOptions` return value for the corresponding server capability as well. +---@field linkSupport? boolean The client supports additional metadata in the form of declaration links. + +---@class nio.lsp.types.InitializedParams +---@alias nio.lsp.types.WatchKind 1|2|4 + +--- Client Capabilities for a {@link DefinitionRequest}. +---@class nio.lsp.types.DefinitionClientCapabilities +---@field dynamicRegistration? boolean Whether definition supports dynamic registration. +---@field linkSupport? boolean The client supports additional metadata in the form of definition links. @since 3.14.0 + +--- Workspace specific client capabilities. +---@class nio.lsp.types.WorkspaceClientCapabilities +---@field applyEdit? boolean The client supports applying batch edits to the workspace by supporting the request 'workspace/applyEdit' +---@field workspaceEdit? nio.lsp.types.WorkspaceEditClientCapabilities Capabilities specific to `WorkspaceEdit`s. +---@field didChangeConfiguration? nio.lsp.types.DidChangeConfigurationClientCapabilities Capabilities specific to the `workspace/didChangeConfiguration` notification. +---@field didChangeWatchedFiles? nio.lsp.types.DidChangeWatchedFilesClientCapabilities Capabilities specific to the `workspace/didChangeWatchedFiles` notification. +---@field symbol? nio.lsp.types.WorkspaceSymbolClientCapabilities Capabilities specific to the `workspace/symbol` request. +---@field executeCommand? nio.lsp.types.ExecuteCommandClientCapabilities Capabilities specific to the `workspace/executeCommand` request. +---@field workspaceFolders? boolean The client has support for workspace folders. @since 3.6.0 +---@field configuration? boolean The client supports `workspace/configuration` requests. @since 3.6.0 +---@field semanticTokens? nio.lsp.types.SemanticTokensWorkspaceClientCapabilities Capabilities specific to the semantic token requests scoped to the workspace. @since 3.16.0. +---@field codeLens? nio.lsp.types.CodeLensWorkspaceClientCapabilities Capabilities specific to the code lens requests scoped to the workspace. @since 3.16.0. +---@field fileOperations? nio.lsp.types.FileOperationClientCapabilities The client has support for file notifications/requests for user operations on files. Since 3.16.0 +---@field inlineValue? nio.lsp.types.InlineValueWorkspaceClientCapabilities Capabilities specific to the inline values requests scoped to the workspace. @since 3.17.0. +---@field inlayHint? nio.lsp.types.InlayHintWorkspaceClientCapabilities Capabilities specific to the inlay hint requests scoped to the workspace. @since 3.17.0. +---@field diagnostics? nio.lsp.types.DiagnosticWorkspaceClientCapabilities Capabilities specific to the diagnostic requests scoped to the workspace. @since 3.17.0. +---@field foldingRange? nio.lsp.types.FoldingRangeWorkspaceClientCapabilities Capabilities specific to the folding range requests scoped to the workspace. @since 3.18.0 @proposed + +--- Since 3.6.0 +---@class nio.lsp.types.TypeDefinitionClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `TypeDefinitionRegistrationOptions` return value for the corresponding server capability as well. +---@field linkSupport? boolean The client supports additional metadata in the form of definition links. Since 3.14.0 + +---@class nio.lsp.types.TextDocumentSyncClientCapabilities +---@field dynamicRegistration? boolean Whether text document synchronization supports dynamic registration. +---@field willSave? boolean The client supports sending will save notifications. +---@field willSaveWaitUntil? boolean The client supports sending a will save request and waits for a response providing text edits which will be applied to the document before it is saved. +---@field didSave? boolean The client supports did save notifications. + +--- @since 3.6.0 +---@class nio.lsp.types.ImplementationClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `ImplementationRegistrationOptions` return value for the corresponding server capability as well. +---@field linkSupport? boolean The client supports additional metadata in the form of definition links. @since 3.14.0 + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensWorkspaceClientCapabilities +---@field refreshSupport? boolean Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all semantic tokens currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation. + +--- Client Capabilities for a {@link ReferencesRequest}. +---@class nio.lsp.types.ReferenceClientCapabilities +---@field dynamicRegistration? boolean Whether references supports dynamic registration. + +--- A special text edit to provide an insert and a replace operation. +--- +--- @since 3.16.0 +---@class nio.lsp.types.InsertReplaceEdit +---@field newText string The string to be inserted. +---@field insert nio.lsp.types.Range The range if the insert is requested +---@field replace nio.lsp.types.Range The range if the replace is requested. + +--- Client Capabilities for a {@link DocumentHighlightRequest}. +---@class nio.lsp.types.DocumentHighlightClientCapabilities +---@field dynamicRegistration? boolean Whether document highlight supports dynamic registration. + +---@class nio.lsp.types.Structure1 +---@field defaultBehavior boolean + +--- Client Capabilities for a {@link DocumentSymbolRequest}. +---@class nio.lsp.types.DocumentSymbolClientCapabilities +---@field dynamicRegistration? boolean Whether document symbol supports dynamic registration. +---@field symbolKind? nio.lsp.types.Structure19 Specific capabilities for the `SymbolKind` in the `textDocument/documentSymbol` request. +---@field hierarchicalDocumentSymbolSupport? boolean The client supports hierarchical document symbols. +---@field tagSupport? nio.lsp.types.Structure20 The client supports tags on `SymbolInformation`. Tags are supported on `DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true. Clients supporting tags have to handle unknown tags gracefully. @since 3.16.0 +---@field labelSupport? boolean The client supports an additional label presented in the UI when registering a document symbol provider. @since 3.16.0 + +--- The publish diagnostic client capabilities. +---@class nio.lsp.types.PublishDiagnosticsClientCapabilities +---@field relatedInformation? boolean Whether the clients accepts diagnostics with related information. +---@field tagSupport? nio.lsp.types.Structure21 Client supports the tag property to provide meta data about a diagnostic. Clients supporting tags have to handle unknown tags gracefully. @since 3.15.0 +---@field versionSupport? boolean Whether the client interprets the version property of the `textDocument/publishDiagnostics` notification's parameter. @since 3.15.0 +---@field codeDescriptionSupport? boolean Client supports a codeDescription property @since 3.16.0 +---@field dataSupport? boolean Whether code action supports the `data` property which is preserved between a `textDocument/publishDiagnostics` and `textDocument/codeAction` request. @since 3.16.0 + +--- The Client Capabilities of a {@link CodeActionRequest}. +---@class nio.lsp.types.CodeActionClientCapabilities +---@field dynamicRegistration? boolean Whether code action supports dynamic registration. +---@field codeActionLiteralSupport? nio.lsp.types.Structure22 The client support code action literals of type `CodeAction` as a valid response of the `textDocument/codeAction` request. If the property is not set the request can only return `Command` literals. @since 3.8.0 +---@field isPreferredSupport? boolean Whether code action supports the `isPreferred` property. @since 3.15.0 +---@field disabledSupport? boolean Whether code action supports the `disabled` property. @since 3.16.0 +---@field dataSupport? boolean Whether code action supports the `data` property which is preserved between a `textDocument/codeAction` and a `codeAction/resolve` request. @since 3.16.0 +---@field resolveSupport? nio.lsp.types.Structure23 Whether the client supports resolving additional code action properties via a separate `codeAction/resolve` request. @since 3.16.0 +---@field honorsChangeAnnotations? boolean Whether the client honors the change annotations in text edits and resource operations returned via the `CodeAction#edit` property by for example presenting the workspace edit in the user interface and asking for confirmation. @since 3.16.0 +--- Defines whether the insert text in a completion item should be interpreted as +--- plain text or a snippet. +---@alias nio.lsp.types.InsertTextFormat 1|2 + +--- The client capabilities of a {@link CodeLensRequest}. +---@class nio.lsp.types.CodeLensClientCapabilities +---@field dynamicRegistration? boolean Whether code lens supports dynamic registration. +--- Completion item tags are extra annotations that tweak the rendering of a completion +--- item. +--- +--- @since 3.15.0 +---@alias nio.lsp.types.CompletionItemTag 1 + +---@alias nio.lsp.types.DocumentFilter nio.lsp.types.TextDocumentFilter|nio.lsp.types.NotebookCellTextDocumentFilter + +--- The client capabilities of a {@link DocumentLinkRequest}. +---@class nio.lsp.types.DocumentLinkClientCapabilities +---@field dynamicRegistration? boolean Whether document link supports dynamic registration. +---@field tooltipSupport? boolean Whether the client supports the `tooltip` property on `DocumentLink`. @since 3.15.0 +--- The message type +---@alias nio.lsp.types.MessageType 1|2|3|4|5 + +---@class nio.lsp.types.DocumentColorClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `DocumentColorRegistrationOptions` return value for the corresponding server capability as well. +--- A symbol kind. +---@alias nio.lsp.types.SymbolKind 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26 + +--- Client capabilities of a {@link DocumentFormattingRequest}. +---@class nio.lsp.types.DocumentFormattingClientCapabilities +---@field dynamicRegistration? boolean Whether formatting supports dynamic registration. +--- A set of predefined range kinds. +---@alias nio.lsp.types.FoldingRangeKind "comment"|"imports"|"region" + +--- Client capabilities of a {@link DocumentRangeFormattingRequest}. +---@class nio.lsp.types.DocumentRangeFormattingClientCapabilities +---@field dynamicRegistration? boolean Whether range formatting supports dynamic registration. +---@field rangesSupport? boolean Whether the client supports formatting multiple ranges at once. @since 3.18.0 @proposed +---@alias nio.lsp.types.LSPErrorCodes -32803|-32802|-32801|-32800 + +--- Completion options. +---@class nio.lsp.types.CompletionOptions : nio.lsp.types.WorkDoneProgressOptions +---@field triggerCharacters? string[] Most tools trigger completion request automatically without explicitly requesting it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user starts to type an identifier. For example if the user types `c` in a JavaScript file code complete will automatically pop up present `console` besides others as a completion item. Characters that make up identifiers don't need to be listed here. If code complete should automatically be trigger on characters not being valid inside an identifier (for example `.` in JavaScript) list them in `triggerCharacters`. +---@field allCommitCharacters? string[] The list of all possible characters that commit a completion. This field can be used if clients don't support individual commit characters per completion item. See `ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport` If a server provides both `allCommitCharacters` and commit characters on an individual completion item the ones on the completion item win. @since 3.2.0 +---@field resolveProvider? boolean The server provides support to resolve additional information for a completion item. +---@field completionItem? nio.lsp.types.Structure24 The server supports the following `CompletionItem` specific capabilities. @since 3.17.0 + +--- Client capabilities of a {@link DocumentOnTypeFormattingRequest}. +---@class nio.lsp.types.DocumentOnTypeFormattingClientCapabilities +---@field dynamicRegistration? boolean Whether on type formatting supports dynamic registration. +--- The document diagnostic report kinds. +--- +--- @since 3.17.0 +---@alias nio.lsp.types.DocumentDiagnosticReportKind "full"|"unchanged" + +---@class nio.lsp.types.RenameClientCapabilities +---@field dynamicRegistration? boolean Whether rename supports dynamic registration. +---@field prepareSupport? boolean Client supports testing for validity of rename operations before execution. @since 3.12.0 +---@field prepareSupportDefaultBehavior? nio.lsp.types.PrepareSupportDefaultBehavior Client supports the default behavior result. The value indicates the default behavior used by the client. @since 3.16.0 +---@field honorsChangeAnnotations? boolean Whether the client honors the change annotations in text edits and resource operations returned via the rename request's workspace edit by for example presenting the workspace edit in the user interface and asking for confirmation. @since 3.16.0 +--- A set of predefined token types. This set is not fixed +--- an clients can specify additional token types via the +--- corresponding client capabilities. +--- +--- @since 3.16.0 +---@alias nio.lsp.types.SemanticTokenTypes "namespace"|"type"|"class"|"enum"|"interface"|"struct"|"typeParameter"|"parameter"|"variable"|"property"|"enumMember"|"event"|"function"|"method"|"macro"|"keyword"|"modifier"|"comment"|"string"|"number"|"regexp"|"operator"|"decorator" + +---@class nio.lsp.types.FoldingRangeClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration for folding range providers. If this is set to `true` the client supports the new `FoldingRangeRegistrationOptions` return value for the corresponding server capability as well. +---@field rangeLimit? integer The maximum number of folding ranges that the client prefers to receive per document. The value serves as a hint, servers are free to follow the limit. +---@field lineFoldingOnly? boolean If set, the client signals that it only supports folding complete lines. If set, client will ignore specified `startCharacter` and `endCharacter` properties in a FoldingRange. +---@field foldingRangeKind? nio.lsp.types.Structure25 Specific options for the folding range kind. @since 3.17.0 +---@field foldingRange? nio.lsp.types.Structure26 Specific options for the folding range. @since 3.17.0 +---@alias nio.lsp.types.Pattern string + +--- Hover options. +---@class nio.lsp.types.HoverOptions : nio.lsp.types.WorkDoneProgressOptions + +---@class nio.lsp.types.SelectionRangeClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration for selection range providers. If this is set to `true` the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server capability as well. + +--- Additional information about the context in which a signature help request was triggered. +--- +--- @since 3.15.0 +---@class nio.lsp.types.SignatureHelpContext +---@field triggerKind nio.lsp.types.SignatureHelpTriggerKind Action that caused signature help to be triggered. +---@field triggerCharacter? string Character that caused signature help to be triggered. This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter` +---@field isRetrigger boolean `true` if signature help was already showing when it was triggered. Retriggers occurs when the signature help is already active and can be caused by actions such as typing a trigger character, a cursor move, or document content changes. +---@field activeSignatureHelp? nio.lsp.types.SignatureHelp The currently active `SignatureHelp`. The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on the user navigating through available signatures. + +--- Signature help represents the signature of something +--- callable. There can be multiple signature but only one +--- active and only one active parameter. +---@class nio.lsp.types.SignatureHelp +---@field signatures nio.lsp.types.SignatureInformation[] One or more signatures. +---@field activeSignature? integer The active signature. If omitted or the value lies outside the range of `signatures` the value defaults to zero or is ignored if the `SignatureHelp` has no signatures. Whenever possible implementors should make an active decision about the active signature and shouldn't rely on a default value. In future version of the protocol this property might become mandatory to better express this. +---@field activeParameter? integer The active parameter of the active signature. If omitted or the value lies outside the range of `signatures[activeSignature].parameters` defaults to 0 if the active signature has parameters. If the active signature has no parameters it is ignored. In future version of the protocol this property might become mandatory to better express the active parameter if the active signature does have any. + +--- Parameters for a {@link SignatureHelpRequest}. +---@class nio.lsp.types.SignatureHelpParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams +---@field context? nio.lsp.types.SignatureHelpContext The signature help context. This is only available if the client specifies to send this using the client capability `textDocument.signatureHelp.contextSupport === true` @since 3.15.0 + +--- Registration options for a {@link SignatureHelpRequest}. +---@class nio.lsp.types.SignatureHelpRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.SignatureHelpOptions + +--- Parameters for a {@link DefinitionRequest}. +---@class nio.lsp.types.DefinitionParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams + +--- Registration options for a {@link DefinitionRequest}. +---@class nio.lsp.types.DefinitionRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DefinitionOptions +---@alias nio.lsp.types.NotebookDocumentFilter nio.lsp.types.Structure27|nio.lsp.types.Structure28|nio.lsp.types.Structure29 + +--- Parameters for a {@link ReferencesRequest}. +---@class nio.lsp.types.ReferenceParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field context nio.lsp.types.ReferenceContext + +--- Registration options for a {@link ReferencesRequest}. +---@class nio.lsp.types.ReferenceRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.ReferenceOptions +---@alias nio.lsp.types.LSPArray nio.lsp.types.LSPAny[] + +--- A document highlight is a range inside a text document which deserves +--- special attention. Usually a document highlight is visualized by changing +--- the background color of its range. +---@class nio.lsp.types.DocumentHighlight +---@field range nio.lsp.types.Range The range this highlight applies to. +---@field kind? nio.lsp.types.DocumentHighlightKind The highlight kind, default is {@link DocumentHighlightKind.Text text}. + +--- Server Capabilities for a {@link DefinitionRequest}. +---@class nio.lsp.types.DefinitionOptions : nio.lsp.types.WorkDoneProgressOptions + +--- Registration options for a {@link DocumentHighlightRequest}. +---@class nio.lsp.types.DocumentHighlightRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DocumentHighlightOptions + +--- Value-object that contains additional information when +--- requesting references. +---@class nio.lsp.types.ReferenceContext +---@field includeDeclaration boolean Include the declaration of the current symbol. + +--- Represents information about programming constructs like variables, classes, +--- interfaces etc. +---@class nio.lsp.types.SymbolInformation : nio.lsp.types.BaseSymbolInformation +---@field deprecated? boolean Indicates if this symbol is deprecated. @deprecated Use tags instead +---@field location nio.lsp.types.Location The location of this symbol. The location's range is used by a tool to reveal the location in the editor. If the symbol is selected in the tool the range's start information is used to position the cursor. So the range usually spans more than the actual symbol's name and does normally include things like visibility modifiers. The range doesn't have to denote a node range in the sense of an abstract syntax tree. It can therefore not be used to re-construct a hierarchy of the symbols. + +--- Represents programming constructs like variables, classes, interfaces etc. +--- that appear in a document. Document symbols can be hierarchical and they +--- have two ranges: one that encloses its definition and one that points to +--- its most interesting range, e.g. the range of an identifier. +---@class nio.lsp.types.DocumentSymbol +---@field name string The name of this symbol. Will be displayed in the user interface and therefore must not be an empty string or a string only consisting of white spaces. +---@field detail? string More detail for this symbol, e.g the signature of a function. +---@field kind nio.lsp.types.SymbolKind The kind of this symbol. +---@field tags? nio.lsp.types.SymbolTag[] Tags for this document symbol. @since 3.16.0 +---@field deprecated? boolean Indicates if this symbol is deprecated. @deprecated Use tags instead +---@field range nio.lsp.types.Range The range enclosing this symbol not including leading/trailing whitespace but everything else like comments. This information is typically used to determine if the clients cursor is inside the symbol to reveal in the symbol in the UI. +---@field selectionRange nio.lsp.types.Range The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. Must be contained by the `range`. +---@field children? nio.lsp.types.DocumentSymbol[] Children of this symbol, e.g. properties of a class. + +--- Parameters for a {@link DocumentSymbolRequest}. +---@class nio.lsp.types.DocumentSymbolParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. + +--- Registration options for a {@link DocumentSymbolRequest}. +---@class nio.lsp.types.DocumentSymbolRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DocumentSymbolOptions + +--- Provider options for a {@link DocumentLinkRequest}. +---@class nio.lsp.types.DocumentLinkOptions : nio.lsp.types.WorkDoneProgressOptions +---@field resolveProvider? boolean Document links have a resolve provider as well. + +--- A code action represents a change that can be performed in code, e.g. to fix a problem or +--- to refactor code. +--- +--- A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. +---@class nio.lsp.types.CodeAction +---@field title string A short, human-readable, title for this code action. +---@field kind? nio.lsp.types.CodeActionKind The kind of the code action. Used to filter code actions. +---@field diagnostics? nio.lsp.types.Diagnostic[] The diagnostics that this code action resolves. +---@field isPreferred? boolean Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted by keybindings. A quick fix should be marked preferred if it properly addresses the underlying error. A refactoring should be marked preferred if it is the most reasonable choice of actions to take. @since 3.15.0 +---@field disabled? nio.lsp.types.Structure30 Marks that the code action cannot currently be applied. Clients should follow the following guidelines regarding disabled code actions: - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) code action menus. - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type of code action, such as refactorings. - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) that auto applies a code action and only disabled code actions are returned, the client should show the user an error message with `reason` in the editor. @since 3.16.0 +---@field edit? nio.lsp.types.WorkspaceEdit The workspace edit this code action performs. +---@field command? nio.lsp.types.Command A command this code action executes. If a code action provides an edit and a command, first the edit is executed and then the command. +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved on a code action between a `textDocument/codeAction` and a `codeAction/resolve` request. @since 3.16.0 + +--- The parameters of a {@link CodeActionRequest}. +---@class nio.lsp.types.CodeActionParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document in which the command was invoked. +---@field range nio.lsp.types.Range The range for which the command was invoked. +---@field context nio.lsp.types.CodeActionContext Context carrying additional information. + +--- Value-object describing what options formatting should use. +---@class nio.lsp.types.FormattingOptions +---@field tabSize integer Size of a tab in spaces. +---@field insertSpaces boolean Prefer spaces over tabs. +---@field trimTrailingWhitespace? boolean Trim trailing whitespace on a line. @since 3.15.0 +---@field insertFinalNewline? boolean Insert a newline character at the end of the file if one does not exist. @since 3.15.0 +---@field trimFinalNewlines? boolean Trim all newlines after the final newline at the end of the file. @since 3.15.0 +---@alias nio.lsp.types.TextDocumentFilter nio.lsp.types.Structure31|nio.lsp.types.Structure32|nio.lsp.types.Structure33 + +--- Client capabilities specific to inline completions. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.InlineCompletionClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration for inline completion providers. + +--- Provider options for a {@link DocumentFormattingRequest}. +---@class nio.lsp.types.DocumentFormattingOptions : nio.lsp.types.WorkDoneProgressOptions + +--- The parameters of a {@link WorkspaceSymbolRequest}. +---@class nio.lsp.types.WorkspaceSymbolParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field query string A query string to filter symbols by. Clients may send an empty string here to request all symbols. + +--- Registration options for a {@link WorkspaceSymbolRequest}. +---@class nio.lsp.types.WorkspaceSymbolRegistrationOptions : nio.lsp.types.WorkspaceSymbolOptions + +--- A base for all symbol information. +---@class nio.lsp.types.BaseSymbolInformation +---@field name string The name of this symbol. +---@field kind nio.lsp.types.SymbolKind The kind of this symbol. +---@field tags? nio.lsp.types.SymbolTag[] Tags for this symbol. @since 3.16.0 +---@field containerName? string The name of the symbol containing this symbol. This information is for user interface purposes (e.g. to render a qualifier in the user interface if necessary). It can't be used to re-infer a hierarchy for the document symbols. + +--- Show message request client capabilities +---@class nio.lsp.types.ShowMessageRequestClientCapabilities +---@field messageActionItem? nio.lsp.types.Structure34 Capabilities specific to the `MessageActionItem` type. + +--- Provider options for a {@link DocumentRangeFormattingRequest}. +---@class nio.lsp.types.DocumentRangeFormattingOptions : nio.lsp.types.WorkDoneProgressOptions +---@field rangesSupport? boolean Whether the server supports formatting multiple ranges at once. @since 3.18.0 @proposed + +--- A code lens represents a {@link Command command} that should be shown along with +--- source text, like the number of references, a way to run tests, etc. +--- +--- A code lens is _unresolved_ when no command is associated to it. For performance +--- reasons the creation of a code lens and resolving should be done in two stages. +---@class nio.lsp.types.CodeLens +---@field range nio.lsp.types.Range The range in which this code lens is valid. Should only span a single line. +---@field command? nio.lsp.types.Command The command this code lens represents. +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved on a code lens item between a {@link CodeLensRequest} and a {@link CodeLensResolveRequest} + +--- The parameters of a {@link CodeLensRequest}. +---@class nio.lsp.types.CodeLensParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document to request code lens for. + +--- Registration options for a {@link CodeLensRequest}. +---@class nio.lsp.types.CodeLensRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.CodeLensOptions +---@alias nio.lsp.types.GlobPattern nio.lsp.types.Pattern|nio.lsp.types.RelativePattern +---@alias nio.lsp.types.LSPObject table +--- Represents reasons why a text document is saved. +---@alias nio.lsp.types.TextDocumentSaveReason 1|2|3 + +---@alias nio.lsp.types.MarkedString string|nio.lsp.types.Structure35 + +--- Provider options for a {@link DocumentOnTypeFormattingRequest}. +---@class nio.lsp.types.DocumentOnTypeFormattingOptions +---@field firstTriggerCharacter string A character on which formatting should be triggered, like `{`. +---@field moreTriggerCharacter? string[] More trigger characters. + +--- Client capabilities specific to regular expressions. +--- +--- @since 3.16.0 +---@class nio.lsp.types.RegularExpressionsClientCapabilities +---@field engine string The engine's name. +---@field version? string The engine's version. +---@alias nio.lsp.types.TextDocumentContentChangeEvent nio.lsp.types.Structure36|nio.lsp.types.Structure37 + +--- The data type of the ResponseError if the +--- initialize request fails. +---@class nio.lsp.types.InitializeError +---@field retry boolean Indicates whether the client execute the following retry logic: (1) show the message provided by the ResponseError to the user (2) user selects retry or cancel (3) if user selected retry the initialize method is sent again. + +--- Contains additional diagnostic information about the context in which +--- a {@link CodeActionProvider.provideCodeActions code action} is run. +---@class nio.lsp.types.CodeActionContext +---@field diagnostics nio.lsp.types.Diagnostic[] An array of diagnostics known on the client side overlapping the range provided to the `textDocument/codeAction` request. They are provided so that the server knows which errors are currently presented to the user for the given range. There is no guarantee that these accurately reflect the error state of the resource. The primary parameter to compute code actions is the provided range. +---@field only? nio.lsp.types.CodeActionKind[] Requested kind of actions to return. Actions not of this kind are filtered out by the client before being shown. So servers can omit computing them. +---@field triggerKind? nio.lsp.types.CodeActionTriggerKind The reason why code actions were requested. @since 3.17.0 +---@alias nio.lsp.types.FailureHandlingKind "abort"|"transactional"|"textOnlyTransactional"|"undo" + +--- Provider options for a {@link RenameRequest}. +---@class nio.lsp.types.RenameOptions : nio.lsp.types.WorkDoneProgressOptions +---@field prepareProvider? boolean Renames should be checked and tested before being executed. @since version 3.12.0 + +--- The params sent in a change notebook document notification. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DidChangeNotebookDocumentParams +---@field notebookDocument nio.lsp.types.VersionedNotebookDocumentIdentifier The notebook document that did change. The version number points to the version after all provided changes have been applied. If only the text document content of a cell changes the notebook version doesn't necessarily have to change. +---@field change nio.lsp.types.NotebookDocumentChangeEvent The actual changes to the notebook document. The changes describe single state changes to the notebook document. So if there are two changes c1 (at array index 0) and c2 (at array index 1) for a notebook in state S then c1 moves the notebook from S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed on the state S'. To mirror the content of a notebook using change events use the following approach: - start with the same initial content - apply the 'notebookDocument/didChange' notifications in the order you receive them. - apply the `NotebookChangeEvent`s in a single notification in the order you receive them. + +---@class nio.lsp.types.Structure19 +---@field valueSet? nio.lsp.types.SymbolKind[] The symbol kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown. If this property is not present the client only supports the symbol kinds from `File` to `Array` as defined in the initial version of the protocol. +---@alias nio.lsp.types.LSPAny nio.lsp.types.LSPObject|nio.lsp.types.LSPArray|string|integer|integer|number|boolean|nil + +--- The server capabilities of a {@link ExecuteCommandRequest}. +---@class nio.lsp.types.ExecuteCommandOptions : nio.lsp.types.WorkDoneProgressOptions +---@field commands string[] The commands to be executed on the server + +--- Client capabilities specific to the used markdown parser. +--- +--- @since 3.16.0 +---@class nio.lsp.types.MarkdownClientCapabilities +---@field parser string The name of the parser. +---@field version? string The version of the parser. +---@field allowedTags? string[] A list of HTML tags that the client allows / supports in Markdown. @since 3.17.0 + +--- Client capabilities for the showDocument request. +--- +--- @since 3.16.0 +---@class nio.lsp.types.ShowDocumentClientCapabilities +---@field support boolean The client has support for the showDocument request. +---@alias nio.lsp.types.ResourceOperationKind "create"|"rename"|"delete" + +---@class nio.lsp.types.Structure12 +---@field properties string[] The properties that a client can resolve lazily. Usually `location.range` + +--- Inlay hint client capabilities. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlayHintClientCapabilities +---@field dynamicRegistration? boolean Whether inlay hints support dynamic registration. +---@field resolveSupport? nio.lsp.types.Structure38 Indicates which properties a client can resolve lazily on an inlay hint. + +--- Client capabilities specific to inline values. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration for inline value providers. + +--- @since 3.17.0 +---@class nio.lsp.types.TypeHierarchyClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well. + +---@class nio.lsp.types.Structure20 +---@field valueSet nio.lsp.types.SymbolTag[] The tags supported by the client. + +--- Client capabilities for the linked editing range request. +--- +--- @since 3.16.0 +---@class nio.lsp.types.LinkedEditingRangeClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well. + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well. +---@field requests nio.lsp.types.Structure39 Which requests the client supports and might send to the server depending on the server's capability. Please note that clients might not show semantic tokens or degrade some of the user experience if a range or full request is advertised by the client but not provided by the server. If for example the client capability `requests.full` and `request.range` are both set to true but the server only provides a range provider the client might not render a minimap correctly or might even decide to not show any semantic tokens at all. +---@field tokenTypes string[] The token types that the client supports. +---@field tokenModifiers string[] The token modifiers that the client supports. +---@field formats nio.lsp.types.TokenFormat[] The token formats the clients supports. +---@field overlappingTokenSupport? boolean Whether the client supports tokens that can overlap each other. +---@field multilineTokenSupport? boolean Whether the client supports tokens that can span multiple lines. +---@field serverCancelSupport? boolean Whether the client allows the server to actively cancel a semantic token request, e.g. supports returning LSPErrorCodes.ServerCancelled. If a server does the client needs to retrigger the request. @since 3.17.0 +---@field augmentsSyntaxTokens? boolean Whether the client uses semantic tokens to augment existing syntax tokens. If set to `true` client side created syntax tokens and semantic tokens are both used for colorization. If set to `false` the client only uses the returned semantic tokens for colorization. If the value is `undefined` then the client behavior is not specified. @since 3.17.0 + +---@class nio.lsp.types.WorkDoneProgressBegin +---@field kind 'begin' +---@field title string Mandatory title of the progress operation. Used to briefly inform about the kind of operation being performed. Examples: "Indexing" or "Linking dependencies". +---@field cancellable? boolean Controls if a cancel button should show to allow the user to cancel the long running operation. Clients that don't support cancellation are allowed to ignore the setting. +---@field message? string Optional, more detailed associated progress message. Contains complementary information to the `title`. Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". If unset, the previous progress message (if any) is still valid. +---@field percentage? integer Optional progress percentage to display (value 100 is considered 100%). If not provided infinite progress is assumed and clients are allowed to ignore the `percentage` value in subsequent in report notifications. The value should be steadily rising. Clients are free to ignore values that are not following this rule. The value range is [0, 100]. + +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyClientCapabilities +---@field dynamicRegistration? boolean Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well. +--- A document highlight kind. +---@alias nio.lsp.types.DocumentHighlightKind 1|2|3 + +---@class nio.lsp.types.HoverClientCapabilities +---@field dynamicRegistration? boolean Whether hover supports dynamic registration. +---@field contentFormat? nio.lsp.types.MarkupKind[] Client supports the following content formats for the content property. The order describes the preferred format of the client. +--- Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. +--- +--- @since 3.18.0 +--- @proposed +---@alias nio.lsp.types.InlineCompletionTriggerKind 0|1 + +---@class nio.lsp.types.WorkDoneProgressReport +---@field kind 'report' +---@field cancellable? boolean Controls enablement state of a cancel button. Clients that don't support cancellation or don't support controlling the button's enablement state are allowed to ignore the property. +---@field message? string Optional, more detailed associated progress message. Contains complementary information to the `title`. Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". If unset, the previous progress message (if any) is still valid. +---@field percentage? integer Optional progress percentage to display (value 100 is considered 100%). If not provided infinite progress is assumed and clients are allowed to ignore the `percentage` value in subsequent in report notifications. The value should be steadily rising. Clients are free to ignore values that are not following this rule. The value range is [0, 100] +--- How a completion was triggered +---@alias nio.lsp.types.CompletionTriggerKind 1|2|3 + +--- Describes the currently selected completion item. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.SelectedCompletionInfo +---@field range nio.lsp.types.Range The range that will be replaced if this completion item is accepted. +---@field text string The text the range will be replaced with if this completion is accepted. + +---@class nio.lsp.types.WorkDoneProgressEnd +---@field kind 'end' +---@field message? string Optional, a final message indicating to for example indicate the outcome of the operation. + +--- Client workspace capabilities specific to inline values. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueWorkspaceClientCapabilities +---@field refreshSupport? boolean Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all inline values currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation. +---@alias nio.lsp.types.TraceValues "off"|"messages"|"verbose" + +--- Represents a color in RGBA space. +---@class nio.lsp.types.Color +---@field red number The red component of this color in the range [0-1]. +---@field green number The green component of this color in the range [0-1]. +---@field blue number The blue component of this color in the range [0-1]. +---@field alpha number The alpha component of this color in the range [0-1]. + +--- A relative pattern is a helper to construct glob patterns that are matched +--- relatively to a base URI. The common value for a `baseUri` is a workspace +--- folder root, but it can be another absolute URI as well. +--- +--- @since 3.17.0 +---@class nio.lsp.types.RelativePattern +---@field baseUri nio.lsp.types.WorkspaceFolder|nio.lsp.types.URI A workspace folder or a base URI to which this pattern will be matched against relatively. +---@field pattern nio.lsp.types.Pattern The actual glob pattern; + +--- Text document specific client capabilities. +---@class nio.lsp.types.TextDocumentClientCapabilities +---@field synchronization? nio.lsp.types.TextDocumentSyncClientCapabilities Defines which synchronization capabilities the client supports. +---@field completion? nio.lsp.types.CompletionClientCapabilities Capabilities specific to the `textDocument/completion` request. +---@field hover? nio.lsp.types.HoverClientCapabilities Capabilities specific to the `textDocument/hover` request. +---@field signatureHelp? nio.lsp.types.SignatureHelpClientCapabilities Capabilities specific to the `textDocument/signatureHelp` request. +---@field declaration? nio.lsp.types.DeclarationClientCapabilities Capabilities specific to the `textDocument/declaration` request. @since 3.14.0 +---@field definition? nio.lsp.types.DefinitionClientCapabilities Capabilities specific to the `textDocument/definition` request. +---@field typeDefinition? nio.lsp.types.TypeDefinitionClientCapabilities Capabilities specific to the `textDocument/typeDefinition` request. @since 3.6.0 +---@field implementation? nio.lsp.types.ImplementationClientCapabilities Capabilities specific to the `textDocument/implementation` request. @since 3.6.0 +---@field references? nio.lsp.types.ReferenceClientCapabilities Capabilities specific to the `textDocument/references` request. +---@field documentHighlight? nio.lsp.types.DocumentHighlightClientCapabilities Capabilities specific to the `textDocument/documentHighlight` request. +---@field documentSymbol? nio.lsp.types.DocumentSymbolClientCapabilities Capabilities specific to the `textDocument/documentSymbol` request. +---@field codeAction? nio.lsp.types.CodeActionClientCapabilities Capabilities specific to the `textDocument/codeAction` request. +---@field codeLens? nio.lsp.types.CodeLensClientCapabilities Capabilities specific to the `textDocument/codeLens` request. +---@field documentLink? nio.lsp.types.DocumentLinkClientCapabilities Capabilities specific to the `textDocument/documentLink` request. +---@field colorProvider? nio.lsp.types.DocumentColorClientCapabilities Capabilities specific to the `textDocument/documentColor` and the `textDocument/colorPresentation` request. @since 3.6.0 +---@field formatting? nio.lsp.types.DocumentFormattingClientCapabilities Capabilities specific to the `textDocument/formatting` request. +---@field rangeFormatting? nio.lsp.types.DocumentRangeFormattingClientCapabilities Capabilities specific to the `textDocument/rangeFormatting` request. +---@field onTypeFormatting? nio.lsp.types.DocumentOnTypeFormattingClientCapabilities Capabilities specific to the `textDocument/onTypeFormatting` request. +---@field rename? nio.lsp.types.RenameClientCapabilities Capabilities specific to the `textDocument/rename` request. +---@field foldingRange? nio.lsp.types.FoldingRangeClientCapabilities Capabilities specific to the `textDocument/foldingRange` request. @since 3.10.0 +---@field selectionRange? nio.lsp.types.SelectionRangeClientCapabilities Capabilities specific to the `textDocument/selectionRange` request. @since 3.15.0 +---@field publishDiagnostics? nio.lsp.types.PublishDiagnosticsClientCapabilities Capabilities specific to the `textDocument/publishDiagnostics` notification. +---@field callHierarchy? nio.lsp.types.CallHierarchyClientCapabilities Capabilities specific to the various call hierarchy requests. @since 3.16.0 +---@field semanticTokens? nio.lsp.types.SemanticTokensClientCapabilities Capabilities specific to the various semantic token request. @since 3.16.0 +---@field linkedEditingRange? nio.lsp.types.LinkedEditingRangeClientCapabilities Capabilities specific to the `textDocument/linkedEditingRange` request. @since 3.16.0 +---@field moniker? nio.lsp.types.MonikerClientCapabilities Client capabilities specific to the `textDocument/moniker` request. @since 3.16.0 +---@field typeHierarchy? nio.lsp.types.TypeHierarchyClientCapabilities Capabilities specific to the various type hierarchy requests. @since 3.17.0 +---@field inlineValue? nio.lsp.types.InlineValueClientCapabilities Capabilities specific to the `textDocument/inlineValue` request. @since 3.17.0 +---@field inlayHint? nio.lsp.types.InlayHintClientCapabilities Capabilities specific to the `textDocument/inlayHint` request. @since 3.17.0 +---@field diagnostic? nio.lsp.types.DiagnosticClientCapabilities Capabilities specific to the diagnostic pull model. @since 3.17.0 +---@field inlineCompletion? nio.lsp.types.InlineCompletionClientCapabilities Client capabilities specific to inline completions. @since 3.18.0 @proposed +--- The file event type +---@alias nio.lsp.types.FileChangeType 1|2|3 + +---@class nio.lsp.types.Structure21 +---@field valueSet nio.lsp.types.DiagnosticTag[] The tags supported by the client. + +--- Represents a parameter of a callable-signature. A parameter can +--- have a label and a doc-comment. +---@class nio.lsp.types.ParameterInformation +---@field label string|integer,integer The label of this parameter information. Either a string or an inclusive start and exclusive end offsets within its containing signature label. (see SignatureInformation.label). The offsets are based on a UTF-16 string representation as `Position` and `Range` does. *Note*: a label of type string should be a substring of its containing signature label. Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`. +---@field documentation? string|nio.lsp.types.MarkupContent The human-readable doc-comment of this parameter. Will be shown in the UI but can be omitted. + +--- Represents a related message and source code location for a diagnostic. This should be +--- used to point to code locations that cause or related to a diagnostics, e.g when duplicating +--- a symbol in a scope. +---@class nio.lsp.types.DiagnosticRelatedInformation +---@field location nio.lsp.types.Location The location of this related diagnostic information. +---@field message string The message of this related diagnostic information. + +--- Structure to capture a description for an error code. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CodeDescription +---@field href nio.lsp.types.URI An URI to open with more information about the diagnostic error. + +--- Represents the connection of two locations. Provides additional metadata over normal {@link Location locations}, +--- including an origin range. +---@class nio.lsp.types.LocationLink +---@field originSelectionRange? nio.lsp.types.Range Span of the origin of this link. Used as the underlined span for mouse interaction. Defaults to the word range at the definition position. +---@field targetUri nio.lsp.types.DocumentUri The target resource identifier of this link. +---@field targetRange nio.lsp.types.Range The full target range of this link. If the target for example is a symbol then target range is the range enclosing this symbol not including leading/trailing whitespace but everything else like comments. This information is typically used to highlight the range in the editor. +---@field targetSelectionRange nio.lsp.types.Range The range that should be selected and revealed when this link is being followed, e.g the name of a function. Must be contained by the `targetRange`. See also `DocumentSymbol#range` +--- The diagnostic's severity. +---@alias nio.lsp.types.DiagnosticSeverity 1|2|3|4 + +---@class nio.lsp.types.WorkspaceFoldersServerCapabilities +---@field supported? boolean The server has support for workspace folders +---@field changeNotifications? string|boolean Whether the server wants to receive workspace folder change notifications. If a string is provided the string is treated as an ID under which the notification is registered on the client side. The ID can be used to unregister for these events using the `client/unregisterCapability` request. + +---@class nio.lsp.types.MessageActionItem +---@field title string A short title like 'Retry', 'Open Log' etc. + +--- The parameters of a change configuration notification. +---@class nio.lsp.types.DidChangeConfigurationParams +---@field settings nio.lsp.types.LSPAny The actual changed settings + +---@class nio.lsp.types.Structure2 +---@field name string The name of the server as defined by the server. +---@field version? string The server's version as defined by the server. + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensPartialResult +---@field data integer[] + +--- A change describing how to move a `NotebookCell` +--- array from state S to S'. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookCellArrayChange +---@field start integer The start oftest of the cell that changed. +---@field deleteCount integer The deleted cells +---@field cells? nio.lsp.types.NotebookCell[] The new cells, if any + +--- Parameters of the workspace diagnostic request. +--- +--- @since 3.17.0 +---@class nio.lsp.types.WorkspaceDiagnosticParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field identifier? string The additional identifier provided during registration. +---@field previousResultIds nio.lsp.types.PreviousResultId[] The currently known diagnostic reports with their previous result ids. + +--- The parameters of a {@link RenameRequest}. +---@class nio.lsp.types.RenameParams : nio.lsp.types.WorkDoneProgressParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document to rename. +---@field position nio.lsp.types.Position The position at which this request was sent. +---@field newName string The new name of the symbol. If the given name is not valid the request must return a {@link ResponseError} with an appropriate message set. + +---@class nio.lsp.types.PrepareRenameParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams + +--- Defines the capabilities provided by the client. +---@class nio.lsp.types.ClientCapabilities +---@field workspace? nio.lsp.types.WorkspaceClientCapabilities Workspace specific client capabilities. +---@field textDocument? nio.lsp.types.TextDocumentClientCapabilities Text document specific client capabilities. +---@field notebookDocument? nio.lsp.types.NotebookDocumentClientCapabilities Capabilities specific to the notebook document support. @since 3.17.0 +---@field window? nio.lsp.types.WindowClientCapabilities Window specific client capabilities. +---@field general? nio.lsp.types.GeneralClientCapabilities General client capabilities. @since 3.16.0 +---@field experimental? nio.lsp.types.LSPAny Experimental client capabilities. + +---@class nio.lsp.types.ImplementationParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams + +---@class nio.lsp.types.ImplementationRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.ImplementationOptions,nio.lsp.types.StaticRegistrationOptions + +--- Provider options for a {@link DocumentSymbolRequest}. +---@class nio.lsp.types.DocumentSymbolOptions : nio.lsp.types.WorkDoneProgressOptions +---@field label? string A human-readable string that is shown when multiple outlines trees are shown for the same document. @since 3.16.0 + +--- Reference options. +---@class nio.lsp.types.ReferenceOptions : nio.lsp.types.WorkDoneProgressOptions + +--- Server Capabilities for a {@link SignatureHelpRequest}. +---@class nio.lsp.types.SignatureHelpOptions : nio.lsp.types.WorkDoneProgressOptions +---@field triggerCharacters? string[] List of characters that trigger signature help automatically. +---@field retriggerCharacters? string[] List of characters that re-trigger signature help. These trigger characters are only active when signature help is already showing. All trigger characters are also counted as re-trigger characters. @since 3.15.0 + +--- Represents the signature of something callable. A signature +--- can have a label, like a function-name, a doc-comment, and +--- a set of parameters. +---@class nio.lsp.types.SignatureInformation +---@field label string The label of this signature. Will be shown in the UI. +---@field documentation? string|nio.lsp.types.MarkupContent The human-readable doc-comment of this signature. Will be shown in the UI but can be omitted. +---@field parameters? nio.lsp.types.ParameterInformation[] The parameters of this signature. +---@field activeParameter? integer The index of the active parameter. If provided, this is used in place of `SignatureHelp.activeParameter`. @since 3.16.0 + +--- Cancellation data returned from a diagnostic request. +--- +--- @since 3.17.0 +---@class nio.lsp.types.DiagnosticServerCancellationData +---@field retriggerRequest boolean + +---@class nio.lsp.types.TextDocumentSyncOptions +---@field openClose? boolean Open and close notifications are sent to the server. If omitted open close notification should not be sent. +---@field change? nio.lsp.types.TextDocumentSyncKind Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None. +---@field willSave? boolean If present will save notifications are sent to the server. If omitted the notification should not be sent. +---@field willSaveWaitUntil? boolean If present will save wait until requests are sent to the server. If omitted the request should not be sent. +---@field save? boolean|nio.lsp.types.SaveOptions If present save notifications are sent to the server. If omitted the notification should not be sent. + +--- The parameter of a `textDocument/prepareCallHierarchy` request. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyPrepareParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams + +--- Completion parameters +---@class nio.lsp.types.CompletionParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field context? nio.lsp.types.CompletionContext The completion context. This is only available it the client specifies to send this using the client capability `textDocument.completion.contextSupport === true` + +--- Options specific to a notebook plus its cells +--- to be synced to the server. +--- +--- If a selector provides a notebook document +--- filter but no cell selector all cells of a +--- matching notebook document will be synced. +--- +--- If a selector provides no notebook document +--- filter but only a cell selector all notebook +--- document that contain at least one matching +--- cell will be synced. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookDocumentSyncOptions +---@field notebookSelector nio.lsp.types.Structure40|nio.lsp.types.Structure41[] The notebooks to be synced +---@field save? boolean Whether save notification should be forwarded to the server. Will only be honored if mode === `notebook`. + +--- Registration options specific to a notebook. +--- +--- @since 3.17.0 +---@class nio.lsp.types.NotebookDocumentSyncRegistrationOptions : nio.lsp.types.NotebookDocumentSyncOptions,nio.lsp.types.StaticRegistrationOptions + +--- An unchanged diagnostic report with a set of related documents. +--- +--- @since 3.17.0 +---@class nio.lsp.types.RelatedUnchangedDocumentDiagnosticReport : nio.lsp.types.UnchangedDocumentDiagnosticReport +---@field relatedDocuments? table Diagnostics of related documents. This information is useful in programming languages where code in a file A can generate diagnostics in a file B which A depends on. An example of such a language is C/C++ where marco definitions in a file a.cpp and result in errors in a header file b.hpp. @since 3.17.0 + +--- Provider options for a {@link CodeActionRequest}. +---@class nio.lsp.types.CodeActionOptions : nio.lsp.types.WorkDoneProgressOptions +---@field codeActionKinds? nio.lsp.types.CodeActionKind[] CodeActionKinds that this server may return. The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server may list out every specific kind they provide. +---@field resolveProvider? boolean The server provides support to resolve additional information for a code action. @since 3.16.0 + +--- A full diagnostic report with a set of related documents. +--- +--- @since 3.17.0 +---@class nio.lsp.types.RelatedFullDocumentDiagnosticReport : nio.lsp.types.FullDocumentDiagnosticReport +---@field relatedDocuments? table Diagnostics of related documents. This information is useful in programming languages where code in a file A can generate diagnostics in a file B which A depends on. An example of such a language is C/C++ where marco definitions in a file a.cpp and result in errors in a header file b.hpp. @since 3.17.0 + +--- Registration options for a {@link DocumentRangeFormattingRequest}. +---@class nio.lsp.types.DocumentRangeFormattingRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.DocumentRangeFormattingOptions + +--- Represents a collection of {@link CompletionItem completion items} to be presented +--- in the editor. +---@class nio.lsp.types.CompletionList +---@field isIncomplete boolean This list it not complete. Further typing results in recomputing this list. Recomputed lists have all their items replaced (not appended) in the incomplete completion sessions. +---@field itemDefaults? nio.lsp.types.Structure42 In many cases the items of an actual completion result share the same value for properties like `commitCharacters` or the range of a text edit. A completion list can therefore define item defaults which will be used if a completion item itself doesn't specify the value. If a completion list specifies a default value and a completion item also specifies a corresponding value the one from the item is used. Servers are only allowed to return default values if the client signals support for this via the `completionList.itemDefaults` capability. @since 3.17.0 +---@field items nio.lsp.types.CompletionItem[] The completion items. + +---@class nio.lsp.types.DeclarationRegistrationOptions : nio.lsp.types.DeclarationOptions,nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.StaticRegistrationOptions + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensLegend +---@field tokenTypes string[] The token types a server uses. +---@field tokenModifiers string[] The token modifiers a server uses. + +---@class nio.lsp.types.DeclarationOptions : nio.lsp.types.WorkDoneProgressOptions + +--- Server capabilities for a {@link WorkspaceSymbolRequest}. +---@class nio.lsp.types.WorkspaceSymbolOptions : nio.lsp.types.WorkDoneProgressOptions +---@field resolveProvider? boolean The server provides support to resolve additional information for a workspace symbol. @since 3.17.0 + +--- Save registration options. +---@class nio.lsp.types.TextDocumentSaveRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.SaveOptions + +--- Inline completion options used during static or dynamic registration. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.InlineCompletionRegistrationOptions : nio.lsp.types.InlineCompletionOptions,nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.StaticRegistrationOptions + +---@class nio.lsp.types.MonikerOptions : nio.lsp.types.WorkDoneProgressOptions + +--- The parameters of a {@link DocumentLinkRequest}. +---@class nio.lsp.types.DocumentLinkParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document to provide document links for. + +--- The result returned from the apply workspace edit request. +--- +--- @since 3.17 renamed from ApplyWorkspaceEditResponse +---@class nio.lsp.types.ApplyWorkspaceEditResult +---@field applied boolean Indicates whether the edit was applied or not. +---@field failureReason? string An optional textual description for why the edit was not applied. This may be used by the server for diagnostic logging or to provide a suitable error for a request that triggered the edit. +---@field failedChange? integer Depending on the client's failure handling strategy `failedChange` might contain the index of the change that failed. This property is only available if the client signals a `failureHandlingStrategy` in its client capabilities. + +--- Code Lens provider options of a {@link CodeLensRequest}. +---@class nio.lsp.types.CodeLensOptions : nio.lsp.types.WorkDoneProgressOptions +---@field resolveProvider? boolean Code lens has a resolve provider as well. + +--- Registration options for a {@link RenameRequest}. +---@class nio.lsp.types.RenameRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.RenameOptions + +--- A text document identifier to optionally denote a specific version of a text document. +---@class nio.lsp.types.OptionalVersionedTextDocumentIdentifier : nio.lsp.types.TextDocumentIdentifier +---@field version integer|nil The version number of this document. If a versioned text document identifier is sent from the server to the client and the file is not open in the editor (the server has not received an open notification before) the server can send `null` to indicate that the version is unknown and the content on disk is the truth (as specified with document content ownership). + +--- Represents a folding range. To be valid, start and end line must be bigger than zero and smaller +--- than the number of lines in the document. Clients are free to ignore invalid ranges. +---@class nio.lsp.types.FoldingRange +---@field startLine integer The zero-based start line of the range to fold. The folded area starts after the line's last character. To be valid, the end must be zero or larger and smaller than the number of lines in the document. +---@field startCharacter? integer The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. +---@field endLine integer The zero-based end line of the range to fold. The folded area ends with the line's last character. To be valid, the end must be zero or larger and smaller than the number of lines in the document. +---@field endCharacter? integer The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. +---@field kind? nio.lsp.types.FoldingRangeKind Describes the kind of the folding range such as `comment' or 'region'. The kind is used to categorize folding ranges and used by commands like 'Fold all comments'. See {@link FoldingRangeKind} for an enumeration of standardized kinds. +---@field collapsedText? string The text that the client should show when the specified range is collapsed. If not defined or not supported by the client, a default will be chosen by the client. @since 3.17.0 + +--- A special text edit with an additional change annotation. +--- +--- @since 3.16.0. +---@class nio.lsp.types.AnnotatedTextEdit : nio.lsp.types.TextEdit +---@field annotationId nio.lsp.types.ChangeAnnotationIdentifier The actual identifier of the change annotation + +--- The parameters of a {@link DocumentFormattingRequest}. +---@class nio.lsp.types.DocumentFormattingParams : nio.lsp.types.WorkDoneProgressParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document to format. +---@field options nio.lsp.types.FormattingOptions The format options. + +---@class nio.lsp.types.Structure23 +---@field properties string[] The properties that a client can resolve lazily. + +--- The parameters of a {@link DocumentRangesFormattingRequest}. +--- +--- @since 3.18.0 +--- @proposed +---@class nio.lsp.types.DocumentRangesFormattingParams : nio.lsp.types.WorkDoneProgressParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document to format. +---@field ranges nio.lsp.types.Range[] The ranges to format +---@field options nio.lsp.types.FormattingOptions The format options + +--- The parameters of a {@link DocumentRangeFormattingRequest}. +---@class nio.lsp.types.DocumentRangeFormattingParams : nio.lsp.types.WorkDoneProgressParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document to format. +---@field range nio.lsp.types.Range The range to format +---@field options nio.lsp.types.FormattingOptions The format options + +---@class nio.lsp.types.WorkDoneProgressOptions +---@field workDoneProgress? boolean + +--- Options to create a file. +---@class nio.lsp.types.CreateFileOptions +---@field overwrite? boolean Overwrite existing file. Overwrite wins over `ignoreIfExists` +---@field ignoreIfExists? boolean Ignore if exists. + +---@class nio.lsp.types.Structure9 +---@field groupsOnLabel? boolean Whether the client groups edits with equal labels into tree nodes, for instance all edits labelled with "Changes in Strings" would be a tree node. + +--- A generic resource operation. +---@class nio.lsp.types.ResourceOperation +---@field kind string The resource operation kind. +---@field annotationId? nio.lsp.types.ChangeAnnotationIdentifier An optional annotation identifier describing the operation. @since 3.16.0 + +--- Parameters for a {@link FoldingRangeRequest}. +---@class nio.lsp.types.FoldingRangeParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. + +---@class nio.lsp.types.FoldingRangeRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.FoldingRangeOptions,nio.lsp.types.StaticRegistrationOptions + +--- Represents a reference to a command. Provides a title which +--- will be used to represent a command in the UI and, optionally, +--- an array of arguments which will be passed to the command handler +--- function when invoked. +---@class nio.lsp.types.Command +---@field title string Title of the command, like `save`. +---@field command string The identifier of the actual command handler. +---@field arguments? nio.lsp.types.LSPAny[] Arguments that the command handler should be invoked with. + +--- A filter to describe in which file operation requests or notifications +--- the server is interested in receiving. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileOperationFilter +---@field scheme? string A Uri scheme like `file` or `untitled`. +---@field pattern nio.lsp.types.FileOperationPattern The actual file operation pattern. + +--- Rename file options +---@class nio.lsp.types.RenameFileOptions +---@field overwrite? boolean Overwrite target if existing. Overwrite wins over `ignoreIfExists` +---@field ignoreIfExists? boolean Ignores if target exists. + +---@class nio.lsp.types.Structure30 +---@field reason string Human readable description of why the code action is currently disabled. This is displayed in the code actions UI. +---@alias nio.lsp.types.Declaration nio.lsp.types.Location|nio.lsp.types.Location[] +---@alias nio.lsp.types.DeclarationLink nio.lsp.types.LocationLink + +---@class nio.lsp.types.DeclarationParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams + +--- Delete file options +---@class nio.lsp.types.DeleteFileOptions +---@field recursive? boolean Delete the content recursively if a folder is denoted. +---@field ignoreIfNotExists? boolean Ignore the operation if the file doesn't exist. + +--- The parameters passed via an apply workspace edit request. +---@class nio.lsp.types.ApplyWorkspaceEditParams +---@field label? string An optional label of the workspace edit. This label is presented in the user interface for example on an undo stack to undo the workspace edit. +---@field edit nio.lsp.types.WorkspaceEdit The edits to apply. + +--- A selection range represents a part of a selection hierarchy. A selection range +--- may have a parent selection range that contains it. +---@class nio.lsp.types.SelectionRange +---@field range nio.lsp.types.Range The {@link Range range} of this selection range. +---@field parent? nio.lsp.types.SelectionRange The parent selection range containing this range. Therefore `parent.range` must contain `this.range`. + +--- A parameter literal used in selection range requests. +---@class nio.lsp.types.SelectionRangeParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. +---@field positions nio.lsp.types.Position[] The positions inside the text document. + +---@class nio.lsp.types.SelectionRangeRegistrationOptions : nio.lsp.types.SelectionRangeOptions,nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.StaticRegistrationOptions + +--- Represents a location inside a resource, such as a line +--- inside a text file. +---@class nio.lsp.types.Location +---@field uri nio.lsp.types.DocumentUri +---@field range nio.lsp.types.Range + +---@class nio.lsp.types.WorkDoneProgressCreateParams +---@field token nio.lsp.types.ProgressToken The token to be used to report progress. + +--- Options for notifications/requests for user operations on files. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileOperationOptions +---@field didCreate? nio.lsp.types.FileOperationRegistrationOptions The server is interested in receiving didCreateFiles notifications. +---@field willCreate? nio.lsp.types.FileOperationRegistrationOptions The server is interested in receiving willCreateFiles requests. +---@field didRename? nio.lsp.types.FileOperationRegistrationOptions The server is interested in receiving didRenameFiles notifications. +---@field willRename? nio.lsp.types.FileOperationRegistrationOptions The server is interested in receiving willRenameFiles requests. +---@field didDelete? nio.lsp.types.FileOperationRegistrationOptions The server is interested in receiving didDeleteFiles file notifications. +---@field willDelete? nio.lsp.types.FileOperationRegistrationOptions The server is interested in receiving willDeleteFiles file requests. + +--- Represents programming constructs like functions or constructors in the context +--- of call hierarchy. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyItem +---@field name string The name of this item. +---@field kind nio.lsp.types.SymbolKind The kind of this item. +---@field tags? nio.lsp.types.SymbolTag[] Tags for this item. +---@field detail? string More detail for this item, e.g. the signature of a function. +---@field uri nio.lsp.types.DocumentUri The resource identifier of this item. +---@field range nio.lsp.types.Range The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. +---@field selectionRange nio.lsp.types.Range The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. Must be contained by the {@link CallHierarchyItem.range `range`}. +---@field data? nio.lsp.types.LSPAny A data entry field that is preserved between a call hierarchy prepare and incoming calls or outgoing calls requests. + +--- A pattern to describe in which file operation requests or notifications +--- the server is interested in receiving. +--- +--- @since 3.16.0 +---@class nio.lsp.types.FileOperationPattern +---@field glob string The glob pattern to match. Glob patterns can have the following syntax: - `*` to match one or more characters in a path segment - `?` to match on one character in a path segment - `**` to match any number of path segments, including none - `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +---@field matches? nio.lsp.types.FileOperationPatternKind Whether to match files or folders with this pattern. Matches both if undefined. +---@field options? nio.lsp.types.FileOperationPatternOptions Additional options used during matching. + +--- Call hierarchy options used during static or dynamic registration. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.CallHierarchyOptions,nio.lsp.types.StaticRegistrationOptions + +--- The parameters sent in a save text document notification +---@class nio.lsp.types.DidSaveTextDocumentParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The document that was saved. +---@field text? string Optional the content when saved. Depends on the includeText value when the save notification was requested. + +---@class nio.lsp.types.RegistrationParams +---@field registrations nio.lsp.types.Registration[] + +--- Represents an incoming call, e.g. a caller of a method or constructor. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyIncomingCall +---@field from nio.lsp.types.CallHierarchyItem The item that makes the call. +---@field fromRanges nio.lsp.types.Range[] The ranges at which the calls appear. This is relative to the caller denoted by {@link CallHierarchyIncomingCall.from `this.from`}. + +--- The parameter of a `callHierarchy/incomingCalls` request. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyIncomingCallsParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field item nio.lsp.types.CallHierarchyItem + +--- Represents a color range from a document. +---@class nio.lsp.types.ColorInformation +---@field range nio.lsp.types.Range The range in the document where this color appears. +---@field color nio.lsp.types.Color The actual color value for this color range. + +--- Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyOutgoingCall +---@field to nio.lsp.types.CallHierarchyItem The item that is called. +---@field fromRanges nio.lsp.types.Range[] The range at which this item is called. This is the range relative to the caller, e.g the item passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`} and not {@link CallHierarchyOutgoingCall.to `this.to`}. + +--- The parameter of a `callHierarchy/outgoingCalls` request. +--- +--- @since 3.16.0 +---@class nio.lsp.types.CallHierarchyOutgoingCallsParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field item nio.lsp.types.CallHierarchyItem + +--- Provider options for a {@link DocumentHighlightRequest}. +---@class nio.lsp.types.DocumentHighlightOptions : nio.lsp.types.WorkDoneProgressOptions + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokens +---@field resultId? string An optional result id. If provided and clients support delta updating the client will include the result id in the next semantic token request. A server can then instead of computing all semantic tokens again simply send a delta. +---@field data integer[] The actual tokens. + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensParams : nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams +---@field textDocument nio.lsp.types.TextDocumentIdentifier The text document. + +--- Provide inline value as text. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueText +---@field range nio.lsp.types.Range The document range for which the inline value applies. +---@field text string The text of the inline value. + +--- Registration options for a {@link CodeActionRequest}. +---@class nio.lsp.types.CodeActionRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.CodeActionOptions + +--- Parameters for a {@link DocumentHighlightRequest}. +---@class nio.lsp.types.DocumentHighlightParams : nio.lsp.types.TextDocumentPositionParams,nio.lsp.types.WorkDoneProgressParams,nio.lsp.types.PartialResultParams + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensRegistrationOptions : nio.lsp.types.TextDocumentRegistrationOptions,nio.lsp.types.SemanticTokensOptions,nio.lsp.types.StaticRegistrationOptions + +--- Provide inline value through a variable lookup. +--- If only a range is specified, the variable name will be extracted from the underlying document. +--- An optional variable name can be used to override the extracted name. +--- +--- @since 3.17.0 +---@class nio.lsp.types.InlineValueVariableLookup +---@field range nio.lsp.types.Range The document range for which the inline value applies. The range is used to extract the variable name from the underlying document. +---@field variableName? string If specified the name of the variable to look up. +---@field caseSensitiveLookup boolean How to perform the lookup. + +--- @since 3.16.0 +---@class nio.lsp.types.SemanticTokensDelta +---@field resultId? string +---@field edits nio.lsp.types.SemanticTokensEdit[] The semantic token edits to transform a previous result into a new result. diff --git a/lua/nio/lsp.lua b/lua/nio/lsp.lua new file mode 100644 index 0000000..dd3e3ed --- /dev/null +++ b/lua/nio/lsp.lua @@ -0,0 +1,112 @@ +local tasks = require("nio.tasks") +local control = require("nio.control") +local logger = require("nio.logger") + +local nio = {} + +---@toc_entry nio.lsp +---@class nio.lsp +nio.lsp = {} + +---@class nio.lsp.Client +---@field request nio.lsp.RequestClient Interface to all requests that can be sent by the client +---@field notify nio.lsp.NotifyClient Interface to all notifications that can be sent by the client +---@field server_capabilities nio.lsp.types.ServerCapabilities + +local async_request = tasks.wrap(function(client, method, params, bufnr, request_id_future, cb) + local success, req_id = client.request(method, params, cb, bufnr) + if not success then + if request_id_future then + request_id_future.set_error("Request failed") + end + error(("Failed to send request. Client %s has shut down"):format(client.id)) + end + if request_id_future then + request_id_future.set(req_id) + end +end, 6) + +--- Get active clients, optionally matching the given filters +--- Equivalent to |vim.lsp.get_clients| +---@param filters? nio.lsp.GetClientsFilters +---@return nio.lsp.Client[] +function nio.lsp.get_clients(filters) + local clients = {} + for _, client in pairs(vim.lsp.get_active_clients(filters)) do + clients[#clients + 1] = nio.lsp.client(client.id) + end + return clients +end + +---@class nio.lsp.GetClientsFilters +---@field id? integer +---@field name? string +---@field bufnr? integer +---@field method? string + +---Create an async client for the given client id +---@param client_id integer +---@return nio.lsp.Client +function nio.lsp.client(client_id) + local n = require("nio") + local internal_client = + assert(vim.lsp.get_client_by_id(client_id), ("Client not found with ID %s"):format(client_id)) + + ---@param name string + local convert_method = function(name) + return name:gsub("__", "$/"):gsub("_", "/") + end + + return { + server_capabilities = internal_client.server_capabilities, + notify = setmetatable({}, { + __index = function(_, method) + method = convert_method(method) + return function(params) + return internal_client.notify(method, params) + end + end, + }), + request = setmetatable({}, { + __index = function(_, method) + method = convert_method(method) + ---@param opts? nio.lsp.RequestOpts + return function(params, bufnr, opts) + -- No params for this request + if type(params) ~= "table" then + opts = bufnr + bufnr = params + end + opts = opts or {} + local err, result + + local start = vim.loop.now() + if opts.timeout then + local req_future = control.future() + err, result = n.first({ + function() + n.sleep(opts.timeout) + local req_id = req_future.wait() + n.run(function() + async_request(internal_client, "$/cancelRequest", { requestId = req_id }, bufnr) + end) + return { code = -1, message = "Request timed out" } + end, + function() + return async_request(internal_client, method, params, bufnr, req_future) + end, + }) + else + err, result = async_request(internal_client, method, params, bufnr) + end + local elapsed = vim.loop.now() - start + logger.trace("Request", method, "took", elapsed, "ms") + + return err, result + end + end, + }), + } +end + +return nio.lsp diff --git a/lua/nio/tasks.lua b/lua/nio/tasks.lua new file mode 100644 index 0000000..677429f --- /dev/null +++ b/lua/nio/tasks.lua @@ -0,0 +1,212 @@ +local nio = {} + +---@class nio.tasks +nio.tasks = {} + +---@type table +---@nodoc +local tasks = {} +---@type table +---@nodoc +local child_tasks = {} + +-- Coroutine.running() was changed between Lua 5.1 and 5.2: +-- - 5.1: Returns the running coroutine, or nil when called by the main thread. +-- - 5.2: Returns the running coroutine plus a boolean, true when the running coroutine is the main one. +-- For LuaJIT, 5.2 behaviour is enabled with LUAJIT_ENABLE_LUA52COMPAT + +---@nodoc +local function current_non_main_co() + local data = { coroutine.running() } + + if select("#", unpack(data)) == 2 then + local co, is_main = unpack(data) + if is_main then + return nil + end + return co + end + + return unpack(data) +end + +---@text +--- Tasks represent a top level running asynchronous function +--- Only one task is ever executing at any time. +---@class nio.tasks.Task +---@field parent? nio.tasks.Task Parent task +---@field cancel fun(): nil Cancels the task +---@field trace fun(): string Get the stack trace of the task +---@field wait async function Wait for the task to finish, returning any result + +---@class nio.tasks.TaskError +---@field message string +---@field traceback? string + +local format_error = function(message, traceback) + if not traceback then + return string.format("The coroutine failed with this message: %s", message) + end + return string.format( + "The coroutine failed with this message: %s\n%s", + type(message) == "string" and vim.startswith(traceback, message) and "" + or ("\n" .. tostring(message)), + traceback + ) +end + +---@return nio.tasks.Task +---@nodoc +function nio.tasks.run(func, cb) + local co = coroutine.create(func) + local cancelled = false + local task = { parent = nio.tasks.current_task() } + if task.parent then + child_tasks[task.parent] = child_tasks[task.parent] or {} + table.insert(child_tasks[task.parent], task) + end + local future = require("nio").control.future() + + function task.cancel() + if coroutine.status(co) == "dead" then + return + end + for _, child in pairs(child_tasks[task] or {}) do + child.cancel() + end + cancelled = true + end + + function task.trace() + return debug.traceback(co) + end + + function task.wait() + return future.wait() + end + + local function close_task(result, err) + tasks[co] = nil + if err then + future.set_error(err) + if cb then + cb(false, err) + elseif not cancelled then + error("Async task failed without callback: " .. err) + end + else + future.set(unpack(result)) + if cb then + cb(true, unpack(result)) + end + end + end + + tasks[co] = task + + local function step(...) + if cancelled then + close_task(nil, format_error("Task was cancelled")) + return + end + + local yielded = { coroutine.resume(co, ...) } + local success = yielded[1] + + if not success then + close_task(nil, format_error(yielded[2], debug.traceback(co))) + return + end + + if coroutine.status(co) == "dead" then + close_task({ unpack(yielded, 2, table.maxn(yielded)) }) + return + end + + local _, nargs, err_or_fn = unpack(yielded) + + if type(err_or_fn) ~= "function" then + error( + ("Async internal error: expected function, got %s\nContext: %s\n%s"):format( + type(err_or_fn), + vim.inspect(yielded), + debug.traceback(co) + ) + ) + end + + local args = { select(4, unpack(yielded)) } + + args[nargs] = step + + err_or_fn(unpack(args, 1, nargs)) + end + + step() + return task +end + +---@param func function +---@param argc? number +---@return function +function nio.tasks.create(func, argc) + vim.validate({ + func = { func, "function" }, + argc = { argc, "number", true }, + }) + argc = argc or 0 + return function(...) + if current_non_main_co() then + return func(...) + end + local args = { ... } + local callback + if #args > argc then + callback = table.remove(args) + end + return nio.tasks.run(function() + func(unpack(args)) + end, callback) + end +end + +---@package +---@nodoc +function nio.tasks.wrap(func, argc) + vim.validate({ func = { func, "function" }, argc = { argc, "number" } }) + local protected = function(...) + local args = { ... } + local cb = args[argc] + args[argc] = function(...) + cb(true, ...) + end + xpcall(func, function(err) + cb(false, err, debug.traceback()) + end, unpack(args, 1, argc)) + end + + return function(...) + if not current_non_main_co() then + return func(...) + end + + local ret = { coroutine.yield(argc, protected, ...) } + local success = ret[1] + if not success then + error(("Wrapped function failed: %s\n%s"):format(ret[2], ret[3])) + end + return unpack(ret, 2, table.maxn(ret)) + end +end + +--- Get the current running task +---@return nio.tasks.Task|nil +function nio.tasks.current_task() + local co = current_non_main_co() + if not co then + return nil + end + return tasks[co] +end + +return nio.tasks diff --git a/lua/nio/tests.lua b/lua/nio/tests.lua new file mode 100644 index 0000000..ea65b7c --- /dev/null +++ b/lua/nio/tests.lua @@ -0,0 +1,64 @@ +local tasks = require("nio.tasks") + +local nio = {} + +---@toc_entry nio.tests +---@text +--- Wrappers around plenary.nvim's test functions for writing async tests +--- ```lua +--- a.it("notifies listeners", function() +--- local event = nio.control.event() +--- local notified = 0 +--- for _ = 1, 10 do +--- nio.run(function() +--- event.wait() +--- notified = notified + 1 +--- end) +--- end +--- +--- event.set() +--- nio.sleep(10) +--- assert.equals(10, notified) +--- end) +---@class nio.tests +nio.tests = {} + +local with_timeout = function(func, timeout) + local success, err + return function() + local task = tasks.run(func, function(success_, err_) + success = success_ + if not success_ then + err = err_ + end + end) + + vim.wait(timeout or 2000, function() + return success ~= nil + end, 20, false) + + if success == nil then + error(string.format("Test task timed out\n%s", task.trace())) + elseif not success then + error(string.format("Test task failed with message:\n%s", err)) + end + end +end + +---@param name string +---@param async_func function +nio.tests.it = function(name, async_func) + it(name, with_timeout(async_func, tonumber(vim.env.PLENARY_TEST_TIMEOUT))) +end + +---@param async_func function +nio.tests.before_each = function(async_func) + before_each(with_timeout(async_func)) +end + +---@param async_func function +nio.tests.after_each = function(async_func) + after_each(with_timeout(async_func)) +end + +return nio.tests diff --git a/lua/nio/ui.lua b/lua/nio/ui.lua new file mode 100644 index 0000000..15feb58 --- /dev/null +++ b/lua/nio/ui.lua @@ -0,0 +1,50 @@ +local tasks = require("nio.tasks") + +local nio = {} + +---@toc_entry nio.ui +---@text +--- Async versions of vim.ui functions. +---@class nio.ui +nio.ui = {} + +--- Prompt the user for input. +--- See |vim.ui.input()| for details. +--- ```lua +--- local value = nio.ui.input({ prompt = "Enter something: " }) +--- print(("You entered: %s"):format(value)) +--- ``` +---@async +---@param args nio.ui.InputArgs +function nio.ui.input(args) end + +---@class nio.ui.InputArgs +---@field prompt string|nil Text of the prompt +---@field default string|nil Default reply to the input +---@field completion string|nil Specifies type of completion supported for input. Supported types are the same that can be supplied to a user-defined command using the "-complete=" argument. See |:command-completion| +---@field highlight function Function that will be used for highlighting user inputs. + +--- Prompts the user to pick from a list of items +--- See |vim.ui.select()| for details. +--- ``` +--- local value = nio.ui.select({ "foo", "bar", "baz" }, { prompt = "Select something: " }) +--- print(("You entered: %s"):format(value)) +--- ``` +---@async +---@param items any[] +---@param args nio.ui.SelectArgs +function nio.ui.select(items, args) end + +---@class nio.ui.SelectArgs +---@field prompt string|nil Text of the prompt. Defaults to `Select one of:` +---@field format_item function|nil Function to format an individual item from `items`. Defaults to `tostring`. +---@field kind string|nil Arbitrary hint string indicating the item shape. Plugins reimplementing `vim.ui.select` may wish to use this to infer the structure or semantics of `items`, or the context in which select() was called. + +nio.ui = { + ---@nodoc + select = tasks.wrap(vim.ui.select, 3), + ---@nodoc + input = tasks.wrap(vim.ui.input, 2), +} + +return nio.ui diff --git a/lua/nio/uv.lua b/lua/nio/uv.lua new file mode 100644 index 0000000..aca290d --- /dev/null +++ b/lua/nio/uv.lua @@ -0,0 +1,169 @@ +local tasks = require("nio.tasks") + +local nio = {} + +---@toc_entry nio.uv +---@text +--- Provides asynchronous versions of vim.loop functions. +--- See corresponding function documentation for parameter and return +--- information. +--- ```lua +--- local file_path = "README.md" +--- +--- local open_err, file_fd = nio.uv.fs_open(file_path, "r", 438) +--- assert(not open_err, open_err) +--- +--- local stat_err, stat = nio.uv.fs_fstat(file_fd) +--- assert(not stat_err, stat_err) +--- +--- local read_err, data = nio.uv.fs_read(file_fd, stat.size, 0) +--- assert(not read_err, read_err) +--- +--- local close_err = nio.uv.fs_close(file_fd) +--- assert(not close_err, close_err) +--- +--- print(data) +--- ``` +--- +---@class nio.uv +---@field close async fun(handle: nio.uv.Handle) +---@field fs_open async fun(path: any, flags: any, mode: any): (string|nil,integer|nil) +---@field fs_read async fun(fd: integer, size: integer, offset?: integer): (string|nil,string|nil) +---@field fs_close async fun(fd: integer): (string|nil,boolean|nil) +---@field fs_unlink async fun(path: string): (string|nil,boolean|nil) +---@field fs_write async fun(fd: any, data: any, offset?: any): (string|nil,integer|nil) +---@field fs_mkdir async fun(path: string, mode: integer): (string|nil,boolean|nil) +---@field fs_mkdtemp async fun(template: string): (string|nil,string|nil) +---@field fs_rmdir async fun(path: string): (string|nil,boolean|nil) +---@field fs_stat async fun(path: string): (string|nil,nio.uv.Stat|nil) +---@field fs_fstat async fun(fd: integer): (string|nil,nio.uv.Stat|nil) +---@field fs_lstat async fun(path: string): (string|nil,nio.uv.Stat|nil) +---@field fs_statfs async fun(path: string): (string|nil,nio.uv.StatFs|nil) +---@field fs_rename async fun(old_path: string, new_path: string): (string|nil,boolean|nil) +---@field fs_fsync async fun(fd: integer): (string|nil,boolean|nil) +---@field fs_fdatasync async fun(fd: integer): (string|nil,boolean|nil) +---@field fs_ftruncate async fun(fd: integer, offset: integer): (string|nil,boolean|nil) +---@field fs_sendfile async fun(out_fd: integer, in_fd: integer, in_offset: integer, length: integer): (string|nil,integer|nil) +---@field fs_access async fun(path: string, mode: integer): (string|nil,boolean|nil) +---@field fs_chmod async fun(path: string, mode: integer): (string|nil,boolean|nil) +---@field fs_fchmod async fun(fd: integer, mode: integer): (string|nil,boolean|nil) +---@field fs_utime async fun(path: string, atime: number, mtime: number): (string|nil,boolean|nil) +---@field fs_futime async fun(fd: integer, atime: number, mtime: number): (string|nil,boolean|nil) +---@field fs_link async fun(path: string, new_path: string): (string|nil,boolean|nil) +---@field fs_symlink async fun(path: string, new_path: string, flags?: integer): (string|nil,boolean|nil) +---@field fs_readlink async fun(path: string): (string|nil,string|nil) +---@field fs_realpath async fun(path: string): (string|nil,string|nil) +---@field fs_chown async fun(path: string, uid: integer, gid: integer): (string|nil,boolean|nil) +---@field fs_fchown async fun(fd: integer, uid: integer, gid: integer): (string|nil,boolean|nil) +---@field fs_lchown async fun(path: string, uid: integer, gid: integer): (string|nil,boolean|nil) +---@field fs_copyfile async fun(path: any, new_path: any, flags?: any): (string|nil,boolean|nil) +---@field fs_opendir async fun(path: string, entries?: integer): (string|nil,nio.uv.Dir|nil) +---@field fs_readdir async fun(dir: nio.uv.Dir): (string|nil,nio.uv.DirEntry[]|nil) +---@field fs_closedir async fun(dir: nio.uv.Dir): (string|nil,boolean|nil) +---@field fs_scandir async fun(path: string): (string|nil,nio.uv.DirEntry[]|nil) +---@field shutdown async fun(stream: nio.uv.Stream): string|nil +---@field listen async fun(stream: nio.uv.Stream, backlog: integer): string|nil +---@field write async fun(stream: nio.uv.Stream, data: string|string[]): string|nil +---@field write2 async fun(stream: nio.uv.Stream, data: string|string[], send_handle: nio.uv.Stream): string|nil +nio.uv = {} + +---@class nio.uv.Handle + +---@class nio.uv.Stream : nio.uv.Handle + +---@class nio.uv.Stat +---@field dev integer +---@field mode integer +---@field nlink integer +---@field uid integer +---@field gid integer +---@field rdev integer +---@field ino integer +---@field size integer +---@field blksize integer +---@field blocks integer +---@field flags integer +---@field gen integer +---@field atime nio.uv.StatTime +---@field mtime nio.uv.StatTime +---@field ctime nio.uv.StatTime +---@field birthtime nio.uv.StatTime +---@field type string + +---@class nio.uv.StatTime +---@field sec integer +---@field nsec integer + +---@class nio.uv.StatFs +---@field type integer +---@field bsize integer +---@field blocks integer +---@field bfree integer +---@field bavail integer +---@field files integer +---@field ffree integer + +---@class nio.uv.Dir + +---@class nio.uv.DirEntry + +---@nodoc +local function add(name, argc) + local success, ret = pcall(tasks.wrap, vim.loop[name], argc) + + if not success then + error("Failed to add function with name " .. name) + end + + nio.uv[name] = ret +end + +add("close", 4) -- close a handle +-- filesystem operations +add("fs_open", 4) +add("fs_read", 4) +add("fs_close", 2) +add("fs_unlink", 2) +add("fs_write", 4) +add("fs_mkdir", 3) +add("fs_mkdtemp", 2) +-- 'fs_mkstemp', +add("fs_rmdir", 2) +add("fs_scandir", 2) +add("fs_stat", 2) +add("fs_fstat", 2) +add("fs_lstat", 2) +add("fs_rename", 3) +add("fs_fsync", 2) +add("fs_fdatasync", 2) +add("fs_ftruncate", 3) +add("fs_sendfile", 5) +add("fs_access", 3) +add("fs_chmod", 3) +add("fs_fchmod", 3) +add("fs_utime", 4) +add("fs_futime", 4) +-- 'fs_lutime', +add("fs_link", 3) +add("fs_symlink", 4) +add("fs_readlink", 2) +add("fs_realpath", 2) +add("fs_chown", 4) +add("fs_fchown", 4) +-- 'fs_lchown', +add("fs_copyfile", 4) +nio.uv.fs_opendir = tasks.wrap(function(path, entries, cb) + vim.loop.fs_opendir(path, cb, entries) +end, 3) +add("fs_readdir", 2) +add("fs_closedir", 2) +add("fs_statfs", 2) +-- stream +add("shutdown", 2) +add("listen", 3) +-- add('read_start', 2) -- do not do this one, the callback is made multiple times +add("write", 3) +add("write2", 4) +add("shutdown", 2) + +return nio.uv diff --git a/scripts/docgen b/scripts/docgen new file mode 100755 index 0000000..9b45520 --- /dev/null +++ b/scripts/docgen @@ -0,0 +1,3 @@ +#!/bin/bash + +nvim --headless -c "luafile ./scripts/gendocs.lua" -c 'qa' diff --git a/scripts/gendocs.lua b/scripts/gendocs.lua new file mode 100644 index 0000000..64e1d5d --- /dev/null +++ b/scripts/gendocs.lua @@ -0,0 +1,854 @@ +-- TODO: A lot of this is private code from minidoc, which could be removed if made public + +local minidoc = require("mini.doc") + +local H = {} +--stylua: ignore start +H.pattern_sets = { + -- Patterns for working with afterlines. At the moment deliberately crafted + -- to work only on first line without indent. + + -- Determine if line is a function definition. Captures function name and + -- arguments. For reference see '2.5.9 – Function Definitions' in Lua manual. + afterline_fundef = { + '^function%s+(%S-)(%b())', -- Regular definition + '^local%s+function%s+(%S-)(%b())', -- Local definition + '^(%S+)%s*=%s*function(%b())', -- Regular assignment + '^(%S+)%s*=%s*nio.create%(function(%b())', -- Regular assignment + '^local%s+(%S+)%s*=%s*function(%b())', -- Local assignment + }, + -- Determine if line is a general assignment + afterline_assign = { + '^(%S-)%s*=', -- General assignment + '^local%s+(%S-)%s*=', -- Local assignment + }, + -- Patterns to work with type descriptions + -- (see https://github.com/sumneko/lua-language-server/wiki/EmmyLua-Annotations#types-and-type) + types = { + 'table%b<>', + 'fun%b(): %S+', 'fun%b()', 'async fun%b(): %S+', 'async fun%b()', + 'nil', 'any', 'boolean', 'string', 'number', 'integer', 'function', 'table', 'thread', 'userdata', 'lightuserdata', + '%.%.%.', + "%S+", + + }, +} + + +H.apply_config = function(config) + MiniDoc.config = config +end + +H.is_disabled = function() + return vim.g.minidoc_disable == true or vim.b.minidoc_disable == true +end + +H.get_config = function(config) + return vim.tbl_deep_extend("force", MiniDoc.config, vim.b.minidoc_config or {}, config or {}) +end + +-- Work with project specific script ========================================== +H.execute_project_script = function(input, output, config) + -- Don't process script if there are more than one active `generate` calls + if H.generate_is_active then + return + end + + -- Don't process script if at least one argument is not default + if not (input == nil and output == nil and config == nil) then + return + end + + -- Store information + local global_config_cache = vim.deepcopy(MiniDoc.config) + local local_config_cache = vim.b.minidoc_config + + -- Pass information to a possible `generate()` call inside script + H.generate_is_active = true + H.generate_recent_output = nil + + -- Execute script + local success = pcall(vim.cmd, "luafile " .. H.get_config(config).script_path) + + -- Restore information + MiniDoc.config = global_config_cache + vim.b.minidoc_config = local_config_cache + H.generate_is_active = nil + + return success +end + +-- Default documentation targets ---------------------------------------------- +H.default_input = function() + -- Search in current and recursively in other directories for files with + -- 'lua' extension + local res = {} + for _, dir_glob in ipairs({ ".", "lua/**", "after/**", "colors/**" }) do + local files = vim.fn.globpath(dir_glob, "*.lua", false, true) + + -- Use full paths + files = vim.tbl_map(function(x) + return vim.fn.fnamemodify(x, ":p") + end, files) + + -- Put 'init.lua' first among files from same directory + table.sort(files, function(a, b) + if vim.fn.fnamemodify(a, ":h") == vim.fn.fnamemodify(b, ":h") then + if vim.fn.fnamemodify(a, ":t") == "init.lua" then + return true + end + if vim.fn.fnamemodify(b, ":t") == "init.lua" then + return false + end + end + + return a < b + end) + table.insert(res, files) + end + + return vim.tbl_flatten(res) +end + +-- Parsing -------------------------------------------------------------------- +H.lines_to_block_arr = function(lines, config) + local matched_prev, matched_cur + + local res = {} + local block_raw = { annotation = {}, section_id = {}, afterlines = {}, line_begin = 1 } + + for i, l in ipairs(lines) do + local from, to, section_id = config.annotation_extractor(l) + matched_prev, matched_cur = matched_cur, from ~= nil + + if matched_cur then + if not matched_prev then + -- Finish current block + block_raw.line_end = i - 1 + table.insert(res, H.raw_block_to_block(block_raw, config)) + + -- Start new block + block_raw = { annotation = {}, section_id = {}, afterlines = {}, line_begin = i } + end + + -- Add annotation line without matched annotation pattern + table.insert(block_raw.annotation, ("%s%s"):format(l:sub(0, from - 1), l:sub(to + 1))) + + -- Add section id (it is empty string in case of no section id capture) + table.insert(block_raw.section_id, section_id or "") + else + -- Add afterline + table.insert(block_raw.afterlines, l) + end + end + block_raw.line_end = #lines + table.insert(res, H.raw_block_to_block(block_raw, config)) + + return res +end + +-- Raw block structure is an intermediate step added for convenience. It is +-- a table with the following keys: +-- - `annotation` - lines (after removing matched annotation pattern) that were +-- parsed as annotation. +-- - `section_id` - array with length equal to `annotation` length with strings +-- captured as section id. Empty string of no section id was captured. +-- - Everything else is used as block info (like `afterlines`, etc.). +H.raw_block_to_block = function(block_raw, config) + if #block_raw.annotation == 0 and #block_raw.afterlines == 0 then + return nil + end + + local block = H.new_struct("block", { + afterlines = block_raw.afterlines, + line_begin = block_raw.line_begin, + line_end = block_raw.line_end, + }) + local block_begin = block.info.line_begin + + -- Parse raw block annotation lines from top to bottom. New section starts + -- when section id is detected in that line. + local section_cur = H.new_struct( + "section", + { id = config.default_section_id, line_begin = block_begin } + ) + + for i, annotation_line in ipairs(block_raw.annotation) do + local id = block_raw.section_id[i] + if id ~= "" then + -- Finish current section + if #section_cur > 0 then + section_cur.info.line_end = block_begin + i - 2 + block:insert(section_cur) + end + + -- Start new section + section_cur = H.new_struct("section", { id = id, line_begin = block_begin + i - 1 }) + end + + section_cur:insert(annotation_line) + end + + if #section_cur > 0 then + section_cur.info.line_end = block_begin + #block_raw.annotation - 1 + block:insert(section_cur) + end + + return block +end + +-- Hooks ---------------------------------------------------------------------- +H.apply_structure_hooks = function(doc, hooks) + for _, file in ipairs(doc) do + for _, block in ipairs(file) do + hooks.block_pre(block) + + for _, section in ipairs(block) do + hooks.section_pre(section) + + local hook = hooks.sections[section.info.id] + if hook ~= nil then + hook(section) + end + + hooks.section_post(section) + end + + hooks.block_post(block) + end + + hooks.file(file) + end + + hooks.doc(doc) +end + +H.alias_register = function(s) + if #s == 0 then + return + end + + -- Remove first word (with bits of surrounding whitespace) while capturing it + local alias_name + s[1] = s[1]:gsub("%s*(%S+) ?", function(x) + alias_name = x + return "" + end, 1) + if alias_name == nil then + return + end + + MiniDoc.current.aliases = MiniDoc.current.aliases or {} + MiniDoc.current.aliases[alias_name] = table.concat(s, "\n") +end + +H.alias_replace = function(s) + if MiniDoc.current.aliases == nil then + return + end + + for i, _ in ipairs(s) do + for alias_name, alias_desc in pairs(MiniDoc.current.aliases) do + -- Escape special characters. This is done here and not while registering + -- alias to allow user to refer to aliases by its original name. + -- Store escaped words in separate variables because `vim.pesc()` returns + -- two values which might conflict if outputs are used as arguments. + local name_escaped = vim.pesc(alias_name) + local desc_escaped = vim.pesc(alias_desc) + s[i] = s[i]:gsub(name_escaped, desc_escaped) + end + end +end + +H.toc_register = function(s) + MiniDoc.current.toc = MiniDoc.current.toc or {} + table.insert(MiniDoc.current.toc, s) +end + +H.toc_insert = function(s) + if MiniDoc.current.toc == nil then + return + end + + -- Render table of contents + local toc_lines = {} + for _, toc_entry in ipairs(MiniDoc.current.toc) do + local _, tag_section = toc_entry.parent:has_descendant(function(x) + return type(x) == "table" and x.type == "section" and x.info.id == "@tag" + end) + tag_section = tag_section or {} + + local lines = {} + for i = 1, math.max(#toc_entry, #tag_section) do + local left = toc_entry[i] or "" + -- Use tag refernce instead of tag enclosure + local right = string.match(tag_section[i], "%*.*%*"):gsub("%*", "|") + -- local right = vim.trim((tag_section[i] or ""):gsub("%*", "|")) + -- Add visual line only at first entry (while not adding trailing space) + local filler = i == 1 and "." or (right == "" and "" or " ") + -- Make padding of 2 spaces at both left and right + local n_filler = math.max(74 - H.visual_text_width(left) - H.visual_text_width(right), 3) + table.insert(lines, (" %s%s%s"):format(left, filler:rep(n_filler), right)) + end + + table.insert(toc_lines, lines) + + -- Don't show `toc_entry` lines in output + toc_entry:clear_lines() + end + + for _, l in ipairs(vim.tbl_flatten(toc_lines)) do + s:insert(l) + end +end + +H.add_section_heading = function(s, heading) + if #s == 0 or s.type ~= "section" then + return + end + + -- Add heading + s:insert(1, ("%s~"):format(heading)) +end + +H.enclose_var_name = function(s) + if #s == 0 or s.type ~= "section" then + return + end + + s[1] = s[1]:gsub("(%S+)", "{%1}", 1) +end + +---@param init number Start of searching for first "type-like" string. It is +--- needed to not detect type early. Like in `@param a_function function`. +---@private +H.enclose_type = function(s, enclosure, init) + if #s == 0 or s.type ~= "section" then + return + end + enclosure = enclosure or "`%(%1%)`" + init = init or 1 + + local cur_type = H.match_first_pattern(s[1], H.pattern_sets["types"], init) + if #cur_type == 0 then + return + end + + -- Add `%S*` to front and back of found pattern to support their combination + -- with `|`. Also allows using `[]` and `?` prefixes. + local type_pattern = ("(%%S*%s%%S*)"):format(vim.pesc(cur_type[1])) + + -- Avoid replacing possible match before `init` + local l_start = s[1]:sub(1, init - 1) + local l_end = s[1]:sub(init):gsub(type_pattern, enclosure, 1) + s[1] = ("%s%s"):format(l_start, l_end) +end + +-- Infer data from afterlines ------------------------------------------------- +H.infer_header = function(b) + local has_signature = b:has_descendant(function(x) + return type(x) == "table" and x.type == "section" and x.info.id == "@signature" + end) + local has_tag = b:has_descendant(function(x) + return type(x) == "table" and x.type == "section" and x.info.id == "@tag" + end) + + if has_signature and has_tag then + return + end + + local l_all = table.concat(b.info.afterlines, " ") + local tag, signature + + -- Try function definition + local fun_capture = H.match_first_pattern(l_all, H.pattern_sets["afterline_fundef"]) + if #fun_capture > 0 then + tag = tag or ("%s()"):format(fun_capture[1]) + signature = signature or ("%s%s"):format(fun_capture[1], fun_capture[2]) + end + + -- Try general assignment + local assign_capture = H.match_first_pattern(l_all, H.pattern_sets["afterline_assign"]) + if #assign_capture > 0 then + tag = tag or assign_capture[1] + signature = signature or assign_capture[1] + end + + if tag ~= nil then + -- First insert signature (so that it will appear after tag section) + if not has_signature then + b:insert(1, H.as_struct({ signature }, "section", { id = "@signature" })) + end + + -- Insert tag + if not has_tag then + b:insert(1, H.as_struct({ tag }, "section", { id = "@tag" })) + end + end +end + +function H.is_module(name) + if string.find(name, "%(") then + return false + end + if string.find(name, "[A-Z]") then + return false + end + return true +end + +H.format_signature = function(line) + -- Try capture function signature + local name, args = line:match("(%S-)(%b())") + + + -- Otherwise pick first word + name = name or line:match("(%S+)") + if not args and H.is_module(name) then + return "" + end + local name_elems = vim.split(name, ".", { plain = true }) + name = name_elems[#name_elems] + + if not name then + return "" + end + + -- Tidy arguments + if args and args ~= "()" then + local arg_parts = vim.split(args:sub(2, -2), ",") + local arg_list = {} + for _, a in ipairs(arg_parts) do + -- Enclose argument in `{}` while controlling whitespace + table.insert(arg_list, ("{%s}"):format(vim.trim(a))) + end + args = ("(%s)"):format(table.concat(arg_list, ", ")) + end + + return ("`%s`%s"):format(name, args or "") +end + +-- Work with structures ------------------------------------------------------- +-- Constructor +H.new_struct = function(struct_type, info) + local output = { + info = info or {}, + type = struct_type, + } + + output.insert = function(self, index, child) + -- Allow both `x:insert(child)` and `x:insert(1, child)` + if child == nil then + child, index = index, #self + 1 + end + + if type(child) == "table" then + child.parent = self + child.parent_index = index + end + + table.insert(self, index, child) + + H.sync_parent_index(self) + end + + output.remove = function(self, index) + index = index or #self + table.remove(self, index) + + H.sync_parent_index(self) + end + + output.has_descendant = function(self, predicate) + local bool_res, descendant = false, nil + H.apply_recursively(function(x) + if not bool_res and predicate(x) then + bool_res = true + descendant = x + end + end, self) + return bool_res, descendant + end + + output.has_lines = function(self) + return self:has_descendant(function(x) + return type(x) == "string" + end) + end + + output.clear_lines = function(self) + for i, x in ipairs(self) do + if type(x) == "string" then + self[i] = nil + else + x:clear_lines() + end + end + end + + return output +end + +H.sync_parent_index = function(x) + for i, _ in ipairs(x) do + if type(x[i]) == "table" then + x[i].parent_index = i + end + end + return x +end + +-- Converter (this ensures that children have proper parent-related data) +H.as_struct = function(array, struct_type, info) + -- Make default info `info` for cases when structure is created manually + local default_info = ({ + section = { id = "@text", line_begin = -1, line_end = -1 }, + block = { afterlines = {}, line_begin = -1, line_end = -1 }, + file = { path = "" }, + doc = { input = {}, output = "", config = H.get_config() }, + })[struct_type] + info = vim.tbl_deep_extend("force", default_info, info or {}) + + local res = H.new_struct(struct_type, info) + for _, x in ipairs(array) do + res:insert(x) + end + return res +end + +-- Work with text ------------------------------------------------------------- +H.ensure_indent = function(text, n_indent_target) + local lines = vim.split(text, "\n") + local n_indent, n_indent_cur = math.huge, math.huge + + -- Find number of characters in indent + for _, l in ipairs(lines) do + -- Update lines indent: minimum of all indents except empty lines + if n_indent > 0 then + _, n_indent_cur = l:find("^%s*") + -- Condition "current n-indent equals line length" detects empty line + if (n_indent_cur < n_indent) and (n_indent_cur < l:len()) then + n_indent = n_indent_cur + end + end + end + + -- Ensure indent + local indent = string.rep(" ", n_indent_target) + for i, l in ipairs(lines) do + if l ~= "" then + lines[i] = indent .. l:sub(n_indent + 1) + end + end + + return table.concat(lines, "\n") +end + +H.align_text = function(text, width, direction) + if type(text) ~= "string" then + return + end + text = vim.trim(text) + width = width or 78 + direction = direction or "left" + + -- Don't do anything if aligning left or line is a whitespace + if direction == "left" or text:find("^%s*$") then + return text + end + + local n_left = math.max(0, 78 - H.visual_text_width(text)) + if direction == "center" then + n_left = math.floor(0.5 * n_left) + end + + return (" "):rep(n_left) .. text +end + +H.visual_text_width = function(text) + -- Ignore concealed characters (usually "invisible" in 'help' filetype) + local _, n_concealed_chars = text:gsub("([*|`])", "%1") + return vim.fn.strdisplaywidth(text) - n_concealed_chars +end + +--- Return earliest match among many patterns +--- +--- Logic here is to test among several patterns. If several got a match, +--- return one with earliest match. +--- +---@private +H.match_first_pattern = function(text, pattern_set, init) + local start_tbl = vim.tbl_map(function(pattern) + return text:find(pattern, init) or math.huge + end, pattern_set) + + local min_start, min_id = math.huge, nil + for id, st in ipairs(start_tbl) do + if st < min_start then + min_start, min_id = st, id + end + end + + if min_id == nil then + return {} + end + return { text:match(pattern_set[min_id], init) } +end + +-- Utilities ------------------------------------------------------------------ +H.apply_recursively = function(f, x, used) + used = used or {} + if used[x] then + return + end + f(x) + used[x] = true + + if type(x) == "table" then + for _, t in ipairs(x) do + H.apply_recursively(f, t, used) + end + end +end + +H.collect_strings = function(x) + local res = {} + H.apply_recursively(function(y) + if type(y) == "string" then + -- Allow `\n` in strings + table.insert(res, vim.split(y, "\n")) + end + end, x) + -- Flatten to only have strings and not table of strings (from `vim.split`) + return vim.tbl_flatten(res) +end + +H.file_read = function(path) + local file = assert(io.open(path)) + local contents = file:read("*all") + file:close() + + return vim.split(contents, "\n") +end + +H.file_write = function(path, lines) + -- Ensure target directory exists + local dir = vim.fn.fnamemodify(path, ":h") + vim.fn.mkdir(dir, "p") + + -- Write to file + vim.fn.writefile(lines, path, "b") +end + +H.full_path = function(path) + return vim.fn.resolve(vim.fn.fnamemodify(path, ":p")) +end + +H.message = function(msg) + vim.cmd("echomsg " .. vim.inspect("(mini.doc) " .. msg)) +end + +local function wrap(str, limit, indent, indent1) + indent = indent or "" + indent1 = indent1 or indent + limit = limit or 79 + local here = 1 - #indent1 + local wrapped = indent1 + .. str:gsub("(%s+)()(%S+)()", function(sp, st, word, fi) + local delta = 0 + word:gsub("@([@%a])", function(c) + if c == "@" then + delta = delta + 1 + elseif c == "x" then + delta = delta + 5 + else + delta = delta + 2 + end + end) + here = here + delta + if fi - here > limit then + here = st - #indent + delta + return "\n" .. indent .. word + end + end) + + return vim.split(wrapped, "\n") +end + + +local function create_config(module, header) + return { + hooks = vim.tbl_extend("force", minidoc.default_hooks, { + block_pre = function(b) + -- Infer metadata based on afterlines + if b:has_lines() and #b.info.afterlines > 0 then H.infer_header(b) end + end, + section_post = function(section) + for i, line in ipairs(section) do + if type(line) == "string" then + if string.find(line, "^```") then + string.gsub(line, "```(.*)", function(lang) + section[i] = lang == "" and "<" or (">%s"):format(lang) + end) + end + end + end + end, + block_post = function(b) + if not b:has_lines() then return end + + local found_param, found_field = false, false + local n_tag_sections = 0 + H.apply_recursively(function(x) + if not (type(x) == 'table' and x.type == 'section') then return end + + -- Add headings before first occurence of a section which type usually + -- appear several times + if not found_param and x.info.id == '@param' then + H.add_section_heading(x, 'Parameters') + found_param = true + end + if not found_field and x.info.id == '@field' then + H.add_section_heading(x, 'Fields') + found_field = true + end + + if x.info.id == '@tag' then + local text = x[1] + local tag = string.match(text, "%*.*%*") + local prefix = (string.sub(tag, 2, #tag - 1)) + if not H.is_module(prefix) then + prefix = "" + end + local n_filler = math.max(78 - H.visual_text_width(prefix) - H.visual_text_width(tag), 3) + local line = ("%s%s%s"):format(prefix, (" "):rep(n_filler), tag) + x:remove(1) + x:insert(1, line) + x.parent:remove(x.parent_index) + n_tag_sections = n_tag_sections + 1 + x.parent:insert(n_tag_sections, x) + end + end, b) + + -- b:insert(1, H.as_struct({ string.rep('=', 78) }, 'section')) + b:insert(H.as_struct({ '' }, 'section')) + end, + doc = function(d) + -- Render table of contents + H.apply_recursively(function(x) + if not (type(x) == 'table' and x.type == 'section' and x.info.id == '@toc') then return end + H.toc_insert(x) + end, d) + + -- Insert modeline + d:insert( + H.as_struct( + { H.as_struct({ H.as_struct({ ' vim:tw=78:ts=8:noet:ft=help:norl:' }, 'section') }, 'block') }, + 'file' + ) + ) + end, + sections = { + ['@generic'] = function(s) + s:remove(1) + end, + ['@field'] = function(s) + -- H.mark_optional(s) + if string.find(s[1], "^private ") then + s:remove(1) + return + end + H.enclose_var_name(s) + H.enclose_type(s, '`%(%1%)`', s[1]:find('%s')) + local wrapped = wrap(s[1], 78, "") + s:remove(1) + for i, line in ipairs(wrapped) do + s:insert(i, line) + end + end, + ['@alias'] = function(s) + local name = s[1]:match('%s*(%S*)') + local alias = s[1]:match('%s(.*)$') + s[1] = ("`%s` → `%s`"):format(name, alias) + H.add_section_heading(s, 'Alias') + s:insert(1, H.as_struct({ ("*%s*"):format(name) }, "section", { id = "@tag" })) + end, + ['@param'] = function(s) + H.enclose_var_name(s) + H.enclose_type(s, '`%(%1%)`', s[1]:find('%s')) + local wrapped = wrap(s[1], 78, "") + s:remove(1) + for i, line in ipairs(wrapped) do + s:insert(i, line) + end + end, + ['@return'] = function(s) + H.enclose_type(s, '`%(%1%)`', 1) + H.add_section_heading(s, 'Return') + end, + ['@nodoc'] = function(s) s.parent:clear_lines() end, + ['@class'] = function(s) + H.enclose_var_name(s) + -- Add heading + local line = s[1] + s:remove(1) + local class_name = string.match(line, "%{(.*)%}") + local inherits = string.match(line, ": (.*)") + if inherits then + s:insert(1, ("Inherits: `%s`"):format(inherits)) + s:insert(2, "") + end + s:insert(1, H.as_struct({ ("*%s*"):format(class_name) }, "section", { id = "@tag" })) + end, + ['@signature'] = function(s) + s[1] = H.format_signature(s[1]) + if s[1] ~= "" then + table.insert(s, "") + end + end, + }, + file = function(f) + if not f:has_lines() then + return + end + + if f.info.path ~= "./lua/" .. module .. "/init.lua" then + f:insert(1, H.as_struct({ H.as_struct({ string.rep("=", 78) }, "section") }, "block")) + f:insert(H.as_struct({ H.as_struct({ "" }, "section") }, "block")) + else + f:insert( + 1, + H.as_struct( + { + H.as_struct( + { header }, + "section" + ), + }, + "block" + ) + ) + f:insert(2, H.as_struct({ H.as_struct({ "" }, "section") }, "block")) + f:insert(3, H.as_struct({ H.as_struct({ string.rep("=", 78) }, "section") }, "block")) + f:insert(H.as_struct({ H.as_struct({ "" }, "section") }, "block")) + end + end, + }), + } +end + +minidoc.setup({}) +minidoc.generate( + { + "./lua/nio/init.lua", + "./lua/nio/control.lua", + "./lua/nio/lsp.lua", + "./lua/nio/uv.lua", + "./lua/nio/ui.lua", + "./lua/nio/tests.lua", + + }, + "doc/nio.txt", + create_config("nio", "*nvim-nio.txt* A library for asynchronous IO in Neovim") + +) diff --git a/scripts/generate_lsp_types.lua b/scripts/generate_lsp_types.lua new file mode 100644 index 0000000..303225d --- /dev/null +++ b/scripts/generate_lsp_types.lua @@ -0,0 +1,535 @@ +---@class Model +---@field requests Request[] +---@field notifications Notification[] +---@field enumerations Enumeration +---@field typeAliases TypeAlias[] +---@field structures Structure[] + +---@alias BaseTypes "URI" | "DocumentUri" | "integer" | "uinteger" | "decimal" | "RegExp" | "string" | "boolean" | "null" + +---@class BooleanLiteralType +---@field kind "boolean" +---@field value boolean + +---@class EnumerationEntry +---@field documentation? string An optional documentation. +---@field name string The name of the enum item. +---@field proposed? boolean Whether this is a proposed enumeration entry. If omitted, the enumeration entry is final. +---@field since? string Since when (release number) this enumeration entry is available. Is undefined if not known. +---@field value string | float The value. + +---@alias Name "string" | "integer" | "uinteger" + +---@class EnumerationType +---@field kind "enumeration" +---@field name Name + +---@class IntegerLiteralType +---@field kind "integer" Represents an integer literal type (e.g. `kind: 1`). +---@field value float + +---@alias Name1 "URI" | "DocumentUri" | "string" | "integer" + +---@class MapKeyTypeItem +---@field kind TypeKind +---@field name Name1 + +---@alias MessageDirection "clientToServer" | "serverToClient" | "both" + +---@class MetaData +---@field version string The protocol version. + +---@class ReferenceType +---@field kind "reference" +---@field name string + +---@class StringLiteralType +---@field kind "stringLiteral" +---@field value string + +---@alias TypeKind "base" | "reference" | "array" | "map" | "and" | "or" | "tuple" | "literal" | "stringLiteral" | "integerLiteral" | "booleanLiteral" + +---@class BaseType +---@field kind "base" +---@field name BaseTypes + +---@class Enumeration +---@field documentation? string An optional documentation. +---@field name string The name of the enumeration. +---@field proposed? boolean Whether this is a proposed enumeration. If omitted, the enumeration is final. +---@field since? string Since when (release number) this enumeration is available. Is undefined if not known. +---@field supportsCustomValues? boolean Whether the enumeration supports custom values (e.g. values which are not part of the set defined in `values`). If omitted no custom values are supported. +---@field type EnumerationType The type of the elements. +---@field values EnumerationEntry[] The enum values. + +---- Represents a type that can be used as a key in a map type. If a reference type is used then the type must either resolve to a `string` or `integer` type. (e.g. `type ChangeAnnotationIdentifier === string`). +---@alias MapKeyType MapKeyTypeItem | ReferenceType + +---@class AndType +---@field items Type[] +---@field kind "and" + +---@class ArrayType +---@field element Type +---@field kind "array" + +---@class MapType +---@field key MapKeyType +---@field kind "map" +---@field value Type + +---@class MetaModel +---@field enumerations Enumeration[] The enumerations. +---@field metaData MetaData Additional meta data. +---@field notifications Notification[] The notifications. +---@field requests Request[] The requests. +---@field structures Structure[] The structures. +---@field typeAliases TypeAlias[] The type aliases. + +---@class Notification +---@field documentation? string An optional documentation; +---@field messageDirection MessageDirection The direction in which this notification is sent in the protocol. +---@field method string The request's method name. +---@field params? Type | Type[] The parameter type(s) if any. +---@field proposed? boolean Whether this is a proposed notification. If omitted the notification is final. +---@field registrationMethod? string Optional a dynamic registration method if it different from the request's method. +---@field registrationOptions? Type Optional registration options if the notification supports dynamic registration. +---@field since? string Since when (release number) this notification is available. Is undefined if not known. + +---@class OrType +---@field items Type[] +---@field kind "or" + +---@class Property +---@field documentation? string An optional documentation. +---@field name string The property name; +---@field optional? boolean Whether the property is optional. If omitted, the property is mandatory. +---@field proposed? boolean Whether this is a proposed property. If omitted, the structure is final. +---@field since? string Since when (release number) this property is available. Is undefined if not known. +---@field type Type The type of the property + +---@class Request +---@field documentation? string An optional documentation; +---@field errorData? Type An optional error data type. +---@field messageDirection MessageDirection The direction in which this request is sent in the protocol. +---@field method string The request's method name. +---@field params? Type | Type[] The parameter type(s) if any. +---@field partialResult? Type Optional partial result type if the request supports partial result reporting. +---@field proposed? boolean Whether this is a proposed feature. If omitted the feature is final. +---@field registrationMethod? string Optional a dynamic registration method if it different from the request's method. +---@field registrationOptions? Type Optional registration options if the request supports dynamic registration. +---@field result Type The result type. +---@field since? string Since when (release number) this request is available. Is undefined if not known. + +---@class Structure +---@field documentation? string An optional documentation; +---@field extends? Type[] Structures extended from. This structures form a polymorphic type hierarchy. +---@field mixins? Type[] Structures to mix in. The properties of these structures are `copied` into this structure. Mixins don't form a polymorphic type hierarchy in LSP. +---@field name string The name of the structure. +---@field properties Property[] The properties. +---@field proposed? boolean Whether this is a proposed structure. If omitted, the structure is final. +---@field since? string Since when (release number) this structure is available. Is undefined if not known. + +---@class StructureLiteral +---@field documentation? string An optional documentation. +---@field properties Property[] The properties. +---@field proposed? boolean Whether this is a proposed structure. If omitted, the structure is final. +---@field since? string Since when (release number) this structure is available. Is undefined if not known. + +---@class StructureLiteralType +---@field kind "literal" +---@field value StructureLiteral + +---@class TupleType +---@field items Type[] +---@field kind "tuple" + +---@alias Type BaseType | ReferenceType | ArrayType | MapType | AndType | OrType | TupleType | StructureLiteralType | StringLiteralType | IntegerLiteralType | BooleanLiteralType + +---@class TypeAlias +---@field documentation? string An optional documentation. +---@field name string The name of the type alias. +---@field proposed? boolean Whether this is a proposed type alias. If omitted, the type alias is final. +---@field since? string Since when (release number) this structure is available. Is undefined if not known. +---@field type Type The aliased type. + +---@class Generator +---@field known_objs table +---@field known_literals table +---@field model Model +local Generator = {} +Generator.__index = Generator + +function Generator.new(model) + local self = setmetatable({}, Generator) + self.model = model + self.known_objs = {} + self.known_literals = {} + return self +end + +---@param obj Structure | TypeAlias | StructureLiteral +---@return Structure | TypeAlias +function Generator:register(obj) + if not obj.name then + if not self.known_literals[obj] then + self.known_literals[obj] = { + name = ("Structure%s"):format(#vim.tbl_keys(self.known_literals)), + documentation = obj.documentation, + properties = obj.properties, + proposed = obj.proposed, + since = obj.since, + extends = {}, + mixins = {}, + } + end + obj = self.known_literals[obj] + end + print(("Registering %s"):format(obj.name)) + if not self.known_objs[obj.name] then + self.known_objs[obj.name] = obj + end + return obj +end + +---@param name string +---@return string +function Generator:convert_method_name(name) + local new_name = name:gsub("/", "_"):gsub("%$", "_") + return new_name +end + +---@return string +function Generator:type_prefix() + return "nio.lsp.types" +end + +---@param orig_name string +---@return string +function Generator:structure_name(orig_name) + return self:type_prefix() .. "." .. orig_name +end + +---@param items ReferenceType[] +---@return Structure +function Generator:and_type(items) + local names = vim.tbl_map(function(item) + return item.name + end, items) + local sub_structure = { + name = table.concat(names, "And"), + documentation = "", + extends = items, + properties = {}, + mixins = {}, + proposed = nil, + since = nil, + } + return sub_structure +end + +---@param name Name | Name1 +---@return string +function Generator:key_name_type(name) + if name == "URI" then + return self:type_prefix() .. ".URI" + elseif name == "DocumentUri" then + return self:type_prefix() .. ".DocumentUri" + else + return name + end +end + +---@param type_ Type | MapKeyType) +---@return string +function Generator:type_name(type_) + if type_.kind == "base" then + local name = type_.name + if name == "integer" or name == "uinteger" then + return "integer" + elseif name == "decimal" then + return "number" + elseif name == "string" then + return "string" + elseif name == "boolean" then + return "boolean" + elseif name == "null" then + return "nil" + else + return self:key_name_type(name) + end + elseif type_.kind == "reference" then + local name = type_.name + return self:structure_name(name) + elseif type_.kind == "array" then + local element = type_.element + return self:type_name(element) .. "[]" + elseif type_.kind == "map" then + local key, value = type_.key, type_.value + if key.kind == "reference" then + return ("table<%s, %s>"):format(self:type_name(key), self:type_name(value)) + else + local name = key.name + return ("table<%s, %s>"):format(self:key_name_type(name), self:type_name(value)) + end + elseif type_.kind == "and" then + local items = type_.items + local refs = {} + for _, item in ipairs(items) do + if item.kind == "reference" then + refs[#refs + 1] = item + end + end + if #items > #refs then + print(("Discarding non-reference/literal types from AndType"):format()) + end + local struc = self:and_type(refs) + self:register(struc) + return self:structure_name(struc.name) + elseif type_.kind == "or" then + local items = type_.items + local names = vim.tbl_map(function(item) + return self:type_name(item) + end, items) + + return table.concat(names, "|") + elseif type_.kind == "tuple" then + local items = type_.items + local names = vim.tbl_map(function(item) + return self:type_name(item) + end, items) + + return table.concat(names, ",") + elseif type_.kind == "literal" then + local value = type_.value + local struc = self:register(value) + return self:structure_name(struc.name) + elseif type_.kind == "stringLiteral" then + local value = type_.value + return ("'%s'"):format(value) + end + error("Unknown type " .. type_.kind) +end + +---@param doc string +---@param multiline boolean +---@return string[] +function Generator:prepare_doc(doc, multiline) + local lines = vim.split(doc, "\n", { trimempty = false, plain = true }) + if multiline then + return vim.tbl_map(function(line) + return #line and ("--- %s"):format(line) or "---" + end, lines) + end + return { table.concat(lines, " ") } +end + +---@param structure Structure +---@return string[] +function Generator:structure(structure) + local lines = { "" } + if structure.documentation then + vim.list_extend(lines, self:prepare_doc(structure.documentation, true)) + end + + lines[#lines + 1] = ("---@class %s"):format(self:structure_name(structure.name)) + if structure.extends or structure.mixins then + local extends = vim.list_extend(vim.deepcopy(structure.extends or {}), structure.mixins or {}) + local names = vim.tbl_map(function(type_) + return self:type_name(type_) + end, extends) + if #names > 0 then + lines[#lines] = lines[#lines] .. " : " .. table.concat(names, ",") + end + end + for _, prop in ipairs(structure.properties) do + local line = ("---@field %s%s %s"):format( + prop.name, + prop.optional and "?" or "", + self:type_name(prop.type) + ) + if prop.documentation then + line = line .. " " .. self:prepare_doc(prop.documentation, false)[1] + end + lines[#lines + 1] = line + end + return lines +end + +---@param type_alias TypeAlias +---@return string[] +function Generator:type_alias(type_alias) + self:register(type_alias) + return { + ("---@alias %s.%s %s"):format( + self:type_prefix(), + type_alias.name, + self:type_name(type_alias.type) + ), + } +end + +---@param request Request +---@return string[] +function Generator:request(request) + local lines = {} + if request.documentation then + vim.list_extend(lines, self:prepare_doc(request.documentation, true)) + end + + lines[#lines + 1] = "---@async" + if request.params then + lines[#lines + 1] = ("---@param args %s Arguments to the request"):format(self:type_name(request.params)) + end + lines[#lines + 1] = "---@param bufnr integer? Buffer number (0 for current buffer)" + lines[#lines + 1] = "---@param opts? nio.lsp.RequestOpts Options for the request handling" + lines[#lines + 1] = ("---@return %s.ResponseError|nil error The error object in case a request fails."):format(self:type_prefix()) + if request.result then + lines[#lines + 1] = (("---@return %s"):format(self:type_name(request.result))) + if not vim.endswith(lines[#lines], "|nil") then + lines[#lines] = lines[#lines] .. "|nil" + end + lines[#lines] = lines[#lines] .. " result The result of the request" + end + + lines[#lines + 1] = ( + ("function LSPRequestClient.%s(%sbufnr, opts) end"):format( + self:convert_method_name(request.method), + request.params and "args, " or "" + ) + ) + lines[#lines + 1] = "" + return lines +end + +---@param notification Notification +---@return string[] +function Generator:notification(notification) + local lines = {} + if notification.documentation then + vim.list_extend(lines, self:prepare_doc(notification.documentation, true)) + end + + lines[#lines + 1] = "---@async" + if notification.params then + lines[#lines + 1] = (("---@param args %s"):format(self:type_name(notification.params))) + lines[#lines + 1] = ( + ("function LSPNotifyClient.%s(%s) end"):format( + self:convert_method_name(notification.method), + notification.params and "args" or "" + ) + ) + lines[#lines + 1] = "" + end + return lines +end + +---@param enum Enumeration +---@return string[] +function Generator:enumeration(enum) + local lines = {} + if enum.documentation then + vim.list_extend(lines, self:prepare_doc(enum.documentation, true)) + end + lines[#lines + 1] = ( + ("---@alias %s.%s %s"):format( + self:type_prefix(), + enum.name, + table.concat( + vim.tbl_map(function(val) + return vim.json.encode(val.value) + end, enum.values), + "|" + ) + ) + ) + lines[#lines + 1] = "" + return lines +end + +function Generator:generate() + local lines = { + ("---Generated on %s"):format(os.date("!%Y-%m-%d-%H:%M:%S GMT")), + "", + "---@class nio.lsp.RequestClient", + "local LSPRequestClient = {}", + "---@class nio.lsp.RequestOpts", + "---@field timeout integer Timeout of request in milliseconds", + "---@class nio.lsp.types.ResponseError", + "---@field code number A number indicating the error type that occurred.", + "---@field message string A string providing a short description of the error.", + "---@field data any A Primitive or Structured value that contains additional information about the error. Can be omitted.", + "", + } + local strucs = {} + vim.list_extend(strucs, self.model.structures) + vim.list_extend(strucs, self.model.typeAliases) + vim.list_extend(strucs, self.model.enumerations) + for _, obj in ipairs(strucs) do + self:register(obj) + end + print("Generating requests") + for _, request in ipairs(self.model.requests) do + if request.messageDirection == "clientToServer" or request.messageDirection == "both" then + vim.list_extend(lines, self:request(request)) + end + end + vim.list_extend(lines, { + "---@class nio.lsp.NotifyClient", + "local LSPNotifyClient = {}", + "", + }) + print("Generating notifications") + for _, notification in ipairs(self.model.notifications) do + if notification.messageDirection == "clientToServer" or notification.messageDirection == "both" + then + vim.list_extend(lines, self:notification(notification)) + end + end + vim.list_extend(lines, { + ("---@alias %s string"):format(self:key_name_type("URI")), + ("---@alias %s string"):format(self:key_name_type("DocumentUri")), + }) + + local length = function() + return #vim.tbl_keys(self.known_objs) + end + local last_length = 0 + + print("Discovering types") + while length() > last_length do + for _, obj in pairs(self.known_objs) do + if obj.properties then + self:structure(obj) + elseif obj.values then + self:enumeration(obj) + else + self:type_alias(obj) + end + end + last_length = length() + end + + print("Generating structures") + for _, obj in pairs(self.known_objs) do + if obj.properties then + vim.list_extend(lines, self:structure(obj)) + elseif obj.values then + vim.list_extend(lines, self:enumeration(obj)) + else + vim.list_extend(lines, self:type_alias(obj)) + end + end + print(("Generated %d lines\n"):format(#lines)) + return lines +end + +local file = assert(io.open("lsp.json")) +local model = vim.json.decode(file:read("*a")) +file:close() +local lines = Generator.new(model):generate() + +local out = assert(io.open("lua/nio/lsp-types.lua", "w")) +out:write(table.concat(lines, "\n")) +out:close() +vim.cmd("exit") diff --git a/scripts/style b/scripts/style new file mode 100755 index 0000000..d81d524 --- /dev/null +++ b/scripts/style @@ -0,0 +1,3 @@ +#!/bin/bash + +stylua lua tests diff --git a/scripts/test b/scripts/test new file mode 100755 index 0000000..9688bea --- /dev/null +++ b/scripts/test @@ -0,0 +1,20 @@ +#!/bin/bash +tempfile=".test_output.tmp" + +if [[ -n $1 ]]; then + nvim --headless --noplugin -u tests/init.vim -c "PlenaryBustedFile $1" | tee "${tempfile}" +else + nvim --headless --noplugin -u tests/init.vim -c "PlenaryBustedDirectory tests/ {minimal_init = 'tests/init.vim'}" | tee "${tempfile}" +fi + +# Plenary doesn't emit exit code 1 when tests have errors during setup +errors=$(sed 's/\x1b\[[0-9;]*m//g' "${tempfile}" | awk '/(Errors|Failed) :/ {print $3}' | grep -v '0') + +rm "${tempfile}" + +if [[ -n $errors ]]; then + echo "Tests failed" + exit 1 +fi + +exit 0 diff --git a/stylua.toml b/stylua.toml new file mode 100644 index 0000000..609d773 --- /dev/null +++ b/stylua.toml @@ -0,0 +1,5 @@ +column_width = 100 +line_endings = "Unix" +indent_type = "Spaces" +indent_width = 2 +quote_style = "AutoPreferDouble" diff --git a/test.lua b/test.lua new file mode 100644 index 0000000..f57bab5 --- /dev/null +++ b/test.lua @@ -0,0 +1,16 @@ +local nio = require("nio") + +nio.run(function() + + local client = nio.lsp.get_clients({ name = "lua_ls" })[1] + + local err, response = client.request.textDocument_semanticTokens_full({ + textDocument = { uri = vim.uri_from_bufnr(0) }, + }) + + assert(not err, err) + + for _, i in pairs(response and response.data or {}) do + print(i) + end +end) diff --git a/tests/control_spec.lua b/tests/control_spec.lua new file mode 100644 index 0000000..7d54883 --- /dev/null +++ b/tests/control_spec.lua @@ -0,0 +1,145 @@ +local nio = require("nio") +local a = nio.tests + +describe("event", function() + a.it("notifies listeners", function() + local event = nio.control.event() + local notified = 0 + for _ = 1, 10 do + nio.run(function() + event.wait() + notified = notified + 1 + end) + end + + event.set() + nio.sleep(10) + assert.equals(10, notified) + end) + + a.it("notifies listeners when already set", function() + local event = nio.control.event() + local notified = 0 + event.set() + for _ = 1, 10 do + nio.run(function() + event.wait() + notified = notified + 1 + end) + end + + nio.sleep(10) + assert.equals(10, notified) + end) +end) + +describe("future", function() + a.it("provides listeners result", function() + local future = nio.control.future() + local notified = 0 + for _ = 1, 10 do + nio.run(function() + local val = future.wait() + notified = notified + val + end) + end + + future.set(1) + nio.sleep(10) + assert.equals(10, notified) + end) + + a.it("notifies listeners when already set", function() + local future = nio.control.future() + local notified = 0 + future.set(1) + for _ = 1, 10 do + nio.run(function() + notified = notified + future.wait() + end) + end + + nio.sleep(10) + assert.equals(10, notified) + end) + + a.it("raises error for listeners", function() + local future = nio.control.future() + local notified = 0 + future.set_error("test") + local success, err = pcall(future.wait) + + nio.sleep(10) + assert.False(success) + assert.True(vim.endswith(err, "test")) + end) +end) +describe("queue", function() + a.it("adds and removes items", function() + local queue = nio.control.queue() + queue.put(1) + queue.put(2) + + assert.same(queue.size(), 2) + assert.same(1, queue.get()) + assert.same(2, queue.get()) + assert.same(queue.size(), 0) + end) + + a.it("get blocks while empty", function() + local queue = nio.control.queue() + nio.run(function() + nio.sleep(10) + queue.put(1) + end) + assert.same(1, queue.get()) + end) + + a.it("put blocks while full", function() + local queue = nio.control.queue(1) + nio.run(function() + nio.sleep(10) + queue.get() + end) + queue.put(1) + queue.put(2) + assert.same(2, queue.get()) + end) + + it("get_nowait errors when empty", function() + local queue = nio.control.queue() + assert.error(queue.get_nowait) + end) + + it("put_nowait errors while full", function() + local queue = nio.control.queue(1) + queue.put_nowait(1) + assert.error(function() + queue.put_nowait(2) + end) + end) +end) + +describe("semaphore", function() + a.it("only allows permitted number of concurrent accesses", function() + local concurrent = 0 + local max_concurrent = 0 + local allowed = 3 + local semaphore = nio.control.semaphore(allowed) + local worker = function() + semaphore.with(function() + concurrent = concurrent + 1 + max_concurrent = math.max(max_concurrent, concurrent) + nio.sleep(10) + concurrent = concurrent - 1 + end) + end + local workers = {} + for _ = 1, 10 do + table.insert(workers, worker) + end + nio.gather(workers) + + assert.same(max_concurrent, allowed) + end) +end) diff --git a/tests/init.vim b/tests/init.vim new file mode 100644 index 0000000..aa9a5f0 --- /dev/null +++ b/tests/init.vim @@ -0,0 +1 @@ +source tests/minimal_init.lua diff --git a/tests/init_spec.lua b/tests/init_spec.lua new file mode 100644 index 0000000..7c50576 --- /dev/null +++ b/tests/init_spec.lua @@ -0,0 +1,118 @@ +local nio = require("nio") +local a = nio.tests + +describe("async helpers", function() + a.it("sleep", function() + local start = vim.loop.now() + nio.sleep(10) + local end_ = vim.loop.now() + assert.True(end_ - start >= 10) + end) + + a.it("wrap returns values provided to callback", function() + local result + local wrapped = nio.wrap(function(_, _, cb) + cb(1, 2) + end, 3) + nio.run(wrapped, function(_, ...) + result = { ... } + end) + + assert.same({ 1, 2 }, result) + end) + + a.it("gather returns results", function() + local worker = function(i) + return function() + nio.sleep(100 - (i * 10)) + return i + end + end + + local workers = {} + for i = 1, 10 do + table.insert(workers, worker(i)) + end + + local results = nio.gather(workers) + assert.same({ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, results) + end) + + a.it("gather raises errors", function() + local worker = function(i) + return function() + if i == 4 then + error("error") + end + nio.sleep(100 - (i * 10)) + return i + end + end + + local workers = {} + for i = 1, 10 do + table.insert(workers, worker(i)) + end + + assert.error(function() + nio.gather(workers) + end) + end) + + a.it("first returns first result", function() + local worker = function(i) + return function() + nio.sleep(100 - (i * 10)) + return i + end + end + + local workers = {} + for i = 1, 10 do + table.insert(workers, worker(i)) + end + + local result = nio.first(workers) + assert.same(10, result) + end) + + a.it("first cancels pending tasks", function() + local worker = function(i) + return function() + nio.sleep(100 - (i * 10)) + if i ~= 10 then + error("error") + end + return i + end + end + + local workers = {} + for i = 1, 10 do + table.insert(workers, worker(i)) + end + + nio.first(workers) + end) + + a.it("first raises errors", function() + local worker = function(i) + return function() + if i == 4 then + error("error") + end + nio.sleep(100 - (i * 10)) + return i + end + end + + local workers = {} + for i = 1, 10 do + table.insert(workers, worker(i)) + end + + assert.error(function() + nio.first(workers) + end) + end) +end) diff --git a/tests/lsp_spec.lua b/tests/lsp_spec.lua new file mode 100644 index 0000000..ef716d4 --- /dev/null +++ b/tests/lsp_spec.lua @@ -0,0 +1,96 @@ +local nio = require("nio") +local a = nio.tests + +describe("lsp client", function() + a.it("sends request and returns result", function() + local expected_result = { "test" } + local expected_params = { a = "b" } + vim.lsp.get_client_by_id = function(id) + return { + request = function(method, params, callback, bufnr) + assert.equals("textDocument/diagnostic", method) + assert.equals(0, bufnr) + assert.same(params, params) + callback(nil, expected_result) + return true, 1 + end, + } + end + + local client = nio.lsp.client(1) + + local err, result = + client.request.textDocument_diagnostic(expected_params, 0, { timeout = 1000 }) + assert.same(expected_result, result) + end) + + a.it("returns error for request", function() + local params = { a = "b" } + vim.lsp.get_client_by_id = function(id) + return { + request = function(method, params, callback, bufnr) + callback({ message = "error" }, nil) + return true, 1 + end, + } + end + + local client = nio.lsp.client(1) + + local err, result = client.request.textDocument_diagnostic(0, params) + assert.same(err.message, "error") + assert.Nil(result) + end) + + a.it("raises error on timeout", function() + vim.lsp.get_client_by_id = function(id) + return { + request = function(method, params, callback, bufnr) + return true, 1 + end, + } + end + + local client = nio.lsp.client(1) + + local err, result = client.request.textDocument_diagnostic({}, 0, { timeout = 10 }) + assert.same(err.message, "Request timed out") + assert.Nil(result) + end) + + a.it("cancels request on timeout", function() + local cancel_received = false + vim.lsp.get_client_by_id = function(id) + return { + request = function(method, params, callback, bufnr) + if method == "$/cancelRequest" then + cancel_received = true + end + return true, 1 + end, + } + end + + local client = nio.lsp.client(1) + + client.request.textDocument_diagnostic({}, 0, { timeout = 10 }) + assert.True(cancel_received) + end) + + a.it("raises errors on client shutdown", function() + vim.lsp.get_client_by_id = function(id) + return { + id = id, + request = function(method, params, callback, bufnr) + return false + end, + } + end + + local client = nio.lsp.client(1) + + local success, err = pcall(client.request.textDocument_diagnostic, {}, 0, { timeout = 10 }) + assert.False(success) + assert.Not.Nil(string.find(err, "Client 1 has shut down")) + end) +end) diff --git a/tests/minimal_init.lua b/tests/minimal_init.lua new file mode 100644 index 0000000..8278230 --- /dev/null +++ b/tests/minimal_init.lua @@ -0,0 +1,9 @@ +local lazypath = vim.fn.stdpath("data") .. "/lazy" +vim.notify = print +vim.opt.rtp:append(".") +vim.opt.rtp:append(lazypath .. "/plenary.nvim") +vim.cmd("runtime! plugin/plenary.vim") +vim.opt.swapfile = false +A = function(...) + print(vim.inspect(...)) +end diff --git a/tests/tasks_spec.lua b/tests/tasks_spec.lua new file mode 100644 index 0000000..6899e84 --- /dev/null +++ b/tests/tasks_spec.lua @@ -0,0 +1,120 @@ +local tasks = require("nio.tasks") +local nio = require("nio") +local a = nio.tests + +describe("task", function() + a.it("provides result in callback", function() + local result + tasks.run(function() + nio.sleep(5) + return "test" + end, function(_, result_) + result = result_ + end) + nio.sleep(10) + assert.equals("test", result) + end) + + a.it("cancels", function() + local err + local task = tasks.run(function() + nio.sleep(10) + return "test" + end, function(_, err_) + err = err_ + end) + task.cancel() + nio.sleep(10) + assert.True(vim.endswith(vim.split(err, "\n")[1], "Task was cancelled")) + end) + + a.it("cancels children", function() + local should_be_nil + local task = tasks.run(function() + tasks.run(function() + nio.sleep(10) + should_be_nil = "not nil" + end) + nio.sleep(10) + end) + task.cancel() + nio.sleep(20) + assert.Nil(should_be_nil) + end) + + a.it("assigns parent task", function() + local current = tasks.current_task() + local task = tasks.run(function() + return "test" + end) + assert.Not.Nil(task.parent) + assert.equal(current, task.parent) + end) + + it("assigns no parent task", function() + local task = tasks.run(function() + return "test" + end) + assert.Nil(task.parent) + end) + + a.it("returns error in function", function() + local success, err + tasks.run(function() + error("test") + end, function(success_, err_) + success, err = success_, err_ + end) + nio.sleep(10) + assert.False(success) + assert.True(vim.endswith(vim.split(err, "\n")[2], "test")) + end) + + a.it("returns error when wrapped function errors", function() + local success, err + local bad_wrapped = tasks.wrap(function() + error("test") + end, 1) + tasks.run(bad_wrapped, function(success_, err_) + success, err = success_, err_ + end) + nio.sleep(10) + assert.False(success) + assert.True(vim.endswith(vim.split(err, "\n")[2], "test")) + end) + + a.it("pcall returns result", function() + local success, x, y = pcall(function() + return 1, 2 + end) + assert.True(success) + assert.equals(1, x) + assert.equals(2, y) + end) + + a.it("pcall returns error", function() + local success, err = pcall(function() + error("test") + end) + assert.False(success) + assert.True(vim.endswith(vim.split(err, "\n")[1], "test")) + end) + + a.it("pcall returns error when wrapped function errors", function() + local success, err = pcall(tasks.wrap(function(...) + error("test") + end, 1)) + + nio.sleep(10) + assert.False(success) + assert.True(vim.endswith(vim.split(err, "\n")[1], "test")) + end) + + a.it("current task", function() + local current + local task = tasks.run(function() + current = tasks.current_task() + end) + assert.equal(task, current) + end) +end) diff --git a/tests/uv_spec.lua b/tests/uv_spec.lua new file mode 100644 index 0000000..a692609 --- /dev/null +++ b/tests/uv_spec.lua @@ -0,0 +1,31 @@ +local nio = require("nio") +local a = nio.tests + +describe("file operations", function() + local path = vim.fn.tempname() + a.after_each(function() + os.remove(path) + end) + a.it("reads a file", function() + local f = assert(io.open(path, "w")) + f:write("test read") + f:close() + + local _, file = nio.uv.fs_open(path, "r", 438) + local _, data = nio.uv.fs_read(file, 1024, -1) + nio.uv.fs_close(file) + assert.equals("test read", data) + end) + + a.it("writes a file", function() + local _, file = nio.uv.fs_open(path, "w", 438) + nio.uv.fs_write(file, "test write") + nio.uv.fs_close(file) + + local file = assert(io.open(path, "r")) + local data = file:read() + file:close() + + assert.equals("test write", data) + end) +end)