robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1 2============================================================================== 3Lua module: vim.async *lua-async* *vim.async* 4 5Structured async API for Lua code that waits on event-loop work. 6 7`vim.async` lets Lua code wait for timers, callbacks, and other tasks without 8blocking Nvim's event loop. Async work runs inside tasks, which can pause at 9checkpoints and manage child tasks created while they are running. 10 11Start async work with |vim.async.run()|. Inside a task, use 12|vim.async.await()| to wait for callback-style APIs or other tasks without 13blocking the event loop. Use |vim.async.pawait()| when an awaited operation 14can fail and the current task should continue. 15 16Examples in this help use `local async = vim.async` for brevity. 17 18Example: run async work without blocking Nvim: >lua 19 local async = vim.async 20 21 async.run(function() 22 vim.notify('waiting...') 23 async.sleep(1000) 24 vim.notify('done') 25 end) 26< 27 28Example: await a callback-style API. Callback results are returned unchanged, 29so an error-first callback still returns `err, value`: >lua 30 local async = vim.async 31 32 async.run(function() 33 local err, stat = async.await(2, fs_stat, 'notes.txt') 34 if err then 35 error(err, 0) 36 end 37 print(('notes.txt is %d bytes'):format(stat.size)) 38 end) 39< 40 41A task has two roles: 42• it is a handle that can be awaited, waited for, or closed 43• it is a scope for child tasks created while the task is running 44 45|vim.async.run()| creates a task. A top-level task starts immediately. A task 46created while another task is running becomes a child of that task, and its 47function starts when the parent reaches its next checkpoint. A parent task 48finishes only after its attached children finish. If a child fails without 49being handled, the parent fails and closes the remaining children. 50 51Use |Task:detach()| for background work that should keep running after the 52current task finishes. A detached task becomes top-level work; the original 53parent no longer waits for it or closes it. 54 55Awaiting a task observes that task's result; it does not attach the task to 56the awaiter or change which task owns it. Ownership is decided when the task 57is created. 58 59Scheduling is cooperative. When a task awaits a timer, I/O operation, 60callback, or another task, `vim.async` saves the Lua stack and returns control 61to the event loop. Other callbacks can run while the task is paused. Nothing 62interrupts synchronous Lua code in the middle of a stack frame. 63 64Checkpoints are the places where a task can pause, start pending child tasks, 65observe cancellation, and receive unhandled child failures. Inside a task, 66these operations are checkpoints: 67• `vim.async.await(...)` 68• `vim.async.pawait(...)` 69• `vim.async.checkpoint()` 70• successful return from the task function, which is the final checkpoint for 71 child management 72 73Convenience APIs such as |vim.async.sleep()| and |vim.async.timeout()| can 74also checkpoint because they call checkpointing APIs internally. 75 76Closing a task closes its attached children. Cancellation is cooperative: 77|Task:close()| marks a task as closing, and the task observes that state at a 78checkpoint. If a task is suspended on a closable operation such as a timer or 79child task, `vim.async` closes that operation before reporting the 80cancellation. 81 82Use |vim.async.await()| inside a task to suspend until work completes. It 83accepts a task, a callback-taking function, or an argument position plus a 84callback-taking function. `await(task)` returns the task result or raises the 85task failure. |vim.async.pawait()| is the async counterpart to `pcall()` for 86recoverable awaited-operation failures; it returns `ok, ...` instead of 87failing the current task for that awaited operation. It does not suppress 88cancellation or a failure already pending on the current task. 89 90From synchronous code, use |Task:wait()| or |Task:pwait()| to pump the event 91loop until the task completes. Use |Task:on_complete()| to observe completion 92without blocking. 93 94Coordination helpers work with task handles. |vim.async.iter()| yields 95completed task handles in completion order, |vim.async.timeout()| awaits a 96task with a deadline, and `vim.async.semaphore(permits)` creates a 97|vim.async.Semaphore| that limits how many tasks can hold a permit for a 98section at once. 99 100 101*vim.async.Closable* 102 103 Fields: ~ 104 • {close} (`fun(self, callback?: fun())`) 105 • {is_closing}? (`fun(self): boolean`) 106 107*vim.async.Semaphore* 108 A semaphore manages an internal permit counter. |Semaphore:acquire()| 109 consumes one permit and |Semaphore:release()| returns one permit. If no 110 permits are available, `acquire()` suspends the current task until another 111 task releases one. 112 113 The preferred way to use a Semaphore is with the `with()` method, which 114 automatically acquires and releases the semaphore around a function call. 115 This is useful for limiting sections that start external work and then 116 await it, such as file reads, requests, or subprocesses. >lua 117 local async = vim.async 118 119 async.run(function() 120 local limit = async.semaphore(4) 121 local tasks = {} 122 123 for _, path in ipairs(paths) do 124 table.insert(tasks, async.run(function() 125 return limit:with(function() 126 return read_file(path) 127 end) 128 end)) 129 end 130 131 local next_task = async.iter(tasks) 132 while true do 133 local task = next_task() 134 if task == nil then 135 break 136 end 137 async.await(task) 138 end 139 end) 140< 141 142 Fields: ~ 143 • {acquire} (`fun(self: vim.async.Semaphore)`) See 144 |Semaphore:acquire()|. 145 • {release} (`fun(self: vim.async.Semaphore)`) See 146 |Semaphore:release()|. 147 • {with} (`fun(self: vim.async.Semaphore, fn: async fun(): R...): R...`) 148 See |Semaphore:with()|. 149 150*vim.async.Task* 151 Extends: |vim.async.Closable| 152 153 A coroutine-backed async operation and concurrency scope. 154 155 Use |vim.async.run()| to create tasks. A task may be awaited by more than 156 one waiter. When a task is created inside another task, it is attached to 157 that parent and becomes part of the parent's concurrency scope. 158 159 Fields: ~ 160 • {close} (`fun(self: vim.async.Task, callback: fun()?)`) See 161 |Task:close()|. 162 • {completed} (`fun(self: vim.async.Task): boolean`) See 163 |Task:completed()|. 164 • {detach} (`fun(self: vim.async.Task): vim.async.Task<R>`) See 165 |Task:detach()|. 166 • {name}? (`string`) Name of the task 167 • {on_complete} (`fun(self: vim.async.Task, callback: fun(err?: any, ...: R...)): fun()`) 168 See |Task:on_complete()|. 169 • {pwait} (`fun(self: vim.async.Task, timeout: integer?): boolean, R...`) 170 See |Task:pwait()|. 171 • {raise_on_error} (`fun(self: vim.async.Task): vim.async.Task<R>`) See 172 |Task:raise_on_error()|. 173 • {status} (`fun(self: vim.async.Task): "running"|"awaiting"|"normal"|"completed"`) 174 See |Task:status()|. 175 • {traceback} (`fun(self: vim.async.Task, msg: string?, level: integer?): string`) 176 See |Task:traceback()|. 177 • {wait} (`fun(self: vim.async.Task, timeout: integer?): R...`) 178 See |Task:wait()|. 179 180 181await({...}) *vim.async.await()* 182 Suspend the current task until an awaitable completes. 183 184 Accepts a task, a callback-taking function, or an argument position plus a 185 callback-taking function. Raises awaited errors and current task-control 186 errors. 187 188 The callback forms return callback arguments unchanged: >lua 189 local async = vim.async 190 191 async.run(function() 192 local err, stat = async.await(2, vim.uv.fs_stat, 'notes.txt') 193 if err then 194 error(err, 0) 195 end 196 print(stat.size) 197 end) 198< 199 200 If a callback API starts cancellable work, return a closable handle from 201 the await callback. |Task:close()| will close that handle if cancellation 202 arrives while the task is suspended there. >lua 203 local async = vim.async 204 205 async.run(function() 206 local lines = async.await(function(done) 207 return start_read_lines('notes.txt', done) 208 end) 209 render(lines) 210 end) 211< 212 213 Parameters: ~ 214 • {...} (`any`) see overloads 215 216 Overloads: ~ 217 • `async fun(func: (fun(callback: fun(...: R...)): vim.async.Closable?)): R...` 218 • `async fun(argc: integer, func: (fun(...: T..., callback: fun(...: R...)): vim.async.Closable?), ...: T...): R...` 219 • `async fun(task: vim.async.Task<R>): R...` 220 221 Return: ~ 222 (`R...`) 223 224checkpoint() *vim.async.checkpoint()* 225 Start pending child tasks and deliver pending cancellation or task failure 226 from the current task. 227 228 This does not yield to the event loop. 229 230 Use this after cleanup code that catches an async failure or close signal, 231 so persistent task state is delivered again before normal execution 232 continues. >lua 233 local ok, err = pcall(cleanup_sensitive_work) 234 cleanup_resources() 235 vim.async.checkpoint() 236 if not ok then 237 error(err, 0) 238 end 239< 240 241is_closing() *vim.async.is_closing()* 242 Returns true if the current task has been closed. 243 244 Can be used in an async function to do cleanup when a task is closing. >lua 245 while not vim.async.is_closing() do 246 poll_once() 247 vim.async.sleep(1000) 248 end 249< 250 251 Return: ~ 252 (`boolean`) 253 254iter({tasks}) *vim.async.iter()* 255 Iterate completed tasks in completion order. 256 257 The iterator yields task handles, not task results. Use 258 |vim.async.await()| or |vim.async.pawait()| to retrieve each result. The 259 tasks are observed in the order they complete, regardless of the order in 260 the input list. >lua 261 local async = vim.async 262 263 async.run(function() 264 local tasks = { 265 async.run(function() return 'cache', read_cache() end):detach(), 266 async.run(function() return 'disk', read_file() end):detach(), 267 } 268 269 for task in async.iter(tasks) do 270 local ok, source, text = async.pawait(task) 271 if ok then 272 for _, other in ipairs(tasks) do 273 if other ~= task then 274 other:close() 275 end 276 end 277 print(('loaded from %s'):format(source)) 278 return text 279 end 280 end 281 end) 282< 283 284 If code must support PUC Lua 5.1, use the direct-call form instead of a 285 generic `for` loop. The iterator may need to suspend while waiting for the 286 next completed task, and PUC Lua 5.1 cannot yield from a generic-for 287 iterator call. >lua 288 local next_task = async.iter(tasks) 289 while true do 290 local task = next_task() 291 if task == nil then 292 break 293 end 294 async.await(task) 295 end 296< 297 298 Parameters: ~ 299 • {tasks} (`vim.async.Task<R>[]`) A list of tasks to wait for and 300 iterate over. 301 302 Return: ~ 303 (`async fun(): vim.async.Task<R>?`) iterator that yields each 304 completed task. 305 306pawait({...}) *vim.async.pawait()* 307 Protected await. 308 309 Async counterpart to `pcall()`. Accepts the same forms as 310 |vim.async.await()|, but returns a leading `ok` boolean for 311 awaited-operation failures. 312 313 Use this when the awaited task or operation is allowed to fail and the 314 current task should continue. Cancellation or already pending failure from 315 the current task is not protected. >lua 316 local async = vim.async 317 318 async.run(function() 319 local ok, text_or_err = async.pawait(async.run(read_file, 'notes.txt')) 320 if not ok then 321 text_or_err = '' 322 end 323 324 show_buffer(text_or_err) 325 end) 326< 327 328 Parameters: ~ 329 • {...} (`any`) see overloads 330 331 Overloads: ~ 332 • `async fun(func: (fun(callback: fun(...: R...)): vim.async.Closable?)): boolean, R...` 333 • `async fun(argc: integer, func: (fun(...: T..., callback: fun(...: R...)): vim.async.Closable?), ...: T...): boolean, R...` 334 • `async fun(task: vim.async.Task<R>): boolean, R...` 335 336 Return (multiple): ~ 337 (`boolean`) ok 338 (`R...`) ... result or error 339 (`_overload`) true 340 (`R...`) 341 (`_overload`) false 342 (`any`) 343 344run({func}, {...}) *vim.async.run()* 345 Create a task from an async function. 346 347 Top-level tasks start immediately. Child tasks are attached immediately 348 and first run when their parent reaches a checkpoint. 349 350 Creating a task decides ownership. Awaiting the task later only observes 351 its result; it does not attach the task to the awaiter. >lua 352 local async = vim.async 353 354 async.run(function() 355 local child = async.run(function() 356 return read_file('notes.txt') 357 end) 358 359 local text = async.await(child) 360 show_buffer(text) 361 end) 362< 363 364 A task created from synchronous code is top-level: >lua 365 local task = vim.async.run(function() 366 vim.async.sleep(100) 367 return 'done' 368 end) 369 370 print(task:wait()) 371< 372 373 Parameters: ~ 374 • {func} (`async fun(...: T...): R...`) 375 • {...} (`T...`) Arguments to pass to the function 376 377 Overloads: ~ 378 • `fun(name: string, func: async fun(...: T...), ...: T...): vim.async.Task<R...>` 379 380 Return: ~ 381 (`vim.async.Task<R...>`) 382 383semaphore({permits}) *vim.async.semaphore()* 384 Create an async semaphore that allows up to a given number of 385 acquisitions. 386 387 Prefer |Semaphore:with()| for most uses so permits are released reliably. 388 Use |Semaphore:acquire()| and |Semaphore:release()| directly only when the 389 acquire and release points cannot be expressed as one function call. 390 391 Parameters: ~ 392 • {permits} (`integer?`) (default: 1) 393 394 Return: ~ 395 (`vim.async.Semaphore`) 396 397Semaphore:acquire() *Semaphore:acquire()* 398 Acquire a semaphore permit. 399 400 If the internal counter is greater than zero, decrement it by `1` and 401 return immediately. If it is `0`, wait until |Semaphore:release()| is 402 called. 403 404Semaphore:release() *Semaphore:release()* 405 Release a semaphore permit. 406 407 Increments the internal counter by `1` and can wake a task waiting in 408 |Semaphore:acquire()|. 409 410 Calling this more times than permits were acquired raises an error. 411 412Semaphore:with({fn}) *Semaphore:with()* 413 Executes a function while holding one semaphore permit. 414 415 This acquires the semaphore before running the function and releases it 416 after the function completes, even if it errors or the current task is 417 closed. 418 419 Parameters: ~ 420 • {fn} (`async fun(): R...`) Function to execute within the semaphore's 421 context. 422 423 Return: ~ 424 (`R...`) Result(s) of the executed function. 425 426sleep({duration}) *vim.async.sleep()* 427 Asynchronously sleep for a given duration. 428 429 Suspends the current task for the given duration without blocking the 430 event loop. After the delay and timer cleanup complete, `sleep()` returns 431 to its caller through the runtime's `schedule` hook. >lua 432 vim.async.run(function() 433 vim.async.sleep(100) 434 vim.notify('resumed later') 435 end) 436< 437 438 Parameters: ~ 439 • {duration} (`integer`) ms 440 441Task:close({callback}) *Task:close()* 442 Request cooperative close for the task and all of its children. 443 444 The optional callback observes task completion and may run immediately if 445 the task has already completed. 446 447 Closing is cooperative. The task observes the close request at a 448 checkpoint such as |vim.async.await()| or |vim.async.checkpoint()|. If the 449 task is suspended on an owned closable operation, that operation is closed 450 before the task reports `"closed"`. 451 452 Parameters: ~ 453 • {callback} (`fun()?`) 454 455Task:completed() *Task:completed()* 456 Returns whether the Task has completed. 457 458 Return: ~ 459 (`boolean`) 460 461Task:detach() *Task:detach()* 462 Detach a task from its parent. 463 464 The task becomes a top-level task. If it was waiting for a parent 465 checkpoint, it is scheduled to start. 466 467 Use this for background work that should not be cancelled when the current 468 task finishes. Detached task failures no longer fail the original parent, 469 so observe them explicitly with |Task:on_complete()|, |Task:wait()|, or 470 |vim.async.await()|. >lua 471 vim.async.run(function() 472 while true do 473 refresh_index() 474 vim.async.sleep(1000) 475 end 476 end):detach() 477< 478 479 Return: ~ 480 (`vim.async.Task<R>`) 481 482Task:on_complete({callback}) *Task:on_complete()* 483 Add a callback to be run when the Task has completed. 484 485 If the Task is already done when this method is called, the callback is 486 called immediately with the results. 487 488 This only observes completion. It does not start a pending task. 489 490 Parameters: ~ 491 • {callback} (`fun(err?: any, ...: R...)`) 492 493 Return: ~ 494 (`fun()`) unsubscribe 495 496Task:pwait({timeout}) *Task:pwait()* 497 Protected-call version of |Task:wait()|. 498 499 Equivalent to `pcall(task.wait, task, timeout)`. >lua 500 local ok, result_or_err = task:pwait(1000) 501 if not ok then 502 vim.notify(tostring(result_or_err), vim.log.levels.ERROR) 503 end 504< 505 506 Parameters: ~ 507 • {timeout} (`integer?`) 508 509 Return (multiple): ~ 510 (`boolean`) 511 (`R...`) 512 513Task:raise_on_error() *Task:raise_on_error()* 514 Raise this task's error when it completes. 515 516 Use this for detached or top-level fire-and-forget tasks whose completion 517 will not otherwise be observed. Attached task errors already propagate to 518 their parent. 519 520 Detached tasks do not raise errors automatically. Detaching changes 521 ownership only; their completion can still be handled with 522 |vim.async.await()|, |Task:wait()|, |Task:pwait()|, or 523 |Task:on_complete()|. 524 525 Return: ~ 526 (`vim.async.Task<R>`) self 527 528Task:status() *Task:status()* 529 Returns the status of the task: 530 • `"running"`: task is currently executing Lua code 531 • `"normal"`: task is active but another coroutine is running 532 • `"awaiting"`: task is suspended at a checkpoint or waiting for children 533 • `"completed"`: task and all attached children have completed 534 535 Return: ~ 536 (`"running"|"awaiting"|"normal"|"completed"`) 537 538Task:traceback({msg}, {level}) *Task:traceback()* 539 Get the traceback of a task when it is not active. Will also get the 540 traceback of nested tasks. 541 542 Parameters: ~ 543 • {msg} (`string?`) 544 • {level} (`integer?`) 545 546 Return: ~ 547 (`string`) traceback 548 549Task:wait({timeout}) *Task:wait()* 550 Synchronously wait for the Task to complete. 551 552 If a timeout is provided, waits for the given time in milliseconds before 553 failing with `"timeout"`. With no timeout, waits indefinitely. 554 555 This is for synchronous code. Inside a task, prefer |vim.async.await()| so 556 the current task suspends instead of pumping the event loop itself. >lua 557 local result = task:wait(10) -- wait for 10ms or raise "timeout" 558 559 local result = task:wait() -- wait indefinitely 560< 561 562 Parameters: ~ 563 • {timeout} (`integer?`) 564 565 Return: ~ 566 (`R...`) 567 568timeout({duration}, {task}) *vim.async.timeout()* 569 Await a task with a timeout. 570 571 If the task completes first, returns or raises the task result as 572 |vim.async.await()| would. If the deadline wins, closes the task and 573 raises `"timeout"` after the target task finishes cancellation cleanup. >lua 574 local async = vim.async 575 576 async.run(function() 577 local task = async.run(read_file, 'notes.txt') 578 local text = async.timeout(5000, task) 579 show_buffer(text) 580 end) 581< 582 583 Parameters: ~ 584 • {duration} (`integer`) Timeout duration in milliseconds 585 • {task} (`vim.async.Task<R>`) 586 587 Return: ~ 588 (`R...`) 589 590wrap({argc}, {func}) *vim.async.wrap()* 591 Create an async function from a callback-style function. 592 593 The callback is inserted at argument position `argc`. If `func` returns a 594 closable handle, it is closed when the awaiting task is cancelled. 595 596 This is a reusable wrapper around |vim.async.await()|. Use it when the 597 same callback API is awaited from more than one place. >lua 598 local async = vim.async 599 local fs_stat = async.wrap(2, vim.uv.fs_stat) 600 601 async.run(function() 602 local err, stat = fs_stat(vim.api.nvim_buf_get_name(0)) 603 if not err and stat then 604 print(stat.size) 605 end 606 end) 607< 608 609 Parameters: ~ 610 • {argc} (`integer`) 611 • {func} (`fun(...: T..., callback: fun(...: R...)): vim.async.Closable?`) 612 613 Return: ~ 614 (`async fun(...: T...): R...`) 615 616 617 vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: