repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/skills/lua-annotations/SKILL.md

Raw

name: lua-annotations description: Write LuaCATS doc annotations for LuaLS type checking — @class, @param, @return, @field, @type, @alias, @enum, generics, function types, optional types. Use when: writing Lua doc comments, adding type annotations, documenting Lua modules, configuring LuaLS. license: MIT

Lua Doc Annotations (LuaCATS)

Add type information and documentation to Lua code for LuaLS (Lua Language Server) / EmmyLua.

Syntax Basics

Comment Prefix

All doc annotations use --- (triple dash):

--- @param name string

Inline cast on a single line:

local x = 42 ---@type number

Inline Type Cast

--[[@as type]]
local x = something ---@as string

Descriptions

Text after the annotation becomes the description. Use blank lines to separate:

--- @class MyClass
---
--- A longer description that continues
--- across multiple lines.
---
---@param value number The value to process

Newlines in Descriptions

Prefer <br> for line breaks:

--- This is line one.<br>This is line two.

Also supported: \n or two trailing spaces.

Markdown Support

Descriptions support markdown:

--- **Important**: See [`vim.print()`](lua://vim.print) for details.

Type System

Primitives

nil, any, boolean, string, number, integer, function, table, thread, userdata, lightuserdata

Optional Types (? suffix)

? after name means type | nil:

--- @field name? string    equivalent to name: string | nil
--- @param opts? table     equivalent to opts: table | nil

Two equivalent forms for optional params:

--- @param opts? table
--- @param opts table?

Union Types

integer | string
"foo" | "bar"           -- string literal union
boolean | nil

Array Types

string[]              -- array of strings
integer[]
vim.api.keyset[]

Table/Dict Types

{ [string]: any }     -- dict with string keys
{ [integer]: string }-- dict with integer keys
table<K, V>           -- generic table

Table Literals

{ key: TYPE, key2: TYPE2 }

Function Types

fun(): void
fun(self: TSNode)
fun(err: string, data: string)
fun(opts: table): boolean
fun(path: string, change_type: vim._watch.FileChangeType)

Tuple Types

[integer, integer]          -- (row, col)
[integer, integer, boolean] -- three values

String Literals

"replace" | "combine" | "blend"
"foo" | "bar" | "baz"

Defining Types

@class — Classes and Structs

--- @class vim.api.keyset.win_config
--- @field external? boolean
--- @field focusable? boolean
--- @field height? integer
--- @field width? integer
--- @field border? any[]|"none"|"single"|"double"|"rounded"|"solid"|"shadow"

Inheritance:

--- @class vim.fn.winsaveview.ret: vim.fn.winrestview.dict
--- @field col integer

Exact class (prevents field injection):

--- @class (exact) MyConfig

Private class:

--- @class (private) vim.var_accessor

@field — Class Fields

--- @field name string
--- @field id? integer           -- optional
--- @field items? string[]       -- optional array
--- @field callback? fun(err: string, data: string)
--- @field nr? integer|'$'       -- union
--- @field [string] any          -- index signature: any string key
--- @field [integer] vim.var_accessor  -- numeric index

@enum — Runtime Enums

--- @enum vim._watch.FileChangeType
M.FileChangeType = {
  Created = 1,
  Changed = 2,
  Deleted = 3,
}

Use @alias for type-only unions instead.

@alias — Type Aliases

--- @alias vim._watch.Callback fun(path: string, change_type: vim._watch.FileChangeType)

--- @alias vim.api.keyset.events
--- | 'BufAdd'
--- | 'BufCreate'
--- | 'BufDelete'

@type — Variable Typing

--- @type vim.NIL
vim.NIL = ...

--- @type LazyPlugin[]
M.to_clean = {}

--- @type string
M.me = nil

Documenting Functions

@param — Parameters

--- @param buffer integer Buffer id, or 0 for current buffer
--- @param ns_id integer Namespace id from nvim_create_namespace()
--- @param opts vim.api.keyset.set_extmark Optional parameters.
--- @param opts? table

@return — Return Values

--- @return integer # Id of the created extmark
--- @return string[] # List of absolute paths
--- @return boolean # true if found, else false

Named returns:

--- @return boolean ok
--- @return nil|-1|-2 status

Optional return:

--- @return string? # nil if conversion fails

Tuple return:

--- @return [integer, integer] # (row, col)

@overload — Multiple Signatures

--- @overload fun(self: TSNode, include_bytes: true): integer, integer, integer, integer, integer, integer
--- @overload fun(self: TSNode, include_bytes?: false): integer, integer, integer, integer
function TSNode:range(include_bytes) end

@generic — Generic Types

--- @generic T
--- @param list T[]
--- @return T

@async — Async Functions

--- @async

Visibility and Control

@private, @package, @protected

--- @private
function vim._on_key(buf, typed_buf) end

--- @package
--- @protected

@meta — Type-Only Files

In vim/_meta/ directories:

--- @meta _
error('Cannot require a meta file')

--- @class vim.api.keyset.win_config
--- @field width? integer

@deprecated — Mark Deprecated

--- @deprecated
function vim.api.nvim_buf_add_highlight(...) end

@nodiscard — Warn on Unused

--- @nodiscard
function M.important() end

@diagnostic — Control Warnings

--- @diagnostic disable: undefined-doc-name
--- @diagnostic disable-next-line: unused-function

@cast — Type Assertion

--- @cast parsed nvim.luacats.Class

Cross-References

@see — Links

--- @see vim.api.nvim_buf_detach
--- @see `:help api-buffer-updates-lua`
--- @see |vim.print()|
--- @see https://github.com/kikito/inspect.lua

Markdown Links

--- See [`vim.print()`](lua://vim.print) for details.

lua:// Symbol Links (v3.9.2+)

--- @return string[] Files matching [pattern](lua://vim.fn.globpath)

Common Patterns

Module Export

local M = {}

--- @class MyPlugin.State
--- @field bufnr? integer
--- @field items string[]

--- Initialize the plugin.
--- @param opts? MyPlugin.Opts
function M.setup(opts) end

return M

Config/Opts Tables

--- @class MyPlugin.Opts
--- @field enabled? boolean Whether the plugin is active
--- @field timeout? integer Timeout in ms (default: 1000)
--- @field on_done? fun(result: string) Callback when done

Callback Typing

--- @param callback fun(err: string|nil, data: string|nil)

Keymap Descriptions

Always include desc:

vim.keymap.set('n', '<leader>f', function()
  require('telescope.builtin').find_files()
end, {
  desc = 'Find files',
  noremap = true,
})

Autocmd Callback Args

--- @class vim.api.keyset.create_autocmd.callback_args
--- @field id integer
--- @field event string
--- @field match string
--- @field buf integer
--- @field data? any

vim.api.nvim_create_autocmd('BufWritePost', {
  callback = function(ev)
    -- ev is typed
  end,
})

Reference Files

Task Load Reference
Neovim-specific patterns references/neovim.md
All annotations table references/annotations.md

Load a reference by reading the file directly.


Quick Type Cheatsheet

Pattern Meaning
string string type
string? string | nil
string[] array of strings
{[string]: V} dict with string keys
fun(): void function returning nothing
T generic type parameter
"a" | "b" string literal union
Markdown source
---
name: lua-annotations
description: Write LuaCATS doc annotations for LuaLS type checking — @class, @param, @return, @field, @type, @alias, @enum, generics, function types, optional types. Use when: writing Lua doc comments, adding type annotations, documenting Lua modules, configuring LuaLS.
  license: MIT
---

# Lua Doc Annotations (LuaCATS)

Add type information and documentation to Lua code for LuaLS (Lua Language
Server) / EmmyLua.

## Syntax Basics

### Comment Prefix

All doc annotations use `---` (triple dash):

```lua
--- @param name string
```

Inline cast on a single line:

```lua
local x = 42 ---@type number
```

### Inline Type Cast

```lua
--[[@as type]]
local x = something ---@as string
```

### Descriptions

Text after the annotation becomes the description. Use blank lines to separate:

```lua
--- @class MyClass
---
--- A longer description that continues
--- across multiple lines.
---
---@param value number The value to process
```

### Newlines in Descriptions

Prefer `<br>` for line breaks:

```lua
--- This is line one.<br>This is line two.
```

Also supported: `\n` or two trailing spaces.

### Markdown Support

Descriptions support markdown:

```lua
--- **Important**: See [`vim.print()`](lua://vim.print) for details.
```

---

## Type System

### Primitives

```lua
nil, any, boolean, string, number, integer, function, table, thread, userdata, lightuserdata
```

### Optional Types (`?` suffix)

`?` after name means `type | nil`:

```lua
--- @field name? string    equivalent to name: string | nil
--- @param opts? table     equivalent to opts: table | nil
```

Two equivalent forms for optional params:

```lua
--- @param opts? table
--- @param opts table?
```

### Union Types

```lua
integer | string
"foo" | "bar"           -- string literal union
boolean | nil
```

### Array Types

```lua
string[]              -- array of strings
integer[]
vim.api.keyset[]
```

### Table/Dict Types

```lua
{ [string]: any }     -- dict with string keys
{ [integer]: string }-- dict with integer keys
table<K, V>           -- generic table
```

### Table Literals

```lua
{ key: TYPE, key2: TYPE2 }
```

### Function Types

```lua
fun(): void
fun(self: TSNode)
fun(err: string, data: string)
fun(opts: table): boolean
fun(path: string, change_type: vim._watch.FileChangeType)
```

### Tuple Types

```lua
[integer, integer]          -- (row, col)
[integer, integer, boolean] -- three values
```

### String Literals

```lua
"replace" | "combine" | "blend"
"foo" | "bar" | "baz"
```

---

## Defining Types

### @class — Classes and Structs

```lua
--- @class vim.api.keyset.win_config
--- @field external? boolean
--- @field focusable? boolean
--- @field height? integer
--- @field width? integer
--- @field border? any[]|"none"|"single"|"double"|"rounded"|"solid"|"shadow"
```

**Inheritance:**

```lua
--- @class vim.fn.winsaveview.ret: vim.fn.winrestview.dict
--- @field col integer
```

**Exact class (prevents field injection):**

```lua
--- @class (exact) MyConfig
```

**Private class:**

```lua
--- @class (private) vim.var_accessor
```

### @field — Class Fields

```lua
--- @field name string
--- @field id? integer           -- optional
--- @field items? string[]       -- optional array
--- @field callback? fun(err: string, data: string)
--- @field nr? integer|'$'       -- union
--- @field [string] any          -- index signature: any string key
--- @field [integer] vim.var_accessor  -- numeric index
```

### @enum — Runtime Enums

```lua
--- @enum vim._watch.FileChangeType
M.FileChangeType = {
  Created = 1,
  Changed = 2,
  Deleted = 3,
}
```

Use `@alias` for type-only unions instead.

### @alias — Type Aliases

```lua
--- @alias vim._watch.Callback fun(path: string, change_type: vim._watch.FileChangeType)

--- @alias vim.api.keyset.events
--- | 'BufAdd'
--- | 'BufCreate'
--- | 'BufDelete'
```

### @type — Variable Typing

```lua
--- @type vim.NIL
vim.NIL = ...

--- @type LazyPlugin[]
M.to_clean = {}

--- @type string
M.me = nil
```

---

## Documenting Functions

### @param — Parameters

```lua
--- @param buffer integer Buffer id, or 0 for current buffer
--- @param ns_id integer Namespace id from nvim_create_namespace()
--- @param opts vim.api.keyset.set_extmark Optional parameters.
--- @param opts? table
```

### @return — Return Values

```lua
--- @return integer # Id of the created extmark
--- @return string[] # List of absolute paths
--- @return boolean # true if found, else false
```

**Named returns:**

```lua
--- @return boolean ok
--- @return nil|-1|-2 status
```

**Optional return:**

```lua
--- @return string? # nil if conversion fails
```

**Tuple return:**

```lua
--- @return [integer, integer] # (row, col)
```

### @overload — Multiple Signatures

```lua
--- @overload fun(self: TSNode, include_bytes: true): integer, integer, integer, integer, integer, integer
--- @overload fun(self: TSNode, include_bytes?: false): integer, integer, integer, integer
function TSNode:range(include_bytes) end
```

### @generic — Generic Types

```lua
--- @generic T
--- @param list T[]
--- @return T
```

### @async — Async Functions

```lua
--- @async
```

---

## Visibility and Control

### @private, @package, @protected

```lua
--- @private
function vim._on_key(buf, typed_buf) end

--- @package
--- @protected
```

### @meta — Type-Only Files

In `vim/_meta/` directories:

```lua
--- @meta _
error('Cannot require a meta file')

--- @class vim.api.keyset.win_config
--- @field width? integer
```

### @deprecated — Mark Deprecated

```lua
--- @deprecated
function vim.api.nvim_buf_add_highlight(...) end
```

### @nodiscard — Warn on Unused

```lua
--- @nodiscard
function M.important() end
```

### @diagnostic — Control Warnings

```lua
--- @diagnostic disable: undefined-doc-name
--- @diagnostic disable-next-line: unused-function
```

### @cast — Type Assertion

```lua
--- @cast parsed nvim.luacats.Class
```

---

## Cross-References

### @see — Links

```lua
--- @see vim.api.nvim_buf_detach
--- @see `:help api-buffer-updates-lua`
--- @see |vim.print()|
--- @see https://github.com/kikito/inspect.lua
```

### Markdown Links

```lua
--- See [`vim.print()`](lua://vim.print) for details.
```

### lua:// Symbol Links (v3.9.2+)

```lua
--- @return string[] Files matching [pattern](lua://vim.fn.globpath)
```

---

## Common Patterns

### Module Export

```lua
local M = {}

--- @class MyPlugin.State
--- @field bufnr? integer
--- @field items string[]

--- Initialize the plugin.
--- @param opts? MyPlugin.Opts
function M.setup(opts) end

return M
```

### Config/Opts Tables

```lua
--- @class MyPlugin.Opts
--- @field enabled? boolean Whether the plugin is active
--- @field timeout? integer Timeout in ms (default: 1000)
--- @field on_done? fun(result: string) Callback when done
```

### Callback Typing

```lua
--- @param callback fun(err: string|nil, data: string|nil)
```

### Keymap Descriptions

Always include `desc`:

```lua
vim.keymap.set('n', '<leader>f', function()
  require('telescope.builtin').find_files()
end, {
  desc = 'Find files',
  noremap = true,
})
```

### Autocmd Callback Args

```lua
--- @class vim.api.keyset.create_autocmd.callback_args
--- @field id integer
--- @field event string
--- @field match string
--- @field buf integer
--- @field data? any

vim.api.nvim_create_autocmd('BufWritePost', {
  callback = function(ev)
    -- ev is typed
  end,
})
```

---

## Reference Files

| Task                     | Load Reference              |
| ------------------------ | --------------------------- |
| Neovim-specific patterns | `references/neovim.md`      |
| All annotations table    | `references/annotations.md` |

Load a reference by reading the file directly.

---

## Quick Type Cheatsheet

| Pattern         | Meaning                    |
| --------------- | -------------------------- |
| `string`        | string type                |
| `string?`       | `string \| nil`            |
| `string[]`      | array of strings           |
| `{[string]: V}` | dict with string keys      |
| `fun(): void`   | function returning nothing |
| `T`             | generic type parameter     |
| `"a" \| "b"`    | string literal union       |