Skip to content

Instantly share code, notes, and snippets.

@rektide
Last active January 29, 2026 10:53
Show Gist options
  • Select an option

  • Save rektide/51e2fa3911b8bf3dcc8edf1ae40eacb5 to your computer and use it in GitHub Desktop.

Select an option

Save rektide/51e2fa3911b8bf3dcc8edf1ae40eacb5 to your computer and use it in GitHub Desktop.
plenary-cheatsheet

Plenary Async System: Deep Dive

Overview

Plenary's async system (plenary.async) is a coroutine-based async framework built on top of Neovim's libuv event loop. It converts traditional callback-style Node.js patterns into Lua coroutines, allowing you to write async code that looks synchronous.

Core Concept: plenary.async.async

The async.async module provides fundamental building blocks:

a.wrap(func, argc)

Converts a callback-style function into an async function that can be awaited.

local a = require("plenary.async")

-- Convert vim.defer (callback-style) to async
local sleep_async = a.wrap(vim.defer,2)

-- Now we can use it like a normal function
a.run(function()
  sleep_async(100)  -- Awaits 100ms
  print("Done!")
end)

How it works:

  1. When you call the wrapped function, it checks if all arguments are provided
  2. If yes: calls the original function directly (sync path)
  3. If no: yields the coroutine with the function and argument count
  4. Later, when the callback is invoked, it resumes the coroutine with the result

a.run(async_function, callback)

Executes an async function and calls a callback when complete.

a.run(function()
  -- This is an async context
  local result = some_async_operation()
  return result
end, function(success, ...)
  -- Callback runs when done
  if success then
    print("Result:", ...)
  else
    print("Error:", ...)
  end
end)

a.void(func)

Creates a fire-and-forget async function. Cannot return values since it doesn't block.

local schedule_async = a.void(function()
  vim.schedule(function()
    print("This runs in main loop")
  end)
end)

-- Returns immediately, runs in background
schedule_async()

Channels: How recv Works

Channels provide a way to pass data between different async contexts. There are three types:

1. Oneshot Channel

Send once, receive once.

local tx, rx = a.control.channel.oneshot()

-- Receiver (async function) - blocks until sender() is called
a.run(function()
  local value = rx()  -- Blocks here!
  print("Got:", value)
end)

-- Sender (regular function) - not async
tx("hello")  -- Unblocks the receiver

How oneshot recv works:

  • rx() is an async function created with a.wrap
  • When called, it yields its coroutine
  • It stores its callback in a saved_callback variable
  • When tx() is called:
    • If callback exists → calls it immediately with the value
    • If no callback yet → stores the value
    • Later when rx() is called → returns the stored value

What happens if you recv() with nothing?

  • The coroutine yields/blocks until tx() is called
  • Your async function pauses at that line
  • When data arrives, the coroutine resumes and continues

2. Counter Channel

Notification-only, no data passing.

local sender, receiver = a.control.channel.counter()

a.run(function()
  -- Blocks until at least one send() has happened
  receiver.recv()
  print("Got notification!")

  -- Another receiver
  receiver.recv()
  print("Another notification!")
end)

-- Multiple sends
sender.send()  -- First recv unblocks
sender.send()  -- Second recv unblocks

How counter recv works:

  • Uses a Condvar (condition variable) internally
  • recv() checks if counter > 0
  • If yes: decrements counter and returns
  • If no: calls condvar:wait() to block
  • When send() happens: it increments counter and calls condvar:notify_all()
  • This wakes up all waiting receivers

What happens if you recv() with nothing?

  • If counter == 0: blocks via condvar:wait()
  • Coroutine yields until send() is called

3. MPSC Channel (Multi-Producer, Single-Consumer)

Multiple senders, single receiver, queue based.

local sender, receiver = a.control.channel.mpsc()

-- Producer 1
a.run(function()
  for i = 1, 5 do
    sender.send(i)
    a.util.sleep(100)
  end
end)

-- Producer 2
a.run(function()
  for i = 6, 10 do
    sender.send(i)
    a.util.sleep(100)
  end
end)

-- Consumer (blocks until data available)
while true do
  local value = receiver.recv()  -- Blocks if queue empty
  print("Received:", value)
end

How mpsc recv works:

  • Uses a Deque (double-ended queue) internally
  • recv() checks if deque is empty
  • If not empty: pops and returns the value
  • If empty: calls condvar:wait() to block
  • When send() happens: pushes to deque and calls condvar:notify_all()
  • Wakes up waiting receiver(s)

What happens if you recv() with nothing?

  • If deque is empty: blocks via condvar:wait()
  • When any send() adds data: unblocks and returns that data

How Do We Know When to recv?

This is pull model vs push model:

Pull model (channels):

  • You call recv() when you're ready to process data
  • The code structure makes this clear:
while true do
  local data = receiver.recv()  -- I'm ready for data now
  process(data)
end

Push model (callbacks):

  • Data arrives whenever, you handle it in a callback
  • Flow is inverted: callback controls when you handle data

The async system lets you write pull-style code that looks synchronous, but actually yields when no data is available.


What Happens When recv Has Nothing?

Depends on context:

In async context (a.run):

a.run(function()
  print("Before recv")
  local data = receiver.recv()  -- Yields here!
  print("After recv")  -- Won't run until data arrives
end)
  • Coroutine yields to the event loop
  • Neovim stays responsive
  • When data arrives → coroutine resumes → continues

In sync context (util.block_on):

-- DANGER: Blocks entire Neovim!
local data = util.block_on(function()
  return receiver.recv()
end)
  • Blocks entire Neovim (not recommended!)
  • Used only for testing or very special cases

Key point: The coroutine yields, but the event loop keeps running. Other async operations can continue.


What Uses plenary.async.async & Futures?

1. Async Libuv Operations (plenary.async.uv_async)

All filesystem and network operations wrapped:

  • fs_read, fs_write, fs_mkdir, etc.
  • tcp_connect, udp_send, etc.
local uv = require("plenary.async").uv

a.run(function()
  local content = uv.fs_read("file.txt")
  print(content)
end)

2. Async LSP Operations (plenary.async.lsp)

local lsp = require("plenary.async").lsp

a.run(function()
  local result = lsp.buf_request(0, "textDocument/hover", params)
  print(result)
end)

3. Async Utilities (plenary.async.util)

  • util.sleep(ms) - Async sleep
  • util.join(fns) - Wait for multiple async functions
  • util.run_first(fns) - Race: first to complete wins
  • util.race(fns) - Race with regular functions
  • util.scheduler() - Yield to vim.schedule
  • util.apcall/protected - Safe error handling

4. Async Control Structures (plenary.async.control)

  • Condvar - Wait/notify pattern (like Go's sync.Cond)
  • Semaphore - Limited concurrent access (like Go's sema)
  • Channels - Oneshot, counter, MPSC (like Go's chan)

5. Async Testing (plenary.async.tests)

describe("async test", function()
  a.it("should do something async", function()
    a.util.sleep(100)
    assert(true)
  end)
end)

Real-World Example

Here's a complete example combining multiple concepts:

local a = require("plenary.async")
local channel = a.control.channel
local util = a.util

-- Worker pool using semaphores
local MAX_WORKERS = 3
local semaphore = a.control.Semaphore.new(MAX_WORKERS)

local task_sender, task_receiver = channel.mpsc()

-- Start consumer
a.run(function()
  while true do
    local task = task_receiver.recv()  -- Pull next task

    -- Acquire worker slot
    local permit = semaphore.acquire()

    -- Do work
    print("Processing:", task.name)
    a.util.sleep(task.duration)
    print("Done:", task.name)

    -- Release worker slot
    permit:forget()
  end
end)

-- Queue some tasks
for i = 1, 10 do
  task_sender.send({name = "Task " .. i, duration = 100})
end

-- Sleep to see work happen
a.util.sleep(2000)

What's happening:

  1. Worker pool limited to 3 concurrent tasks
  2. Consumer pulls tasks from channel (blocks when empty)
  3. Each worker acquires semaphore permit (blocks if full)
  4. When worker finishes, releases permit (unblocks waiting worker)
  5. All this looks synchronous but actually yields to event loop

Key Takeaways

  1. a.wrap() is the bridge: callbacks → async coroutines
  2. Channels let you coordinate between async contexts
  3. recv() blocks but yields, keeping Neovim responsive
  4. Use a.run() to enter async context, void() for fire-and-forget
  5. Everything in async/ uses this system: file I/O, LSP, timers, etc.

The async system lets you write concurrent, non-blocking Lua code that feels synchronous and readable, while leveraging Neovim's event loop under the hood.

Plenary.nvim API Reference

Complete API reference for the Plenary.nvim Lua library.

Table of Contents


plenary (init.lua)

Lazy-loads all Plenary modules dynamically.

name arg name / returns description type
module value All modules are lazy-loaded through metatable __index table

plenary.strings (strings.lua)

String manipulation utilities with Unicode support.

name arg name / returns description type default
M.strdisplaywidth Calculate display width of a string, accounting for Unicode characters function
str String to measure string|number
col Starting column offset number
returns Number of display cells number
M.strcharpart Extract a substring by character positions, not byte positions function
str Source string string
nchar Starting character position number
charlen Number of characters to extract number
returns Extracted substring string
M.truncate Truncate a string to fit within a display width function
str String to truncate string
len Maximum display width number
dots Truncation indicator string
direction Truncation direction (1=left, -1=right, 0=center) number 1
returns Truncated string string
M.align_str Align a string to a specified width function
string String to align string
width Target display width number
right_justify If true, right-align; otherwise left-align boolean
returns Padded string string
M.dedent Remove common indentation from multi-line strings function
str Multi-line string to dedent string
leave_indent Indentation to preserve number
returns Dedented string string

plenary.functional (functional.lua)

Functional programming utilities.

name arg name / returns description type
f.kv_pairs Convert table key-value pairs to array of {key, value} tables function
t Source table table
returns Array of {key, value} pairs array
f.kv_map Map function over key-value pairs function
fun Function to apply to each {key, value} pair function
t Source table table
returns Mapped array array
f.join Join array elements with separator function
array Array to join table
sep Separator string string
returns Joined string string
f.partial Partial application - pre-fill function arguments function
fun Function to partially apply function
... Arguments to pre-fill
returns New function with pre-filled arguments function
f.any Check if any element satisfies predicate function
fun Predicate function (key, value) -> boolean function
iterable Table to check table
returns boolean
f.all Check if all elements satisfy predicate function
fun Predicate function (key, value) -> boolean function
iterable Table to check table
returns boolean
f.if_nil Conditional based on nil value function
val Value to check any
was_nil Value to return if val is nil any
was_not_nil Value to return if val is not nil any
returns Appropriate value any
f.select_only Create function that selects nth argument function
n Argument index to select number
returns Function (...) -> nth_arg function
f.first Returns first argument (alias for select_only(1)) function
f.second Returns second argument (alias for select_only(2)) function
f.third Returns third argument (alias for select_only(3)) function
f.last Returns last argument function

plenary.fun (fun.lua)

Higher-order function utilities.

name arg name / returns description type
M.bind Alias for plenary.functional.partial function
M.arify Wrap function to enforce specific argument count function
fn Function to wrap function
argc Expected argument count number
returns Wrapped function that errors on argument count mismatch function
M.create_wrapper Create function wrapper that applies mapping to result function
map Function to apply to wrapped function's result function
returns Wrapper function function

plenary.path (path.lua)

Python-like pathlib implementation for filesystem operations.

Static Properties

name arg name / returns description type
Path.home Home directory path string
Path.sep Path separator (/ or \) string
Path.root Root directory function function

Constructor

name arg name / returns description type
Path:new Create a new Path object function
... Path segments (strings, tables, or Path objects)
returns Path instance Path

Instance Methods

name arg name / returns description type default
Path:joinpath Join path segments function
... Additional path segments
returns New Path Path
Path:absolute Get absolute path function
returns Absolute path string string
Path:exists Check if path exists function
returns boolean
Path:expand Expand ~, ., and $VAR in path function
returns Expanded path string string
Path:make_relative Make path relative to cwd function
cwd Base directory, defaults to current working directory string
returns Relative path string string
Path:normalize Normalize path, handling .. and redundant separators function
cwd Base directory string
returns Normalized path string string
Path:shorten Shorten path components function
len Length for shortened components number 1
exclude Indices to exclude from shortening table
returns Shortened path string string
Path:mkdir Create directory function
opts.mode File mode number 448
opts.parents Create parent directories boolean
opts.exists_ok Don't error if exists boolean true
returns boolean
Path:rmdir Remove directory if empty function
Path:rename Rename/move path function
opts.new_name New name/path string
returns Status
Path:copy Copy files or directories function
opts.destination Target path string|Path
opts.recursive Copy directories recursively boolean
opts.override Override existing files boolean true
opts.interactive Confirm before overriding boolean
opts.respect_gitignore Respect gitignore boolean
opts.hidden Include hidden files boolean true
opts.parents Create parent directories boolean
opts.exists_ok Merge existing directories boolean true
returns Table of copy results table
Path:touch Create empty file or update timestamp function
opts.mode File mode number 420
opts.parents Create parent directories boolean
returns boolean
Path:rm Remove file or directory function
opts.recursive Remove directories recursively boolean
Path:is_dir Check if path is a directory function
returns boolean
Path:is_file Check if path is a regular file function
returns boolean
Path:is_absolute Check if path is absolute function
returns boolean
Path:parent Get parent directory function
returns Path
Path:parents Get all parent directories function
returns Array of Paths array
Path:write Write to file function
txt Content to write string
flag Write mode ("w", "a", etc.) string
mode File mode number 438
Path:read Read file contents function
callback Async callback function
returns File contents string (sync) or nil (async) string nil
Path:readlines Read file as lines function
returns Array of strings array
Path:head Read first N lines function
lines Number of lines number 10
returns string
Path:tail Read last N lines function
lines Number of lines number 10
returns string
Path:readbyterange Read byte range from file function
offset Byte offset (can be negative) number
length Number of bytes to read number
returns string
Path:iter Create line iterator function
returns Iterator function function
Path:find_upwards Find file upwards from current path function
filename Filename to search for string
returns Path|nil

plenary.job (job.lua)

Process spawning and management wrapper around libuv.

Constructor

name arg name / returns description type default
Job:new Create new job function
o.command Command to execute string
o.args Arguments string[]
o.cwd Working directory string
o.env Environment variables table<string,string>|string[]
o.interactive Enable stdin boolean true
o.detached Spawn detached process boolean
o.skip_validation Skip executable validation boolean
o.enable_handlers Enable output handlers boolean true
o.enable_recording Record output boolean true
o.on_start Start callback function
o.on_stdout Stdout callback (err, data, self) -> nil function
o.on_stderr Stderr callback (err, data, self) -> nil function
o.on_exit Exit callback (self, code, signal) -> nil function
o.maximum_results Stop after N results number
o.writer Job that writes to stdin Job|table|string
returns Job instance Job

Instance Methods

name arg name / returns description type default
Job:start Start the job function
Job:sync Start and wait for job to complete function
timeout Timeout in ms number 5000
wait_interval Poll interval in ms number 10
returns Results table and exit code table, number
Job:wait Wait for job to complete function
timeout Timeout in ms number 5000
wait_interval Poll interval in ms number 10
should_redraw Redraw during wait boolean
returns self Job
Job:co_wait Wait in coroutine function
wait_time Wait interval in ms number 5
returns self Job
Job:result Get stdout results (requires enable_recording) function
returns Array of strings array
Job:stderr_result Get stderr results (requires enable_recording) function
returns Array of strings array
Job:pid Get process ID function
returns number
Job:shutdown Shutdown job function
code Exit code number
signal Signal number
Job:send Send data to stdin function
data Data to send string
Job:and_then Chain next job to start after this one function
next_job Next job to start Job
Job:and_then_wrap Chain next job with schedule wrap function
next_job Next job to start Job
Job:after Add callback on exit function
fn Callback function function
returns self Job
Job:and_then_on_success Chain job on success (exit code 0) function
next_job Next job to start Job
Job:and_then_on_success_wrap Chain job on success with schedule wrap function
next_job Next job to start Job
Job:after_success Add callback on success function
fn Callback function function
Job:and_then_on_failure Chain job on failure (non-zero exit code) function
next_job Next job to start Job
Job:and_then_on_failure_wrap Chain job on failure with schedule wrap function
next_job Next job to start Job
Job:after_failure Add callback on failure function
fn Callback function function
Job:add_on_exit_callback Add additional exit callback function
cb Callback function function

Static Methods

name arg name / returns description type
Job.join Wait for multiple jobs to complete function
... Jobs to wait for, optionally followed by timeout (number)
returns All completed boolean
Job.chain Chain multiple jobs sequentially function
... Jobs to chain
returns Request ID number
Job.chain_status Check chain completion status function
id Request ID from Job.chain number
returns boolean
Job.is_job Check if item is a Job function
item Item to check any
returns boolean

plenary.curl (curl.lua)

HTTP client wrapper using curl.

Common Request Options

All methods accept these options and return a response table.

name arg name / returns description type default
url Request URL string
method HTTP method (get, post, put, patch, delete, head) string
query URL query parameters table
body Request body string|table|filepath
headers Request headers table
auth Basic auth ("user:pass" or {"user", "pass"}) string|table
form Form data table
raw Additional curl arguments table
dry_run Return args without executing boolean
output Download destination filepath string
timeout Request timeout in ms number 10000
http_version HTTP version (HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, HTTP/3) string
proxy Proxy URL string
insecure Allow insecure server connections boolean
compressed Request compressed response (non-Windows default) boolean true
accept Accept header string
callback Async response callback function
stream Streaming stdout callback function
on_error Error callback function

Response Table

name arg name / returns description type
exit Shell exit code number
status HTTP status code number
headers Response headers array
body Response body string

Methods

name arg name / returns description type
M.get HTTP GET request function
url Request URL string
opts Additional options table
returns Response table or Job (if async) table|Job
M.post HTTP POST request function
url Request URL string
opts Additional options table
returns Response table or Job (if async) table|Job
M.put HTTP PUT request function
url Request URL string
opts Additional options table
returns Response table or Job (if async) table|Job
M.patch HTTP PATCH request function
url Request URL string
opts Additional options table
returns Response table or Job (if async) table|Job
M.delete HTTP DELETE request function
url Request URL string
opts Additional options table
returns Response table or Job (if async) table|Job
M.head HTTP HEAD request function
url Request URL string
opts Additional options table
returns Response table or Job (if async) table|Job
M.request Generic HTTP request with method in options function
opts Request options including method table
returns Response table or Job (if async) table|Job

plenary.json (json.lua)

JSON utilities for handling JSON with comments.

name arg name / returns description type default
M.json_strip_comments Strip JSON comments and optionally trailing commas function
jsonString JSON string with comments string
options Options table table
options.whitespace Replace comments with whitespace boolean true
options.trailing_commas Include trailing commas boolean false
returns Clean JSON string suitable for vim.fn.json_decode string

plenary.iterators (iterators.lua)

An adaptation of luafun for neovim with iterator utilities.

Constructor

name arg name / returns description type
iter Create an iterator from an object function
obj Object to iterate (table, function, string, or Iterator) any
param Optional iterator param any
state Optional iterator state any
returns Iterator instance Iterator
wrap Wrap iterator triplet into Iterator table function
gen Generator function any
param Iterator param any
state Iterator state any
returns Iterator instance Iterator
unwrap Unwrap Iterator metatable into iterator triplet function
self Iterator to unwrap Iterator
returns gen, param, state any, any, any

Instance Methods

name arg name / returns description type
Iterator:for_each Call function for each element function
fn Function to call for each element function
Iterator:stateful Convert to stateful iterator function
returns Stateful iterator Iterator
Iterator:map Map function over iterator function
fun Function to map over each element function
returns Mapped iterator Iterator
Iterator:flatten Recursively flatten nested iterator structure function
returns Flattened iterator Iterator
Iterator:filter Filter values function
fun Predicate function - keeps if returns true function
returns Filtered iterator Iterator
Iterator:enumerate Add index to values function
returns Iterator yielding (index, value) Iterator
Iterator:any Check if any value satisfies predicate function
fun Predicate function function
returns boolean
Iterator:all Check if all values satisfy predicate function
fun Predicate function function
returns boolean
Iterator:find Find value matching predicate or value function
val_or_fn Value to find or predicate function any|function
returns Found value or nil any
Iterator:fold Fold iterator into single value function
init Initial accumulator value any
fun Function (acc, val) -> acc function
returns Folded value any
Iterator:tolist Convert to list (first value only) function
returns Array of first values table
Iterator:tolistn Convert to list (all values) function
returns Array of value tables table
Iterator:tomap Convert to map function
returns Map from first value to second value table

Generators

name arg name / returns description type
range Create range iterator function
start Start value number
stop Stop value number
step Step value number
returns Range iterator Iterator
duplicate Create infinite iterator yielding arguments function
... Values to repeat
returns Infinite iterator Iterator
from_fun Create iterator from function function
fun Function to call function
returns Iterator of function results Iterator
zeros Create infinite iterator of zeros function
returns Infinite iterator yielding 0 Iterator
ones Create infinite iterator of ones function
returns Infinite iterator yielding 1 Iterator
rands Create infinite random iterator function
n Min value (or if m nil: 0 to n) number
m Max value number
returns Random value iterator Iterator
split Split string by separator function
input String to split string
sep Separator string
returns Iterator of substrings Iterator
words Split string by spaces function
input String to split string
returns Iterator of words Iterator
lines Split string by newlines function
input String to split string
returns Iterator of lines Iterator

Compositions

name arg name / returns description type
chain Chain multiple iterators function
... Iterators to chain
returns Combined iterator Iterator
zip Zip multiple iterators function
... Iterators to zip
returns Zipped iterator (truncated to shortest) Iterator

plenary.tbl (tbl.lua)

Table utilities.

name arg name / returns description type
tbl.apply_defaults Apply default values to table function
original Original table (modified in place) table
defaults Default values table
returns Modified original table
tbl.pack Pack arguments into table with n field function
... Arguments to pack
returns Packed table with n field table
tbl.unpack Unpack table with n field function
t Table to unpack table
i Start index number
j End index number
returns Unpacked values
tbl.freeze Freeze table to prevent modifications function
t Table to freeze table
returns Frozen table table

plenary.scandir (scandir.lua)

Directory scanning utilities with async support and gitignore handling.

name arg name / returns description type default
m.scan_dir Search directory recursively (sync) function
path Path or array of paths string|table
opts Options table table
opts.hidden Include hidden files boolean
opts.add_dirs Include directories in results boolean
opts.only_dirs Only include directories boolean
opts.respect_gitignore Respect gitignore files boolean
opts.depth Search depth number
opts.search_pattern Regex pattern, array of patterns, or filter function string|table|function
opts.on_insert Called for each element (entry, type) function
opts.silent Suppress inaccessible path messages boolean
returns Array of file paths array
m.scan_dir_async Search directory recursively (async) function
path Path or array of paths string|table
opts Options table table
opts.hidden Include hidden files boolean
opts.add_dirs Include directories in results boolean
opts.only_dirs Only include directories boolean
opts.respect_gitignore Respect gitignore files boolean
opts.depth Search depth number
opts.search_pattern Regex pattern, array of patterns, or filter function string|table|function
opts.on_insert Called for each element (entry, type) function
opts.on_exit Called on completion (results) function
opts.silent Suppress inaccessible path messages boolean
m.ls List directory contents (long format) function
path Path to list string
opts Options table table
opts.hidden Include hidden files boolean
opts.add_dirs Include directories in results boolean true
opts.respect_gitignore Respect gitignore files boolean
opts.depth Search depth number 1
opts.group_directories_first Group directories first boolean
returns Formatted output lines and sections array, table
m.ls_async List directory contents async (long format) function
path Path to list string
opts Options table table
opts.hidden Include hidden files boolean
opts.add_dirs Include directories in results boolean true
opts.respect_gitignore Respect gitignore files boolean
opts.depth Search depth number 1
opts.group_directories_first Group directories first boolean
opts.on_exit Called on completion (results) function

plenary.class (class.lua)

Classic OOP class system.

name arg name / returns description type
Object:new Initialize new instance (override for custom init) function
returns New instance Object
Object:extend Create subclass function
returns New subclass with super field Object
Object:implement Mixin other classes/functions function
... Classes/tables to implement
Object:is Check if object is instance of class function
T Class to check against Object
returns boolean
Object:__tostring String representation (override for custom) function
returns Default: "Object" string
Object:__call Create instance without using new function

plenary.log (log.lua)

Logging library with console, file, and quickfix output.

name arg name / returns description type default
log.new Create new logger function
config Configuration options table
config.plugin Plugin name prepended to messages string "plenary"
config.use_console Output to console: "sync", "async", or false string|boolean "async"
config.highlights Use highlighting in console boolean true
config.use_file Write to log file boolean true
config.outfile Custom log file path string
config.use_quickfix Write to quickfix list boolean
config.level Minimum log level (trace/debug/info/warn/error/fatal) string "info"
config.modes Level configurations table
config.float_precision Float precision number 0.01
config.fmt_msg Custom message formatter function
standalone Return standalone logger or attach to config boolean
returns Logger object table|Object

Logger Methods

For each log level (trace, debug, info, warn, error, fatal):

name arg name / returns description type
logger.{level} Log message at level function
... Values to log
logger.fmt_{level} Log formatted message function
fmt Format string string
... Values for format
logger.lazy_{level} Log lazily evaluated function function
fn Function to call if logging function
logger.file_{level} Log to file only function
vals Values to log table
override Override options table

plenary.reload (reload.lua)

Module reloading utilities.

name arg name / returns description type default
reload.reload_module Reload Lua module(s) function
module_name Module name to reload string
starts_with_only Match modules starting with name boolean true

plenary.filetype (filetype.lua)

Filetype detection from extension, filename, shebang, and modeline.

name arg name / returns description type default
filetype.add_table Add filetype mappings function
new_filetypes Table with extension, file_name, or shebang keys table
filetype.add_file Load filetype definitions from runtime file function
filename Filename without path (e.g., "base", "builtin") string
filetype.detect Detect filetype from filepath function
filepath Path to file string
opts Options table
opts.fs_access Check file if exists boolean true
returns Detected filetype string

Internal Detection Methods

name arg name / returns description type
filetype.detect_from_extension Detect from file extension function
filepath File path string
returns Filetype string
filetype.detect_from_name Detect from filename function
filepath File path string
returns Filetype string
filetype.detect_from_shebang Detect from shebang line function
filepath File path string
returns Filetype string
filetype.detect_from_modeline Detect from vim modeline function
filepath File path string
returns Filetype string

plenary.busted (busted.lua)

Busted-style testing framework.

name arg name / returns description type
mod.describe Define test suite function
desc Suite description string
func Suite function function
mod.inner_describe Define nested test suite function
desc Suite description string
func Suite function function
mod.it Define test case function
desc Test description string
func Test function function
mod.pending Define pending test function
desc Test description string
func Test function (optional) function
mod.before_each Run before each test in current suite function
fn Function to run function
mod.after_each Run after each test in current suite function
fn Function to run function
mod.clear Clear current buffer function
mod.format_results Print test results summary function
res Results object with pass/fail/errs arrays table
mod.run Run test file function
file Path to test file string

Global Functions

name arg name / returns description type
describe Alias for mod.describe function
it Alias for mod.it function
pending Alias for mod.pending function
before_each Alias for mod.before_each function
after_each Alias for mod.after_each function
clear Alias for mod.clear function
print Shadowed print function for reliable output function
... Values to print

plenary.async (async/init.lua)

Async utilities for Neovim. API is still under construction and may change.

name arg name / returns description type
uv Libuv async operations module
util Async utility functions module
lsp LSP async operations module
api Async API functions module
tests Async testing utilities module
control Async control structures module
tests.add_globals Add async test globals to environment function
tests.add_to_env Add async test functions to environment function

plenary.async.async (async/async.lua)

Core async wrapper utilities.

name arg name / returns description type
M.wrap Creates an async function with a callback style function function
func A callback style function to be converted. The last argument must be the callback function
argc The number of arguments of func. Must be included number
returns Returns an async function function
M.is_leaf_function Check if function is a leaf async function function
async_func Async function to check function
returns boolean
M.get_leaf_function_argc Get argument count of leaf function function
async_func Async function function
returns Argument count number
M.run Execute a future with a callback when it is done, or run a future with a callback in a non async context function
async_function Future: the future to execute function
callback The callback to call when done function
M.void Create a function which executes in an async context but called from a non-async context. Cannot return anything since it is non-blocking function
func Function to wrap function
returns Wrapped function function

plenary.async.control (async/control.lua)

Async control structures including condvars, semaphores, and channels.

Condvar

name arg name / returns description type
Condvar.new Create a new condition variable function
returns Condvar
Condvar.wait Blocks the thread until a notification is received function
Condvar.notify_all Notify everyone that is waiting on this Condvar function
Condvar.notify_one Notify randomly one person that is waiting on this Condvar function

Semaphore

name arg name / returns description type
Semaphore.new Create a new semaphore function
initial_permits The number of permits that it can give out number
returns Semaphore
Semaphore.acquire Acquire a permit (async function, blocks until a permit can be acquired) function
returns Permit object table

Channel

name arg name / returns description type
channel.oneshot Creates a oneshot channel. Returns a sender and receiver function. The sender is not async while the receiver is function
returns sender function, receiver function function, function
channel.counter A counter channel. A channel that you want to use only to notify and not to send any actual values function
returns Sender table, Receiver table table, table
channel.mpsc A multiple producer single consumer channel function
returns Sender table, Receiver table table, table

plenary.async.structs (async/structs.lua)

Async data structures.

Deque

name arg name / returns description type
Deque.new Create a new double ended queue function
returns Deque
Deque.pushleft Push to left of deque function
value Value to push any
Deque.pushright Push to right of deque function
value Value to push any
Deque.popleft Pop from left of deque function
returns any
Deque.popright Pop from right of deque function
returns any
Deque.is_empty Check if deque is empty function
returns boolean
Deque.len Return number of elements of deque function
returns number
Deque.ipairs_left Return an iterator of indices and values starting from the left function
returns function
Deque.ipairs_right Return an iterator of indices and values starting from the right function
returns function
Deque.clear Remove all values from deque function

plenary.async.util (async/util.lua)

Async utility functions.

name arg name / returns description type default
util.sleep Sleep for milliseconds function
ms Milliseconds to sleep number
util.block_on Completely block neovim waiting for async function to complete. Please just use util.run unless you have a very special usecase function
async_function Future function
timeout Stop blocking if timeout was surpassed number 2000
util.will_block Returns a function that will block on async function function
async_function Future function
timeout Timeout number
returns function
util.join Join multiple async functions, wait for all to complete function
async_fns Array of async functions table
returns Array of results table
util.run_first Returns a result from async function that finishes first function
async_functions The futures that you want to select table
returns ...
util.race Returns a result from functions that finishes first function
funcs The async functions that you want to select table
returns ...
util.run_all Run all async functions and call callback when done function
async_fns Array of async functions table
callback Callback function function
util.apcall Protected call for async functions function
async_fn Async function function
... Arguments
returns success status, result boolean, any
util.protected Wrap async function to always return success, result tuple function
async_fn Async function function
returns Wrapped function function
util.scheduler Async function that when called will yield to neovim scheduler to be able to call the API function

plenary.async.uv_async (async/uv_async.lua)

Async wrappers for libuv operations.

name arg name / returns description type
close Close a handle function
fs_open Open a file function
fs_read Read a file function
fs_close Close a file function
fs_unlink Delete a file function
fs_write Write to a file function
fs_mkdir Create a directory function
fs_mkdtemp Create a temporary directory function
fs_rmdir Remove a directory function
fs_scandir Scan a directory function
fs_stat Get file status function
fs_fstat Get file status (by fd) function
fs_lstat Get file status (don't follow symlinks) function
fs_rename Rename a file function
fs_fsync Sync file to disk function
fs_fdatasync Sync file data to disk function
fs_ftruncate Truncate a file function
fs_sendfile Send file data function
fs_access Check file access permissions function
fs_chmod Change file mode function
fs_fchmod Change file mode (by fd) function
fs_utime Change file access/modification times function
fs_futime Change file access/modification times (by fd) function
fs_link Create a hard link function
fs_symlink Create a symbolic link function
fs_readlink Read symbolic link function
fs_realpath Get canonical path function
fs_chown Change file owner function
fs_fchown Change file owner (by fd) function
fs_copyfile Copy a file function
fs_opendir Open a directory function
fs_readdir Read directory entries function
fs_closedir Close a directory function
shutdown Shutdown a connection function
listen Start listening for connections function
write Write data to stream function
write2 Write data to stream function
tcp_connect Connect to TCP server function
pipe_connect Connect to pipe function
udp_send Send UDP data function
udp_recv_start Start receiving UDP data function
getaddrinfo DNS address lookup function
getnameinfo DNS reverse lookup function

plenary.benchmark (benchmark/init.lua)

Benchmarking utilities for measuring function performance.

name arg name / returns description type default
bench Benchmark a function or group of functions function
name Benchmark name string
opts Options table table
opts.warmup Number of initial runs before starting to track time number 3
opts.runs Number of runs to make number 5
opts.fun Functions to execute (array of {name, function} pairs) table
returns Results array table

plenary.collections.py_list (collections/py_list.lua)

Python-like list implementation.

name arg name / returns description type
List.new List constructor. Can be used in higher order functions function
tbl A list-like table containing the initial elements of the list table
returns A new list object List
List.is_list Checks whether the argument is a List object function
tbl The object to test table
returns Whether tbl is an instance of List boolean
List.push Pushes the element to the end of the list function
other The object to append any
List.pop Pops the last element off the list and returns it function
returns The (previously) last element from the list any
List.insert Inserts other into the specified idx function
idx The index that other will be inserted to number
other The element to insert any
List.remove Removes the element at index idx and returns it function
idx The index of the element to remove number
returns The element previously at index idx any
List.equal Compare elements with any list-like table. It only checks for shallow equality function
other The element to test for any
returns True if other is a list object and all it's elements are equal boolean
List.deep_equal Checks for deep equality between lists. Uses vim.deep_equal for testing function
other The element to test for any
returns True if all elements and their children are equal boolean
List.slice Returns a copy of the list with elements between a and b, inclusive function
a The low end of the slice number
b The high end of the slice number
returns A list with elements between a and b List
List.copy Similar to slice, but with every element. Makes a shallow copy function
returns A slice from 1 to #self, i.e., a complete copy of the list List
List.deep_copy Similar to copy, but makes a deep copy instead function
returns A deep copy of the object List
List.reverse Reverses the list in place function
returns The list itself, so you can chain method calls List
List.join Concatenates the elements within the list separated by the given string function
sep The separator to place between the elements. Default '' string
returns The elements in the list separated by sep string
List.concat Returns a list with the elements of self concatenated with those in the given arguments function
... The sequences to concatenate to this one table|List
returns List
List.move Moves the elements between from and from+len in self, to positions between to and to+len in other function
from The first index of the origin slice number
len The length of the slices number
to The first index of the destination slice number
other The destination list. Defaults to self table|List
List.pack Packs the given elements into a list. Similar to lua 5.3's table.pack function
... The elements to pack any
returns A list containing all the given elements List
List.unpack Unpacks the elements from this list and returns them function
returns All the elements from self[1] to self[#self] ...any
List.count Counts occurrences of e inside the list function
e The element to test for any
returns The number of occurrences of e number
List.extend Appends the elements in given iterator to the list function
other An iterator object table
List.contains Checks whether there is an occurrence of given element in the list function
e The object to test for any
returns True if e is present boolean
List.iter Creates an iterator for the list function
returns An iterator object table
List.riter Creates a reverse iterator for the list function
returns An iterator object table
List.from_iter Create a list from elements pointed at by the given iterator function
iter An iterator object table
returns List

plenary.lsp.override (lsp/override.lua)

LSP callback override utilities.

name arg name / returns description type
override.override Override an lsp method default callback function
method LSP method name string
new_function New callback function function
override.get_original_function Get original method callback, useful if you only want to override in some circumstances function
method LSP method name string
returns Original function function

plenary.popup (popup/init.lua)

Popup window API wrapper for Neovim.

name arg name / returns description type default
popup.create Create a popup window function
what Buffer number or lines to display (string or table) number|string|table
vim_options Options table table
vim_options.width Popup width number
vim_options.height Popup height number
vim_options.line Line position (number or "cursor±N") number|string
vim_options.col Column position (number or "cursor±N") number|string
vim_options.pos Position anchor (topleft, topright, botleft, botright, center) string
vim_options.padding List with numbers defining padding above/right/below/left table
vim_options.border List with numbers defining border thickness or boolean table|boolean
vim_options.borderchars List with characters defining border characters table
vim_options.title Popup title text string
vim_options.highlight Popup highlight group string
vim_options.borderhighlight Border highlight group string
vim_options.titlehighlight Title highlight group string
vim_options.time Auto-close after N milliseconds number
vim_options.enter Enter popup after creation boolean true
vim_options.cursorline Enable cursorline boolean
vim_options.wrap Enable wrapping boolean
vim_options.focusable Window is focusable boolean false
vim_options.moved Close when cursor moves ("any", "word", etc.) string
vim_options.posinvert Invert position if doesn't fit boolean true
vim_options.zindex Window z-index priority number 50
vim_options.noautocmd Disable autocmds boolean true
vim_options.callback Callback on Enter key press function
vim_options.finalize_callback Callback after creation function
returns Window ID and popup info table number, table
popup.move Move popup with window id to new position/size function
win_id Window ID number
vim_options Options for position/size (line, col, height, width, etc.) table
popup.execute_callback Execute the callback registered for a buffer function
bufnr Buffer number number

plenary.window.border (window/border.lua)

Border window utilities for popups.

name arg name / returns description type
Border.new Create a new border window function
content_bufnr Content buffer number number
content_win_id Content window ID number
content_win_options Content window options table
border_win_options Border window options table
returns Border
Border.move Set size and position of border function
content_win_options Content window options table
border_win_options Border window options table
Border.change_title Change the border title function
new_title New title text string
pos Title position (NW, N, NE, SW, S, SE) string

plenary.window.float (window/float.lua)

Floating window utilities.

name arg name / returns description type default
float.centered Create a centered floating window function
options Options table table
options.bufnr Buffer to use (creates new if not provided) number
options.percentage Percentage of screen size to use number 0.9
options.winblend Window transparency level number 15
returns Table with bufnr and win_id table
float.centered_with_top_win Create a centered floating window with a top window function
top_text Array of lines for top window table
options Options table table
returns Table with bufnr, win_id, minor_bufnr, minor_win_id table
float.percentage_range_window Create window that takes up certain percentages of current screen function
col_range Column range (number or [start, end]) number|table
row_range Row range (number or [start, end]) number|table
win_opts Window options table
border_opts Border options table
returns Table with bufnr, win_id, border_bufnr, border_win_id table
float.clear Clear/Close floating windows associated with buffer function
bufnr Buffer number number

plenary.vararg.rotate (vararg/rotate.lua)

Vararg rotation utilities. Do not edit, generated file.

name arg name / returns description type
rotate Rotate a lua vararg (move first argument to end) function
nargs Number of arguments number
... Arguments to rotate any
returns Rotated arguments ...any

plenary.profile.lua_profiler (profile/lua_profiler.lua)

Lua profiler for measuring function execution times.

name arg name / returns description type
module.start Start profiling function
module.stop Stop profiling function
module.report Write profile report to file function
filename Output filename string
module.attachPrintFunction Attach a print function to receive profile output function
fn Print function function
verbose Enable verbose output boolean

plenary.profile.p (profile/p.lua)

LuaJIT profiler command line interface.

name arg name / returns description type
start Start profiling with optional mode and output file function
mode Profiler mode (see module documentation for options) string
outfile Output file path string
stop Stop profiling and dump results function

Profiler dump features:

  • f - Stack dump: function name
  • F - Stack dump with module prefix
  • l - Stack dump: module:line
  • <number> - Stack dump depth
  • -<number> - Inverse stack dump depth
  • s - Split stack dump after first level
  • p - Show full path for module names
  • v - Show VM states
  • z - Show zones
  • r - Show raw sample counts
  • a/A - Annotate excerpts/complete source code files
  • G - Produce raw output for graphical tools
  • m<number> - Minimum sample percentage to show (default 3)
  • i<number> - Sampling interval in milliseconds (default 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment