From 18766e742bdc8d179ff73b739a530052c9a669e5 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 8 Aug 2022 06:07:59 +0800 Subject: fix(folds): fix fold remains when :delete makes buffer empty (#19673) --- src/nvim/change.c | 8 ++++---- test/functional/ui/fold_spec.lua | 7 +++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/nvim/change.c b/src/nvim/change.c index c063ece907..f0ca5f3af3 100644 --- a/src/nvim/change.c +++ b/src/nvim/change.c @@ -421,12 +421,12 @@ void deleted_lines(linenr_T lnum, linenr_T count) /// be triggered to display the cursor. void deleted_lines_mark(linenr_T lnum, long count) { - // if we deleted the entire buffer, we need to implicitly add a new empty line bool made_empty = (count > 0) && curbuf->b_ml.ml_flags & ML_EMPTY; - mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, - -(linenr_T)count + (made_empty?1:0), - kExtmarkUndo); + mark_adjust(lnum, (linenr_T)(lnum + count - 1), MAXLNUM, -(linenr_T)count, kExtmarkNOOP); + // if we deleted the entire buffer, we need to implicitly add a new empty line + extmark_adjust(curbuf, lnum, (linenr_T)(lnum + count - 1), MAXLNUM, + -(linenr_T)count + (made_empty ? 1 : 0), kExtmarkUndo); changed_lines(lnum, 0, lnum + (linenr_T)count, (linenr_T)(-count), true); } diff --git a/test/functional/ui/fold_spec.lua b/test/functional/ui/fold_spec.lua index c79fc2989c..6bb8bb81c6 100644 --- a/test/functional/ui/fold_spec.lua +++ b/test/functional/ui/fold_spec.lua @@ -1904,4 +1904,11 @@ describe("folded lines", function() describe('without ext_multigrid', function() with_ext_multigrid(false) end) + + it('no folds remains if :delete makes buffer empty #19671', function() + funcs.setline(1, {'foo', 'bar', 'baz'}) + command('2,3fold') + command('%delete') + eq(0, funcs.foldlevel(1)) + end) end) -- cgit From 2d5fce2cdb1254391481a1603be7bfb0872044a5 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Mon, 8 Aug 2022 12:34:37 +0200 Subject: feat(lsp): disable exit_timeout by default (#19672) The lsp client used to wait up to 500ms for a language server to shutdown before sending a TERM signal. The intention behind the 500ms grace period was to ensure the language server exits to prevent stale processes, but it has the side-effect that it can interrupt language-servers which are too slow to shutdown within 500ms. Language servers tend to write out index files or project files on shutdown, and being interrupted during this process can cause corruption of those files. This changes the default to not wait at all, at the risk of leaving stale processes around if the language server isn't well behaved. An alternative would be to wait indefinitely, but that can cause neovim to take several seconds to exit. --- runtime/doc/lsp.txt | 13 +++++++------ runtime/lua/vim/lsp.lua | 4 ++-- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 11f96db8c9..48b3f6b4bb 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -1015,12 +1015,13 @@ start_client({config}) *vim.lsp.start_client()* notifications to the server by the given number in milliseconds. No debounce occurs if nil - • exit_timeout (number, default 500): - Milliseconds to wait for server to - exit cleanly after sending the - 'shutdown' request before sending - kill -15. If set to false, nvim - exits immediately after sending the + • exit_timeout (number|boolean, + default false): Milliseconds to + wait for server to exit cleanly + after sending the 'shutdown' + request before sending kill -15. If + set to false, nvim exits + immediately after sending the 'shutdown' request to the server. {root_dir} (string) Directory where the LSP server will base its diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index bf2201d9c8..2f6323ee30 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -871,7 +871,7 @@ end --- - debounce_text_changes (number, default 150): Debounce didChange --- notifications to the server by the given number in milliseconds. No debounce --- occurs if nil ---- - exit_timeout (number, default 500): Milliseconds to wait for server to +--- - exit_timeout (number|boolean, default false): Milliseconds to wait for server to --- exit cleanly after sending the 'shutdown' request before sending kill -15. --- If set to false, nvim exits immediately after sending the 'shutdown' request to the server. --- @@ -1681,7 +1681,7 @@ api.nvim_create_autocmd('VimLeavePre', { local send_kill = false for client_id, client in pairs(active_clients) do - local timeout = if_nil(client.config.flags.exit_timeout, 500) + local timeout = if_nil(client.config.flags.exit_timeout, false) if timeout then send_kill = true timeouts[client_id] = timeout -- cgit From a46e6afb8b95229478c5c1fb75e3f1c55991def0 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Mon, 8 Aug 2022 13:02:15 +0200 Subject: fix(lsp): set end_col in formatexpr (#19676) The last line was excluded from formatting via formatexpr because the character in the params was set to 0 instead of the end of line. --- runtime/lua/vim/lsp.lua | 45 +++++++++++++++++++++++--------------------- runtime/lua/vim/lsp/util.lua | 2 +- 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index 2f6323ee30..b26ed0c759 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -1982,29 +1982,32 @@ function lsp.formatexpr(opts) return 1 end - local start_line = vim.v.lnum - local end_line = start_line + vim.v.count - 1 - - if start_line > 0 and end_line > 0 then - local params = { - textDocument = util.make_text_document_params(), - range = { - start = { line = start_line - 1, character = 0 }, - ['end'] = { line = end_line - 1, character = 0 }, - }, - } - params.options = util.make_formatting_params().options - local client_results = - vim.lsp.buf_request_sync(0, 'textDocument/rangeFormatting', params, timeout_ms) + local start_lnum = vim.v.lnum + local end_lnum = start_lnum + vim.v.count - 1 - -- Apply the text edits from one and only one of the clients. - for client_id, response in pairs(client_results) do + if start_lnum <= 0 or end_lnum <= 0 then + return 0 + end + local bufnr = api.nvim_get_current_buf() + for _, client in pairs(lsp.get_active_clients({ bufnr = bufnr })) do + if client.supports_method('textDocument/rangeFormatting') then + local params = util.make_formatting_params() + local end_line = vim.fn.getline(end_lnum) + local end_col = util._str_utfindex_enc(end_line, nil, client.offset_encoding) + params.range = { + start = { + line = start_lnum - 1, + character = 0, + }, + ['end'] = { + line = end_lnum - 1, + character = end_col, + }, + } + local response = + client.request_sync('textDocument/rangeFormatting', params, timeout_ms, bufnr) if response.result then - vim.lsp.util.apply_text_edits( - response.result, - 0, - vim.lsp.get_client_by_id(client_id).offset_encoding - ) + vim.lsp.util.apply_text_edits(response.result, 0, client.offset_encoding) return 0 end end diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index eac21db386..283099bbcf 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -113,7 +113,7 @@ end --- Convert byte index to `encoding` index. --- Convenience wrapper around vim.str_utfindex ---@param line string line to be indexed ----@param index number byte index (utf-8), or `nil` for length +---@param index number|nil byte index (utf-8), or `nil` for length ---@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 ---@return number `encoding` index of `index` in `line` function M._str_utfindex_enc(line, index, encoding) -- cgit From bc8fbb7c1de0e5cbc8650be883a675bdc3e9d7d8 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 8 Aug 2022 11:35:44 +0800 Subject: refactor: move non-symbols in mbyte.h to mbyte_defs.h This just avoids including mbyte.h in eval/typval.h, so that mbyte.h can include eval/typval.h in Vim patch 8.2.1535. --- src/nvim/eval/typval.h | 2 +- src/nvim/grid.h | 1 + src/nvim/mbyte.h | 48 +------------------------------------------ src/nvim/mbyte_defs.h | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 48 deletions(-) create mode 100644 src/nvim/mbyte_defs.h diff --git a/src/nvim/eval/typval.h b/src/nvim/eval/typval.h index c02351947b..2a4dd7b146 100644 --- a/src/nvim/eval/typval.h +++ b/src/nvim/eval/typval.h @@ -13,7 +13,7 @@ #include "nvim/hashtab.h" #include "nvim/lib/queue.h" #include "nvim/macros.h" -#include "nvim/mbyte.h" +#include "nvim/mbyte_defs.h" #include "nvim/message.h" #include "nvim/pos.h" // for linenr_T #include "nvim/profile.h" // for proftime_T diff --git a/src/nvim/grid.h b/src/nvim/grid.h index c38748940d..4a8072bd96 100644 --- a/src/nvim/grid.h +++ b/src/nvim/grid.h @@ -6,6 +6,7 @@ #include "nvim/ascii.h" #include "nvim/buffer_defs.h" #include "nvim/grid_defs.h" +#include "nvim/mbyte.h" /// By default, all windows are drawn on a single rectangular grid, represented by /// this ScreenGrid instance. In multigrid mode each window will have its own diff --git a/src/nvim/mbyte.h b/src/nvim/mbyte.h index 1e5e332ad9..ffa8411675 100644 --- a/src/nvim/mbyte.h +++ b/src/nvim/mbyte.h @@ -6,7 +6,7 @@ #include #include "nvim/func_attr.h" -#include "nvim/iconv.h" +#include "nvim/mbyte_defs.h" #include "nvim/os/os_defs.h" // For indirect #include "nvim/types.h" // for char_u @@ -19,52 +19,6 @@ #define MB_BYTE2LEN(b) utf8len_tab[b] #define MB_BYTE2LEN_CHECK(b) (((b) < 0 || (b) > 255) ? 1 : utf8len_tab[b]) -// max length of an unicode char -#define MB_MAXCHAR 6 - -// properties used in enc_canon_table[] (first three mutually exclusive) -#define ENC_8BIT 0x01 -#define ENC_DBCS 0x02 -#define ENC_UNICODE 0x04 - -#define ENC_ENDIAN_B 0x10 // Unicode: Big endian -#define ENC_ENDIAN_L 0x20 // Unicode: Little endian - -#define ENC_2BYTE 0x40 // Unicode: UCS-2 -#define ENC_4BYTE 0x80 // Unicode: UCS-4 -#define ENC_2WORD 0x100 // Unicode: UTF-16 - -#define ENC_LATIN1 0x200 // Latin1 -#define ENC_LATIN9 0x400 // Latin9 -#define ENC_MACROMAN 0x800 // Mac Roman (not Macro Man! :-) - -/// Flags for vimconv_T -typedef enum { - CONV_NONE = 0, - CONV_TO_UTF8 = 1, - CONV_9_TO_UTF8 = 2, - CONV_TO_LATIN1 = 3, - CONV_TO_LATIN9 = 4, - CONV_ICONV = 5, -} ConvFlags; - -#define MBYTE_NONE_CONV { \ - .vc_type = CONV_NONE, \ - .vc_factor = 1, \ - .vc_fail = false, \ -} - -/// Structure used for string conversions -typedef struct { - int vc_type; ///< Zero or more ConvFlags. - int vc_factor; ///< Maximal expansion factor. -#ifdef HAVE_ICONV - iconv_t vc_fd; ///< Value for CONV_ICONV. -#endif - bool vc_fail; ///< What to do with invalid characters: if true, fail, - ///< otherwise use '?'. -} vimconv_T; - extern const uint8_t utf8len_tab_zero[256]; extern const uint8_t utf8len_tab[256]; diff --git a/src/nvim/mbyte_defs.h b/src/nvim/mbyte_defs.h new file mode 100644 index 0000000000..53b01a211f --- /dev/null +++ b/src/nvim/mbyte_defs.h @@ -0,0 +1,56 @@ +#ifndef NVIM_MBYTE_DEFS_H +#define NVIM_MBYTE_DEFS_H + +#include + +#include "nvim/iconv.h" + +/// max length of an unicode char +enum { MB_MAXCHAR = 6, }; + +/// properties used in enc_canon_table[] (first three mutually exclusive) +enum { + ENC_8BIT = 0x01, + ENC_DBCS = 0x02, + ENC_UNICODE = 0x04, + + ENC_ENDIAN_B = 0x10, ///< Unicode: Big endian + ENC_ENDIAN_L = 0x20, ///< Unicode: Little endian + + ENC_2BYTE = 0x40, ///< Unicode: UCS-2 + ENC_4BYTE = 0x80, ///< Unicode: UCS-4 + ENC_2WORD = 0x100, ///< Unicode: UTF-16 + + ENC_LATIN1 = 0x200, ///< Latin1 + ENC_LATIN9 = 0x400, ///< Latin9 + ENC_MACROMAN = 0x800, ///< Mac Roman (not Macro Man! :-) +}; + +/// Flags for vimconv_T +typedef enum { + CONV_NONE = 0, + CONV_TO_UTF8 = 1, + CONV_9_TO_UTF8 = 2, + CONV_TO_LATIN1 = 3, + CONV_TO_LATIN9 = 4, + CONV_ICONV = 5, +} ConvFlags; + +#define MBYTE_NONE_CONV { \ + .vc_type = CONV_NONE, \ + .vc_factor = 1, \ + .vc_fail = false, \ +} + +/// Structure used for string conversions +typedef struct { + int vc_type; ///< Zero or more ConvFlags. + int vc_factor; ///< Maximal expansion factor. +#ifdef HAVE_ICONV + iconv_t vc_fd; ///< Value for CONV_ICONV. +#endif + bool vc_fail; ///< What to do with invalid characters: if true, fail, + ///< otherwise use '?'. +} vimconv_T; + +#endif // NVIM_MBYTE_DEFS_H -- cgit From 53c9500c1dc95eb446e13e857a7d6a7642d859ab Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 8 Aug 2022 08:22:10 +0800 Subject: vim-patch:8.2.1535: it is not possible to specify cell widths of characters Problem: It is not possible to specify cell widths of characters. Solution: Add setcellwidths(). https://github.com/vim/vim/commit/08aac3c6192f0103cb87e280270a32b50e653be1 Co-Authored-By: delphinus --- runtime/doc/builtin.txt | 24 +++++ runtime/doc/options.txt | 4 +- runtime/doc/usr_41.txt | 1 + src/nvim/eval.lua | 1 + src/nvim/generators/gen_unicode_tables.lua | 6 +- src/nvim/mbyte.c | 166 ++++++++++++++++++++++++++++- src/nvim/mbyte.h | 1 + src/nvim/testdir/test_utf8.vim | 35 ++++++ 8 files changed, 233 insertions(+), 5 deletions(-) diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index c56ab70774..447f1c89e2 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -396,6 +396,7 @@ setbufline({expr}, {lnum}, {text}) Number set line {lnum} to {text} in buffer {expr} setbufvar({buf}, {varname}, {val}) set {varname} in buffer {buf} to {val} +setcellwidths({list}) none set character cell width overrides setcharpos({expr}, {list}) Number set the {expr} position to {list} setcharsearch({dict}) Dict set character search from {dict} setcmdpos({pos}) Number set cursor position in command-line @@ -6817,6 +6818,29 @@ setbufvar({buf}, {varname}, {val}) *setbufvar()* third argument: > GetValue()->setbufvar(buf, varname) + +setcellwidths({list}) *setcellwidths()* + Specify overrides for cell widths of character ranges. This + tells Vim how wide characters are, counted in screen cells. + This overrides 'ambiwidth'. Example: > + setcellwidths([[0xad, 0xad, 1], + \ [0x2194, 0x2199, 2]]) + +< *E1109* *E1110* *E1111* *E1112* *E1113* + The {list} argument is a list of lists with each three + numbers. These three numbers are [low, high, width]. "low" + and "high" can be the same, in which case this refers to one + character. Otherwise it is the range of characters from "low" + to "high" (inclusive). "width" is either 1 or 2, indicating + the character width in screen cells. + An error is given if the argument is invalid, also when a + range overlaps with another. + Only characters with value 0x100 and higher can be used. + + To clear the overrides pass an empty list: > + setcellwidths([]); + + setcharpos({expr}, {list}) *setcharpos()* Same as |setpos()| but uses the specified column number as the character index instead of the byte index in the line. diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 9d03397821..28922e9c7f 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -591,7 +591,9 @@ A jump table for the options with a short description can be found at |Q_op|. "double": Use twice the width of ASCII characters. *E834* *E835* The value "double" cannot be used if 'listchars' or 'fillchars' - contains a character that would be double width. + + The values are overruled for characters specified with + |setcellwidths()|. There are a number of CJK fonts for which the width of glyphs for those characters are solely based on how many octets they take in diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index 008b9b4e58..bc2f7f077b 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -619,6 +619,7 @@ String manipulation: *string-functions* strchars() length of a string in characters strwidth() size of string when displayed strdisplaywidth() size of string when displayed, deals with tabs + setcellwidths() set character cell width overrides substitute() substitute a pattern match with a string submatch() get a specific match in ":s" and substitute() strpart() get part of a string using byte index diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 6d8776d08b..a2272f0c98 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -327,6 +327,7 @@ return { serverstop={args=1}, setbufline={args=3, base=3}, setbufvar={args=3, base=3}, + setcellwidths={args=1, base=1}, setcharpos={args=2, base=2}, setcharsearch={args=1, base=1}, setcmdpos={args=1, base=1}, diff --git a/src/nvim/generators/gen_unicode_tables.lua b/src/nvim/generators/gen_unicode_tables.lua index aa96c97bc1..36553f4649 100644 --- a/src/nvim/generators/gen_unicode_tables.lua +++ b/src/nvim/generators/gen_unicode_tables.lua @@ -12,8 +12,8 @@ -- 2 then interval applies only to first, third, fifth, … character in range. -- Fourth value is number that should be added to the codepoint to yield -- folded/lower/upper codepoint. --- 4. emoji_width and emoji_all tables: sorted lists of non-overlapping closed --- intervals of Emoji characters. emoji_width contains all the characters +-- 4. emoji_wide and emoji_all tables: sorted lists of non-overlapping closed +-- intervals of Emoji characters. emoji_wide contains all the characters -- which don't have ambiguous or double width, and emoji_all has all Emojis. if arg[1] == '--help' then print('Usage:') @@ -288,7 +288,7 @@ local build_emoji_table = function(ut_fp, emojiprops, doublewidth, ambiwidth) end ut_fp:write('};\n') - ut_fp:write('static const struct interval emoji_width[] = {\n') + ut_fp:write('static const struct interval emoji_wide[] = {\n') for _, p in ipairs(emojiwidth) do ut_fp:write(make_range(p[1], p[2])) end diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index 223b4d6845..66262ebfad 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -74,6 +74,19 @@ struct interval { # include "unicode_tables.generated.h" #endif +static char e_list_item_nr_is_not_list[] + = N_("E1109: List item %d is not a List"); +static char e_list_item_nr_does_not_contain_3_numbers[] + = N_("E1110: List item %d does not contain 3 numbers"); +static char e_list_item_nr_range_invalid[] + = N_("E1111: List item %d range invalid"); +static char e_list_item_nr_cell_width_invalid[] + = N_("E1112: List item %d cell width invalid"); +static char e_overlapping_ranges_for_nr[] + = N_("E1113: Overlapping ranges for %lx"); +static char e_only_values_of_0x100_and_higher_supported[] + = N_("E1114: Only values of 0x100 and higher supported"); + // To speed up BYTELEN(); keep a lookup table to quickly get the length in // bytes of a UTF-8 character from the first byte of a UTF-8 string. Bytes // which are illegal when used as the first byte have a 1. The NUL byte has @@ -472,13 +485,18 @@ static bool intable(const struct interval *table, size_t n_items, int c) int utf_char2cells(int c) { if (c >= 0x100) { + int n = cw_value(c); + if (n != 0) { + return n; + } + if (!utf_printable(c)) { return 6; // unprintable, displays } if (intable(doublewidth, ARRAY_SIZE(doublewidth), c)) { return 2; } - if (p_emoji && intable(emoji_width, ARRAY_SIZE(emoji_width), c)) { + if (p_emoji && intable(emoji_wide, ARRAY_SIZE(emoji_wide), c)) { return 2; } } else if (c >= 0x80 && !vim_isprintc(c)) { @@ -2678,3 +2696,149 @@ char_u *string_convert_ext(const vimconv_T *const vcp, char_u *ptr, size_t *lenp return retval; } + +/// Table set by setcellwidths(). +typedef struct { + long first; + long last; + char width; +} cw_interval_T; + +static cw_interval_T *cw_table = NULL; +static size_t cw_table_size = 0; + +/// Return the value of the cellwidth table for the character `c`. +/// +/// @param c The source character. +/// @return 1 or 2 when `c` is in the cellwidth table, 0 if not. +static int cw_value(int c) +{ + if (cw_table == NULL) { + return 0; + } + + // first quick check for Latin1 etc. characters + if (c < cw_table[0].first) { + return 0; + } + + // binary search in table + int bot = 0; + int top = (int)cw_table_size - 1; + while (top >= bot) { + int mid = (bot + top) / 2; + if (cw_table[mid].last < c) { + bot = mid + 1; + } else if (cw_table[mid].first > c) { + top = mid - 1; + } else { + return cw_table[mid].width; + } + } + return 0; +} + +static int tv_nr_compare(const void *a1, const void *a2) +{ + const listitem_T *const li1 = (const listitem_T *)a1; + const listitem_T *const li2 = (const listitem_T *)a2; + + return (int)(TV_LIST_ITEM_TV(li1)->vval.v_number - TV_LIST_ITEM_TV(li2)->vval.v_number); +} + +/// "setcellwidths()" function +void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) +{ + if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL) { + emsg(_(e_listreq)); + return; + } + const list_T *const l = argvars[0].vval.v_list; + if (tv_list_len(l) == 0) { + // Clearing the table. + xfree(cw_table); + cw_table = NULL; + cw_table_size = 0; + return; + } + + const listitem_T **ptrs = xmalloc(sizeof(const listitem_T *) * (size_t)tv_list_len(l)); + + // Check that all entries are a list with three numbers, the range is + // valid and the cell width is valid. + int item = 0; + TV_LIST_ITER_CONST(l, li, { + const typval_T *const li_tv = TV_LIST_ITEM_TV(li); + + if (li_tv->v_type != VAR_LIST || li_tv->vval.v_list == NULL) { + semsg(_(e_list_item_nr_is_not_list), item); + xfree(ptrs); + return; + } + + const list_T *const li_l = li_tv->vval.v_list; + const listitem_T *lili = tv_list_first(li_l); + int i = 0; + varnumber_T n1; + for (; lili != NULL; lili = TV_LIST_ITEM_NEXT(li_l, lili), i++) { + const typval_T *const lili_tv = TV_LIST_ITEM_TV(lili); + if (lili_tv->v_type != VAR_NUMBER) { + break; + } + if (i == 0) { + n1 = lili_tv->vval.v_number; + if (n1 < 0x100) { + emsg(_(e_only_values_of_0x100_and_higher_supported)); + xfree(ptrs); + return; + } + } else if (i == 1 && lili_tv->vval.v_number < n1) { + semsg(_(e_list_item_nr_range_invalid), item); + xfree(ptrs); + return; + } else if (i == 2 && (lili_tv->vval.v_number < 1 || lili_tv->vval.v_number > 2)) { + semsg(_(e_list_item_nr_cell_width_invalid), item); + xfree(ptrs); + return; + } + } + + if (i != 3) { + semsg(_(e_list_item_nr_does_not_contain_3_numbers), item); + xfree(ptrs); + return; + } + + ptrs[item++] = lili; + }); + + // Sort the list on the first number. + qsort((void *)ptrs, (size_t)tv_list_len(l), sizeof(const listitem_T *), tv_nr_compare); + + cw_interval_T *table = xmalloc(sizeof(cw_interval_T) * (size_t)tv_list_len(l)); + + // Store the items in the new table. + item = 0; + TV_LIST_ITER_CONST(l, li, { + const list_T *const li_l = TV_LIST_ITEM_TV(li)->vval.v_list; + const listitem_T *lili = tv_list_first(li_l); + const varnumber_T n1 = TV_LIST_ITEM_TV(lili)->vval.v_number; + if (item > 0 && n1 <= table[item - 1].last) { + semsg(_(e_overlapping_ranges_for_nr), (long)n1); + xfree(ptrs); + xfree(table); + return; + } + table[item].first = n1; + lili = TV_LIST_ITEM_NEXT(li_l, lili); + table[item].last = TV_LIST_ITEM_TV(lili)->vval.v_number; + lili = TV_LIST_ITEM_NEXT(li_l, lili); + table[item].width = (char)TV_LIST_ITEM_TV(lili)->vval.v_number; + item++; + }); + + xfree(ptrs); + xfree(cw_table); + cw_table = table; + cw_table_size = (size_t)tv_list_len(l); +} diff --git a/src/nvim/mbyte.h b/src/nvim/mbyte.h index ffa8411675..2a9afcbd03 100644 --- a/src/nvim/mbyte.h +++ b/src/nvim/mbyte.h @@ -5,6 +5,7 @@ #include #include +#include "nvim/eval/typval.h" #include "nvim/func_attr.h" #include "nvim/mbyte_defs.h" #include "nvim/os/os_defs.h" // For indirect diff --git a/src/nvim/testdir/test_utf8.vim b/src/nvim/testdir/test_utf8.vim index 9b010a5dbc..c5dfd85e5e 100644 --- a/src/nvim/testdir/test_utf8.vim +++ b/src/nvim/testdir/test_utf8.vim @@ -140,6 +140,41 @@ func Test_list2str_str2list_latin1() call assert_equal(s, sres) endfunc +func Test_setcellwidths() + call setcellwidths([ + \ [0x1330, 0x1330, 2], + \ [0x1337, 0x1339, 2], + \ [9999, 10000, 1], + \]) + + call assert_equal(2, strwidth("\u1330")) + call assert_equal(1, strwidth("\u1336")) + call assert_equal(2, strwidth("\u1337")) + call assert_equal(2, strwidth("\u1339")) + call assert_equal(1, strwidth("\u133a")) + + call setcellwidths([]) + + call assert_fails('call setcellwidths(1)', 'E714:') + + call assert_fails('call setcellwidths([1, 2, 0])', 'E1109:') + + call assert_fails('call setcellwidths([[0x101]])', 'E1110:') + call assert_fails('call setcellwidths([[0x101, 0x102]])', 'E1110:') + call assert_fails('call setcellwidths([[0x101, 0x102, 1, 4]])', 'E1110:') + call assert_fails('call setcellwidths([["a"]])', 'E1110:') + + call assert_fails('call setcellwidths([[0x102, 0x101, 1]])', 'E1111:') + + call assert_fails('call setcellwidths([[0x101, 0x102, 0]])', 'E1112:') + call assert_fails('call setcellwidths([[0x101, 0x102, 3]])', 'E1112:') + + call assert_fails('call setcellwidths([[0x111, 0x122, 1], [0x115, 0x116, 2]])', 'E1113:') + call assert_fails('call setcellwidths([[0x111, 0x122, 1], [0x122, 0x123, 2]])', 'E1113:') + + call assert_fails('call setcellwidths([[0x33, 0x44, 2]])', 'E1114:') +endfunc + func Test_print_overlong() " Text with more composing characters than MB_MAXBYTES. new -- cgit From 967415d5277df25ee96d961ec0ab95ddfe01a611 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 8 Aug 2022 12:01:57 +0800 Subject: vim-patch:8.2.1537: memory acccess error when using setcellwidths() Problem: Memory acccess error when using setcellwidths(). Solution: Use array and pointers correctly. https://github.com/vim/vim/commit/b06a6d59d12dbd67d55b3c46f6e5547e9103c931 --- src/nvim/mbyte.c | 26 ++++++++++++-------------- src/nvim/testdir/test_utf8.vim | 2 +- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index 66262ebfad..e5658fa15d 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -83,7 +83,7 @@ static char e_list_item_nr_range_invalid[] static char e_list_item_nr_cell_width_invalid[] = N_("E1112: List item %d cell width invalid"); static char e_overlapping_ranges_for_nr[] - = N_("E1113: Overlapping ranges for %lx"); + = N_("E1113: Overlapping ranges for 0x%lx"); static char e_only_values_of_0x100_and_higher_supported[] = N_("E1114: Only values of 0x100 and higher supported"); @@ -2740,8 +2740,8 @@ static int cw_value(int c) static int tv_nr_compare(const void *a1, const void *a2) { - const listitem_T *const li1 = (const listitem_T *)a1; - const listitem_T *const li2 = (const listitem_T *)a2; + const listitem_T *const li1 = *(const listitem_T **)a1; + const listitem_T *const li2 = *(const listitem_T **)a2; return (int)(TV_LIST_ITEM_TV(li1)->vval.v_number - TV_LIST_ITEM_TV(li2)->vval.v_number); } @@ -2778,9 +2778,10 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) const list_T *const li_l = li_tv->vval.v_list; const listitem_T *lili = tv_list_first(li_l); - int i = 0; + ptrs[item] = lili; + int i; varnumber_T n1; - for (; lili != NULL; lili = TV_LIST_ITEM_NEXT(li_l, lili), i++) { + for (i = 0; lili != NULL; lili = TV_LIST_ITEM_NEXT(li_l, lili), i++) { const typval_T *const lili_tv = TV_LIST_ITEM_TV(lili); if (lili_tv->v_type != VAR_NUMBER) { break; @@ -2809,7 +2810,7 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } - ptrs[item++] = lili; + item++; }); // Sort the list on the first number. @@ -2818,10 +2819,8 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) cw_interval_T *table = xmalloc(sizeof(cw_interval_T) * (size_t)tv_list_len(l)); // Store the items in the new table. - item = 0; - TV_LIST_ITER_CONST(l, li, { - const list_T *const li_l = TV_LIST_ITEM_TV(li)->vval.v_list; - const listitem_T *lili = tv_list_first(li_l); + for (item = 0; item < tv_list_len(l); item++) { + const listitem_T *lili = ptrs[item]; const varnumber_T n1 = TV_LIST_ITEM_TV(lili)->vval.v_number; if (item > 0 && n1 <= table[item - 1].last) { semsg(_(e_overlapping_ranges_for_nr), (long)n1); @@ -2830,12 +2829,11 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } table[item].first = n1; - lili = TV_LIST_ITEM_NEXT(li_l, lili); + lili = TV_LIST_ITEM_NEXT(, lili); // TODO: get list which lili belongs to table[item].last = TV_LIST_ITEM_TV(lili)->vval.v_number; - lili = TV_LIST_ITEM_NEXT(li_l, lili); + lili = TV_LIST_ITEM_NEXT(, lili); // TODO: get list which lili belongs to table[item].width = (char)TV_LIST_ITEM_TV(lili)->vval.v_number; - item++; - }); + } xfree(ptrs); xfree(cw_table); diff --git a/src/nvim/testdir/test_utf8.vim b/src/nvim/testdir/test_utf8.vim index c5dfd85e5e..882e9623f6 100644 --- a/src/nvim/testdir/test_utf8.vim +++ b/src/nvim/testdir/test_utf8.vim @@ -143,8 +143,8 @@ endfunc func Test_setcellwidths() call setcellwidths([ \ [0x1330, 0x1330, 2], - \ [0x1337, 0x1339, 2], \ [9999, 10000, 1], + \ [0x1337, 0x1339, 2], \]) call assert_equal(2, strwidth("\u1330")) -- cgit From 01a7009af9f7bbf5f1b38c82956caf67a7c8bcca Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 8 Aug 2022 14:31:36 +0800 Subject: refactor(setcellwidths): use TV_LIST_ITEM_NEXT properly --- src/nvim/mbyte.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index e5658fa15d..e19c356343 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -2740,8 +2740,8 @@ static int cw_value(int c) static int tv_nr_compare(const void *a1, const void *a2) { - const listitem_T *const li1 = *(const listitem_T **)a1; - const listitem_T *const li2 = *(const listitem_T **)a2; + const listitem_T *const li1 = tv_list_first(*(const list_T **)a1); + const listitem_T *const li2 = tv_list_first(*(const list_T **)a2); return (int)(TV_LIST_ITEM_TV(li1)->vval.v_number - TV_LIST_ITEM_TV(li2)->vval.v_number); } @@ -2762,7 +2762,8 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } - const listitem_T **ptrs = xmalloc(sizeof(const listitem_T *) * (size_t)tv_list_len(l)); + // Note: use list_T instead of listitem_T so that TV_LIST_ITEM_NEXT can be used properly below. + const list_T **ptrs = xmalloc(sizeof(const list_T *) * (size_t)tv_list_len(l)); // Check that all entries are a list with three numbers, the range is // valid and the cell width is valid. @@ -2777,8 +2778,8 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) } const list_T *const li_l = li_tv->vval.v_list; + ptrs[item] = li_l; const listitem_T *lili = tv_list_first(li_l); - ptrs[item] = lili; int i; varnumber_T n1; for (i = 0; lili != NULL; lili = TV_LIST_ITEM_NEXT(li_l, lili), i++) { @@ -2814,13 +2815,14 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) }); // Sort the list on the first number. - qsort((void *)ptrs, (size_t)tv_list_len(l), sizeof(const listitem_T *), tv_nr_compare); + qsort((void *)ptrs, (size_t)tv_list_len(l), sizeof(const list_T *), tv_nr_compare); cw_interval_T *table = xmalloc(sizeof(cw_interval_T) * (size_t)tv_list_len(l)); // Store the items in the new table. for (item = 0; item < tv_list_len(l); item++) { - const listitem_T *lili = ptrs[item]; + const list_T *const li_l = ptrs[item]; + const listitem_T *lili = tv_list_first(li_l); const varnumber_T n1 = TV_LIST_ITEM_TV(lili)->vval.v_number; if (item > 0 && n1 <= table[item - 1].last) { semsg(_(e_overlapping_ranges_for_nr), (long)n1); @@ -2829,9 +2831,9 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } table[item].first = n1; - lili = TV_LIST_ITEM_NEXT(, lili); // TODO: get list which lili belongs to + lili = TV_LIST_ITEM_NEXT(li_l, lili); table[item].last = TV_LIST_ITEM_TV(lili)->vval.v_number; - lili = TV_LIST_ITEM_NEXT(, lili); // TODO: get list which lili belongs to + lili = TV_LIST_ITEM_NEXT(li_l, lili); table[item].width = (char)TV_LIST_ITEM_TV(lili)->vval.v_number; } -- cgit From 9fedb6fd783b9ac48239bc7574779118eec3729a Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 8 Aug 2022 12:08:28 +0800 Subject: vim-patch:8.2.3545: setcellwidths() may make 'listchars' or 'fillchars' invalid Problem: setcellwidths() may make 'listchars' or 'fillchars' invalid. Solution: Check the value and give an error. (closes vim/vim#9024) https://github.com/vim/vim/commit/94358a1e6e640ca5ebeb295efdddd4e92b700673 Cherry-pick f_setcellwidths() change from patch 9.0.0036. Cherry-pick 'ambiwidth' docs update from runtime update 079ba76ae7a7. --- runtime/doc/builtin.txt | 3 +++ runtime/doc/options.txt | 2 ++ src/nvim/globals.h | 5 +++++ src/nvim/mbyte.c | 33 ++++++++++++++++++++++++++++++++- src/nvim/option.c | 6 +++--- src/nvim/testdir/test_utf8.vim | 10 ++++++++++ 6 files changed, 55 insertions(+), 4 deletions(-) diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 447f1c89e2..b80bedfac5 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -6837,6 +6837,9 @@ setcellwidths({list}) *setcellwidths()* range overlaps with another. Only characters with value 0x100 and higher can be used. + If the new value causes 'fillchars' or 'listchars' to become + invalid it is rejected and an error is given. + To clear the overrides pass an empty list: > setcellwidths([]); diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 28922e9c7f..f0977c91de 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -591,6 +591,8 @@ A jump table for the options with a short description can be found at |Q_op|. "double": Use twice the width of ASCII characters. *E834* *E835* The value "double" cannot be used if 'listchars' or 'fillchars' + contains a character that would be double width. These errors may + also be given when calling setcellwidths(). The values are overruled for characters specified with |setcellwidths()|. diff --git a/src/nvim/globals.h b/src/nvim/globals.h index 317423ffa0..23870a572e 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -1000,6 +1000,11 @@ EXTERN char e_fnametoolong[] INIT(= N_("E856: Filename too long")); EXTERN char e_float_as_string[] INIT(= N_("E806: using Float as a String")); EXTERN char e_cannot_edit_other_buf[] INIT(= N_("E788: Not allowed to edit another buffer now")); +EXTERN char e_conflicts_with_value_of_listchars[] +INIT(= N_("E834: Conflicts with value of 'listchars'")); +EXTERN char e_conflicts_with_value_of_fillchars[] +INIT(= N_("E835: Conflicts with value of 'fillchars'")); + EXTERN char e_autocmd_err[] INIT(= N_("E5500: autocmd has thrown an exception: %s")); EXTERN char e_cmdmap_err[] INIT(= N_("E5520: mapping must end with ")); EXTERN char e_cmdmap_repeated[] diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index e19c356343..5de7231a0a 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -2838,7 +2838,38 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) } xfree(ptrs); - xfree(cw_table); + + cw_interval_T *const cw_table_save = cw_table; + const size_t cw_table_size_save = cw_table_size; cw_table = table; cw_table_size = (size_t)tv_list_len(l); + + // Check that the new value does not conflict with 'fillchars' or + // 'listchars'. + char *error = NULL; + if (set_chars_option(curwin, &p_fcs, false) != NULL) { + error = e_conflicts_with_value_of_fillchars; + } else if (set_chars_option(curwin, &p_lcs, false) != NULL) { + error = e_conflicts_with_value_of_listchars; + } else { + FOR_ALL_TAB_WINDOWS(tp, wp) { + if (set_chars_option(wp, &wp->w_p_lcs, false) != NULL) { + error = e_conflicts_with_value_of_listchars; + break; + } + if (set_chars_option(wp, &wp->w_p_fcs, false) != NULL) { + error = e_conflicts_with_value_of_fillchars; + break; + } + } + } + if (error != NULL) { + emsg(_(error)); + cw_table = cw_table_save; + cw_table_size = cw_table_size_save; + xfree(table); + return; + } + + xfree(cw_table_save); } diff --git a/src/nvim/option.c b/src/nvim/option.c index 12c5889703..3ab1a32eeb 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -2580,11 +2580,11 @@ static char *did_set_string_option(int opt_idx, char_u **varp, char_u *oldval, c } else { FOR_ALL_TAB_WINDOWS(tp, wp) { if (set_chars_option(wp, &wp->w_p_lcs, true) != NULL) { - errmsg = _("E834: Conflicts with value of 'listchars'"); + errmsg = _(e_conflicts_with_value_of_listchars); goto ambw_end; } if (set_chars_option(wp, &wp->w_p_fcs, true) != NULL) { - errmsg = _("E835: Conflicts with value of 'fillchars'"); + errmsg = _(e_conflicts_with_value_of_fillchars); goto ambw_end; } } @@ -3605,7 +3605,7 @@ static int get_encoded_char_adv(char_u **p) /// /// @param varp either &curwin->w_p_lcs or &curwin->w_p_fcs /// @return error message, NULL if it's OK. -static char *set_chars_option(win_T *wp, char_u **varp, bool set) +char *set_chars_option(win_T *wp, char_u **varp, bool set) { int round, i, len, len2, entries; char_u *p, *s; diff --git a/src/nvim/testdir/test_utf8.vim b/src/nvim/testdir/test_utf8.vim index 882e9623f6..ab3503c282 100644 --- a/src/nvim/testdir/test_utf8.vim +++ b/src/nvim/testdir/test_utf8.vim @@ -173,6 +173,16 @@ func Test_setcellwidths() call assert_fails('call setcellwidths([[0x111, 0x122, 1], [0x122, 0x123, 2]])', 'E1113:') call assert_fails('call setcellwidths([[0x33, 0x44, 2]])', 'E1114:') + + set listchars=tab:--\\u2192 + call assert_fails('call setcellwidths([[0x2192, 0x2192, 2]])', 'E834:') + + set fillchars=stl:\\u2501 + call assert_fails('call setcellwidths([[0x2501, 0x2501, 2]])', 'E835:') + + set listchars& + set fillchars& + call setcellwidths([]) endfunc func Test_print_overlong() -- cgit From 603f7bd253e6dd3693e2957f0beb3223945fe705 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 8 Aug 2022 14:59:07 +0800 Subject: fix(fillchars): change fallback after setcellwidths() --- src/nvim/mbyte.c | 5 +++-- src/nvim/option.c | 32 ++++++++++--------------------- test/functional/options/defaults_spec.lua | 30 +++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 24 deletions(-) diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index 5de7231a0a..e156fa58d1 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -2853,11 +2853,11 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) error = e_conflicts_with_value_of_listchars; } else { FOR_ALL_TAB_WINDOWS(tp, wp) { - if (set_chars_option(wp, &wp->w_p_lcs, false) != NULL) { + if (set_chars_option(wp, &wp->w_p_lcs, true) != NULL) { error = e_conflicts_with_value_of_listchars; break; } - if (set_chars_option(wp, &wp->w_p_fcs, false) != NULL) { + if (set_chars_option(wp, &wp->w_p_fcs, true) != NULL) { error = e_conflicts_with_value_of_fillchars; break; } @@ -2872,4 +2872,5 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) } xfree(cw_table_save); + redraw_all_later(NOT_VALID); } diff --git a/src/nvim/option.c b/src/nvim/option.c index 3ab1a32eeb..d7443bc593 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -3624,21 +3624,22 @@ char *set_chars_option(win_T *wp, char_u **varp, bool set) }; struct chars_tab *tab; + // XXX: Characters taking 2 columns is forbidden (TUI limitation?). Set old defaults in this case. struct chars_tab fcs_tab[] = { { &wp->w_p_fcs_chars.stl, "stl", ' ' }, { &wp->w_p_fcs_chars.stlnc, "stlnc", ' ' }, { &wp->w_p_fcs_chars.wbr, "wbr", ' ' }, - { &wp->w_p_fcs_chars.horiz, "horiz", 9472 }, // ─ - { &wp->w_p_fcs_chars.horizup, "horizup", 9524 }, // ┴ - { &wp->w_p_fcs_chars.horizdown, "horizdown", 9516 }, // ┬ - { &wp->w_p_fcs_chars.vert, "vert", 9474 }, // │ - { &wp->w_p_fcs_chars.vertleft, "vertleft", 9508 }, // ┤ - { &wp->w_p_fcs_chars.vertright, "vertright", 9500 }, // ├ - { &wp->w_p_fcs_chars.verthoriz, "verthoriz", 9532 }, // ┼ - { &wp->w_p_fcs_chars.fold, "fold", 183 }, // · + { &wp->w_p_fcs_chars.horiz, "horiz", char2cells(0x2500) == 1 ? 0x2500 : '-' }, // ─ + { &wp->w_p_fcs_chars.horizup, "horizup", char2cells(0x2534) == 1 ? 0x2534 : '-' }, // ┴ + { &wp->w_p_fcs_chars.horizdown, "horizdown", char2cells(0x252c) == 1 ? 0x252c : '-' }, // ┬ + { &wp->w_p_fcs_chars.vert, "vert", char2cells(0x2502) == 1 ? 0x2502 : '|' }, // │ + { &wp->w_p_fcs_chars.vertleft, "vertleft", char2cells(0x2524) == 1 ? 0x2524 : '|' }, // ┤ + { &wp->w_p_fcs_chars.vertright, "vertright", char2cells(0x251c) == 1 ? 0x251c : '|' }, // ├ + { &wp->w_p_fcs_chars.verthoriz, "verthoriz", char2cells(0x253c) == 1 ? 0x253c : '+' }, // ┼ + { &wp->w_p_fcs_chars.fold, "fold", char2cells(0x00b7) == 1 ? 0x00b7 : '-' }, // · { &wp->w_p_fcs_chars.foldopen, "foldopen", '-' }, { &wp->w_p_fcs_chars.foldclosed, "foldclose", '+' }, - { &wp->w_p_fcs_chars.foldsep, "foldsep", 9474 }, // │ + { &wp->w_p_fcs_chars.foldsep, "foldsep", char2cells(0x2502) == 1 ? 0x2502 : '|' }, // │ { &wp->w_p_fcs_chars.diff, "diff", '-' }, { &wp->w_p_fcs_chars.msgsep, "msgsep", ' ' }, { &wp->w_p_fcs_chars.eob, "eob", '~' }, @@ -3667,19 +3668,6 @@ char *set_chars_option(win_T *wp, char_u **varp, bool set) if (varp == &wp->w_p_fcs && wp->w_p_fcs[0] == NUL) { varp = &p_fcs; } - if (*p_ambw == 'd') { - // XXX: If ambiwidth=double then some characters take 2 columns, - // which is forbidden (TUI limitation?). Set old defaults. - fcs_tab[3].def = '-'; - fcs_tab[4].def = '-'; - fcs_tab[5].def = '-'; - fcs_tab[6].def = '|'; - fcs_tab[7].def = '|'; - fcs_tab[8].def = '|'; - fcs_tab[9].def = '+'; - fcs_tab[10].def = '-'; - fcs_tab[13].def = '|'; - } } // first round: check for valid value, second round: assign values diff --git a/test/functional/options/defaults_spec.lua b/test/functional/options/defaults_spec.lua index 9244ca0974..4e2f2ab63e 100644 --- a/test/functional/options/defaults_spec.lua +++ b/test/functional/options/defaults_spec.lua @@ -161,6 +161,36 @@ describe('startup defaults', function() ~ |~ | | ]]) + + -- change "vert" character to single-cell + funcs.setcellwidths({{0x2502, 0x2502, 1}}) + screen:expect([[ + 1 │1 | + ^+-- 2 lines: 2----------│+-- 2 lines: 2---------| + 4 │4 | + ~ │~ | + | + ]]) + + -- change "vert" character to double-cell + funcs.setcellwidths({{0x2502, 0x2502, 2}}) + screen:expect([[ + 1 |1 | + ^+-- 2 lines: 2----------|+-- 2 lines: 2---------| + 4 |4 | + ~ |~ | + | + ]]) + + -- "vert" character should still default to single-byte fillchars because of setcellwidths(). + command('set ambiwidth=single') + screen:expect([[ + 1 |1 | + ^+-- 2 lines: 2··········|+-- 2 lines: 2·········| + 4 |4 | + ~ |~ | + | + ]]) end) end) -- cgit From d31ee6664d3b8d37ac4bb95b3adad397e90a8da1 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 8 Aug 2022 22:04:21 +0800 Subject: test: increse expect_exit() timeouts (#19680) A timeout of 100 milliseconds is sometimes still too short for macOS. Change it to 1000 milliseconds. --- test/functional/legacy/arglist_spec.lua | 2 +- test/functional/legacy/excmd_spec.lua | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/functional/legacy/arglist_spec.lua b/test/functional/legacy/arglist_spec.lua index f90da16d7b..4d9e88c446 100644 --- a/test/functional/legacy/arglist_spec.lua +++ b/test/functional/legacy/arglist_spec.lua @@ -276,6 +276,6 @@ describe('argument list commands', function() 2 more files to edit. Quit anyway? | [Y]es, (N)o: ^ | ]]) - expect_exit(100, feed, 'Y') + expect_exit(1000, feed, 'Y') end) end) diff --git a/test/functional/legacy/excmd_spec.lua b/test/functional/legacy/excmd_spec.lua index 65957d85de..ece88d26bd 100644 --- a/test/functional/legacy/excmd_spec.lua +++ b/test/functional/legacy/excmd_spec.lua @@ -94,7 +94,7 @@ describe(':confirm command dialog', function() {3:Save changes to "Xbar"?} | {3:[Y]es, (N)o, Save (A)ll, (D)iscard All, (C)ancel: }^ | ]]) - expect_exit(100, feed, 'A') + expect_exit(1000, feed, 'A') eq('foo2\n', read_file('Xfoo')) eq('bar2\n', read_file('Xbar')) @@ -132,7 +132,7 @@ describe(':confirm command dialog', function() {3:Save changes to "Xbar"?} | {3:[Y]es, (N)o, Save (A)ll, (D)iscard All, (C)ancel: }^ | ]]) - expect_exit(100, feed, 'D') + expect_exit(1000, feed, 'D') eq('foo2\n', read_file('Xfoo')) eq('bar2\n', read_file('Xbar')) @@ -193,7 +193,7 @@ describe(':confirm command dialog', function() {3:Save changes to "Xfoo"?} | {3:[Y]es, (N)o, (C)ancel: }^ | ]]) - expect_exit(100, feed, 'Y') + expect_exit(1000, feed, 'Y') eq('foo4\n', read_file('Xfoo')) eq('bar2\n', read_file('Xbar')) -- cgit From 68c674af0fbc4158690319aa6125a098a592412d Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Mon, 8 Aug 2022 18:30:17 +0200 Subject: feat(lsp): set formatexpr by default (#19677) Follow up to https://github.com/neovim/neovim/pull/19003 --- runtime/doc/lsp.txt | 3 +++ runtime/lua/vim/lsp.lua | 15 +++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 48b3f6b4bb..94726ceaab 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -59,6 +59,9 @@ language server supports the functionality. - |tagfunc| is set to |vim.lsp.tagfunc|. This enables features like go-to-definition, |:tjump|, and keymaps like |CTRL-]|, |CTRL-W_]|, |CTRL-W_}| to utilize the language server. +- |formatexpr| is set to |vim.lsp.formatexpr| if both |formatprg| and + |formatexpr| are empty. This allows to format lines via |gq| if the language + server supports it. To use other LSP features like hover, rename, etc. you can setup some additional keymaps. It's recommended to setup them in a |LspAttach| autocmd to diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index b26ed0c759..7f3237bdd0 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -968,12 +968,20 @@ function lsp.start_client(config) ---@private local function set_defaults(client, bufnr) - if client.server_capabilities.definitionProvider and vim.bo[bufnr].tagfunc == '' then + local capabilities = client.server_capabilities + if capabilities.definitionProvider and vim.bo[bufnr].tagfunc == '' then vim.bo[bufnr].tagfunc = 'v:lua.vim.lsp.tagfunc' end - if client.server_capabilities.completionProvider and vim.bo[bufnr].omnifunc == '' then + if capabilities.completionProvider and vim.bo[bufnr].omnifunc == '' then vim.bo[bufnr].omnifunc = 'v:lua.vim.lsp.omnifunc' end + if + capabilities.documentRangeFormattingProvider + and vim.bo[bufnr].formatprg == '' + and vim.bo[bufnr].formatexpr == '' + then + vim.bo[bufnr].formatexpr = 'v:lua.vim.lsp.formatexpr()' + end end ---@private @@ -986,6 +994,9 @@ function lsp.start_client(config) if vim.bo[bufnr].omnifunc == 'v:lua.vim.lsp.omnifunc' then vim.bo[bufnr].omnifunc = nil end + if vim.bo[bufnr].formatexpr == 'v:lua.vim.lsp.formatexpr()' then + vim.bo[bufnr].formatexpr = nil + end end ---@private -- cgit From e6680ea7c3912d38f2ef967e053be741624633ad Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Mon, 8 Aug 2022 18:58:32 +0200 Subject: docs(lua): add Lua 5.1 reference manual (#19663) based on http://www.vim.org/scripts/script.php?script_id=1291 reformatted to match Nvim documentation style; removed irrelevant sections Co-authored-by: dundargoc Co-authored-by: Christian Clason Co-authored-by: Lewis Russell --- runtime/doc/help.txt | 1 + runtime/doc/lua.txt | 30 +- runtime/doc/luaref.txt | 4966 ++++++++++++++++++++++++++++++++++++++++++++ runtime/lua/vim/shared.lua | 2 +- 4 files changed, 4983 insertions(+), 16 deletions(-) create mode 100644 runtime/doc/luaref.txt diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt index b97c9a2e3f..2a7125a044 100644 --- a/runtime/doc/help.txt +++ b/runtime/doc/help.txt @@ -185,6 +185,7 @@ Other ~ |channel.txt| Nvim asynchronous IO |dev_style.txt| Nvim style guide |job_control.txt| Spawn and control multiple processes +|luaref.txt| Lua reference manual *standard-plugin-list* Standard plugins ~ diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 4062a35735..52d25d82e6 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -37,7 +37,7 @@ separator when searching. For a module `foo.bar`, each directory is searched for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found, the directories are searched again for a shared library with a name matching `lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from -the initial value of `package.cpath`. If still no files are found, Nvim falls +the initial value of |package.cpath|. If still no files are found, Nvim falls back to Lua's default search mechanism. The first script found is run and `require()` returns the value returned by the script if any, else `true`. @@ -46,7 +46,7 @@ with subsequent calls returning the cached value without searching for, or executing any script. For further details on `require()`, see the Lua documentation at https://www.lua.org/manual/5.1/manual.html#pdf-require. -For example, if 'runtimepath' is `foo,bar` and `package.cpath` was +For example, if 'runtimepath' is `foo,bar` and |package.cpath| was `./?.so;./?.dll` at startup, `require('mod')` searches these paths in order and loads the first module found: @@ -59,27 +59,27 @@ and loads the first module found: bar/lua/mod.so bar/lua/mod.dll -Nvim automatically adjusts `package.path` and `package.cpath` according to the +Nvim automatically adjusts |package.path| and |package.cpath| according to the effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is -changed. `package.path` is adjusted by simply appending `/lua/?.lua` and +changed. |package.path| is adjusted by simply appending `/lua/?.lua` and `/lua/?/init.lua` to each directory from 'runtimepath' (`/` is actually the first character of `package.config`). -Similarly to `package.path`, modified directories from 'runtimepath' are also -added to `package.cpath`. In this case, instead of appending `/lua/?.lua` and +Similarly to |package.path|, modified directories from 'runtimepath' are also +added to |package.cpath|. In this case, instead of appending `/lua/?.lua` and `/lua/?/init.lua` to each runtimepath, all unique `?`-containing suffixes of -the existing `package.cpath` are used. Example: +the existing |package.cpath| are used. Example: 1. Given that - 'runtimepath' contains `/foo/bar,/xxx;yyy/baz,/abc`; - initial (defined at compile-time or derived from - `$LUA_CPATH`/`$LUA_INIT`) `package.cpath` contains + `$LUA_CPATH`/`$LUA_INIT`) |package.cpath| contains `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`. 2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in order: parts of the path starting from the first path component containing question mark and preceding path separator. 3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same - as the suffix of the first path from `package.path` (i.e. `./?.so`). Which + as the suffix of the first path from |package.path| (i.e. `./?.so`). Which leaves `/?.so` and `/a?d/j/g.elf`, in this order. 4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The second one contains a semicolon which is a paths separator so it is out, @@ -93,7 +93,7 @@ the existing `package.cpath` are used. Example: - `/abc/lua/?.so` - `/abc/lua/a?d/j/g.elf` -6. New paths are prepended to the original `package.cpath`. +6. New paths are prepended to the original |package.cpath|. The result will look like this: @@ -108,16 +108,16 @@ Note: remembered and removed at the next update, while all paths derived from the new 'runtimepath' are prepended as described above. This allows removing paths when path is removed from 'runtimepath', adding paths when they are - added and reordering `package.path`/`package.cpath` content if 'runtimepath' + added and reordering |package.path|/|package.cpath| content if 'runtimepath' was reordered. - Although adjustments happen automatically, Nvim does not track current - values of `package.path` or `package.cpath`. If you happen to delete some + values of |package.path| or |package.cpath|. If you happen to delete some paths from there you can set 'runtimepath' to trigger an update: > let &runtimepath = &runtimepath - Skipping paths from 'runtimepath' which contain semicolons applies both to - `package.path` and `package.cpath`. Given that there are some badly written + |package.path| and |package.cpath|. Given that there are some badly written plugins using shell, which will not work with paths containing semicolons, it is better to not have them in 'runtimepath' at all. @@ -182,7 +182,7 @@ Lua Patterns *lua-patterns* For performance reasons, Lua does not support regular expressions natively. Instead, the Lua `string` standard library allows manipulations using a -restricted set of "patterns", see https://www.lua.org/manual/5.1/manual.html#5.4.1 +restricted set of "patterns", see |luaref-patterns|. Examples (`string.match` extracts the first match): > @@ -1603,7 +1603,7 @@ list_slice({list}, {start}, {finish}) *vim.list_slice()* (inclusive) pesc({s}) *vim.pesc()* - Escapes magic chars in a Lua pattern. + Escapes magic chars in |lua-patterns|. Parameters: ~ {s} (string) String to escape diff --git a/runtime/doc/luaref.txt b/runtime/doc/luaref.txt new file mode 100644 index 0000000000..9dbd2d4de5 --- /dev/null +++ b/runtime/doc/luaref.txt @@ -0,0 +1,4966 @@ +*luaref.txt* Nvim + *luaref* *Lua-Reference* + + LUA REFERENCE MANUAL + + + Version 0.3.0 + August 7th, 2022 + + + Vimdoc version (c) 2006 by Luis Carvalho + + + Adapted from "Lua: 5.1 reference manual" + R. Ierusalimschy, L. H. de Figueiredo, W. Celes + Copyright (c) 2006 Lua.org, PUC-Rio. + + + See |luaref-doc| for information on this manual. + See |luaref-copyright| for copyright and licenses. + + + CONTENTS + ============ + + 1 INTRODUCTION........................|luaref-intro| + + 2 THE LANGUAGE........................|luaref-language| + 2.1 Lexical Conventions...............|luaref-langLexConv| + 2.2 Values and Types..................|luaref-langValTypes| + 2.2.1 Coercion........................|luaref-langCoercion| + 2.3 Variables.........................|luaref-langVariables| + 2.4 Statements........................|luaref-langStats| + 2.4.1 Chunks..........................|luaref-langChunks| + 2.4.2 Blocks..........................|luaref-langBlocks| + 2.4.3 Assignment......................|luaref-langAssign| + 2.4.4 Control Structures..............|luaref-langContStructs| + 2.4.5 For Statement...................|luaref-langForStat| + 2.4.6 Function Calls as Statements....|luaref-langFuncStat| + 2.4.7 Local Declarations..............|luaref-langLocalDec| + 2.5 Expressions.......................|luaref-langExpressions| + 2.5.1 Arithmetic Operators............|luaref-langArithOp| + 2.5.2 Relational Operators............|luaref-langRelOp| + 2.5.3 Logical Operators...............|luaref-langLogOp| + 2.5.4 Concatenation...................|luaref-langConcat| + 2.5.5 The Length Operator.............|luaref-langLength| + 2.5.6 Precedence......................|luaref-langPrec| + 2.5.7 Table Constructors..............|luaref-langTableConst| + 2.5.8 Function Calls..................|luaref-langFuncCalls| + 2.5.9 Function Definitions............|luaref-langFuncDefs| + 2.6 Visibility Rules..................|luaref-langVisibRules| + 2.7 Error Handling....................|luaref-langError| + 2.8 Metatables........................|luaref-langMetatables| + 2.9 Environments......................|luaref-langEnvironments| + 2.10 Garbage Collection...............|luaref-langGC| + 2.10.1 Garbage-Collection Metamethods.|luaref-langGCMeta| + 2.10.2 Weak Tables....................|luaref-langWeaktables| + 2.11 Coroutines.......................|luaref-langCoro| + + 3 THE APPLICATION PROGRAM INTERFACE...|luaref-api| + 3.1 The Stack.........................|luaref-apiStack| + 3.2 Stack Size........................|luaref-apiStackSize| + 3.3 Pseudo-Indices....................|luaref-apiPseudoIndices| + 3.4 C Closures........................|luaref-apiCClosures| + 3.5 Registry..........................|luaref-apiRegistry| + 3.6 Error Handling in C...............|luaref-apiError| + 3.7 Functions and Types...............|luaref-apiFunctions| + 3.8 The Debug Interface...............|luaref-apiDebug| + + 4 THE AUXILIARY LIBRARY...............|luaref-aux| + 4.1 Functions and Types...............|luaref-auxFunctions| + + 5 STANDARD LIBRARIES..................|luaref-lib| + 5.1 Basic Functions...................|luaref-libBasic| + 5.2 Coroutine Manipulation............|luaref-libCoro| + 5.3 Modules...........................|luaref-libModule| + 5.4 String Manipulation...............|luaref-libString| + 5.4.1 Patterns........................|luaref-libStringPat| + 5.5 Table Manipulation................|luaref-libTable| + 5.6 Mathematical Functions............|luaref-libMath| + 5.7 Input and Output Facilities.......|luaref-libIO| + 5.8 Operating System Facilities.......|luaref-libOS| + 5.9 The Debug Library.................|luaref-libDebug| + + A BIBLIOGRAPHY........................|luaref-bibliography| + B COPYRIGHT & LICENSES................|luaref-copyright| + C LUAREF DOC..........................|luaref-doc| + + +============================================================================== +1 INTRODUCTION *luaref-intro* +============================================================================== + +Lua is an extension programming language designed to support general +procedural programming with data description facilities. It also offers good +support for object-oriented programming, functional programming, and +data-driven programming. Lua is intended to be used as a powerful, +light-weight scripting language for any program that needs one. Lua is +implemented as a library, written in clean C (that is, in the common subset of +ANSI C and C++). + +Being an extension language, Lua has no notion of a "main" program: it only +works embedded in a host client, called the embedding program or simply the +host. This host program can invoke functions to execute a piece of Lua code, +can write and read Lua variables, and can register C functions to be called by +Lua code. Through the use of C functions, Lua can be augmented to cope with a +wide range of different domains, thus creating customized programming +languages sharing a syntactical framework. + +Lua is free software, and is provided as usual with no guarantees, as stated +in its license. The implementation described in this manual is available at +Lua's official web site, www.lua.org. + +Like any other reference manual, this document is dry in places. For a +discussion of the decisions behind the design of Lua, see references at +|luaref-bibliography|. For a detailed introduction to programming in Lua, see +Roberto's book, Programming in Lua. + +Lua means "moon" in Portuguese and is pronounced LOO-ah. + +============================================================================== +2 THE LANGUAGE *luaref-language* +============================================================================== + +This section describes the lexis, the syntax, and the semantics of Lua. In +other words, this section describes which tokens are valid, how they can be +combined, and what their combinations mean. + +The language constructs will be explained using the usual extended BNF +notation, in which { `a` } means 0 or more `a`'s, and [ `a` ] means an optional `a`. + +============================================================================== +2.1 Lexical Conventions *luaref-langLexConv* + + *luaref-names* *luaref-identifiers* +Names (also called identifiers) in Lua can be any string of letters, digits, +and underscores, not beginning with a digit. This coincides with the +definition of identifiers in most languages. (The definition of letter depends +on the current locale: any character considered alphabetic by the current +locale can be used in an identifier.) Identifiers are used to name variables +and table fields. + +The following keywords are reserved and cannot be used as names: +> + and break do else elseif + end false for function if + in local nil not or + repeat return then true until while +< +Lua is a case-sensitive language: `and` is a reserved word, but `And` and `AND` are +two different, valid names. As a convention, names starting with an underscore +followed by uppercase letters (such as `_VERSION`) are reserved for internal +global variables used by Lua. + +The following strings denote other tokens: +> + + - * / % ^ # + == ~= <= >= < > = + ( ) { } [ ] + ; : , . .. ... +< + *luaref-literal* +Literal strings can be delimited by matching single or double quotes, and can +contain the following C-like escape sequences: + + - `\a` bell + - `\b` backspace + - `\f` form feed + - `\n` newline + - `\r` carriage return + - `\t` horizontal tab + - `\v` vertical tab + - `\\` backslash + - `\"` quotation mark (double quote) + - `\'` apostrophe (single quote) + +Moreover, a backslash followed by a real newline results in a newline in the +string. A character in a string may also be specified by its numerical value +using the escape sequence `\ddd`, where `ddd` is a sequence of up to three +decimal digits. (Note that if a numerical escape is to be followed by a digit, +it must be expressed using exactly three digits.) Strings in Lua may contain +any 8-bit value, including embedded zeros, which can be specified as `\0`. + +To put a double (single) quote, a newline, a backslash, or an embedded zero +inside a literal string enclosed by double (single) quotes you must use an +escape sequence. Any other character may be directly inserted into the +literal. (Some control characters may cause problems for the file system, but +Lua has no problem with them.) + +Literal strings can also be defined using a long format enclosed by long +brackets. We define an opening long bracket of level n as an opening square +bracket followed by n equal signs followed by another opening square bracket. +So, an opening long bracket of level 0 is written as `[[`, an opening long +bracket of level 1 is written as `[=[`, and so on. +A closing long bracket is defined similarly; for instance, a closing long +bracket of level 4 is written as `]====]`. A long string starts with an +opening long bracket of any level and ends at the first closing long bracket +of the same level. Literals in this bracketed form may run for several lines, +do not interpret any escape sequences, and ignore long brackets of any other +level. They may contain anything except a closing bracket of the proper level. + +For convenience, when the opening long bracket is immediately followed by a +newline, the newline is not included in the string. As an example, in a system +using ASCII (in which `a` is coded as 97, newline is coded as 10, and `1` is +coded as 49), the five literals below denote the same string: +> + a = 'alo\n123"' + a = "alo\n123\"" + a = '\97lo\10\04923"' + a = [[alo + 123"]] + a = [==[ + alo + 123"]==] +< + *luaref-numconstant* +A numerical constant may be written with an optional decimal part and an +optional decimal exponent. Lua also accepts integer hexadecimal constants, by +prefixing them with `0x`. Examples of valid numerical constants are +> + 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56 +< + *luaref-comment* +A comment starts with a double hyphen (`--`) anywhere outside a string. If the +text immediately after `--` is not an opening long bracket, the comment is a +short comment, which runs until the end of the line. Otherwise, it is a long +comment, which runs until the corresponding closing long bracket. Long +comments are frequently used to disable code temporarily. + +============================================================================== +2.2 Values and Types *luaref-langValTypes* + +Lua is a dynamically typed language. This means that variables do not have +types; only values do. There are no type definitions in the language. All +values carry their own type. + +All values in Lua are first-class values. This means that all values can be +stored in variables, passed as arguments to other functions, and returned as +results. + + *luaref-types* *luaref-nil* + *luaref-true* *luaref-false* + *luaref-number* *luaref-string* +There are eight basic types in Lua: `nil`, `boolean`, `number`, `string`, +`function`, `userdata`, `thread`, and `table`. Nil is the type of the value +`nil`, whose main property is to be different from any other value; it usually +represents the absence of a useful value. Boolean is the type of the values +`false` and `true`. Both `nil` and `false` make a condition false; any other +value makes it true. Number represents real (double-precision floating-point) +numbers. (It is easy to build Lua interpreters that use other internal +representations for numbers, such as single-precision float or long integers; +see file `luaconf.h`.) String represents arrays of characters. Lua is 8-bit +clean: strings may contain any 8-bit character, including embedded zeros +(`\0`) (see |luaref-literal|). + +Lua can call (and manipulate) functions written in Lua and functions written +in C (see |luaref-langFuncCalls|). + + *luaref-userdatatype* +The type userdata is provided to allow arbitrary C data to be stored in Lua +variables. This type corresponds to a block of raw memory and has no +pre-defined operations in Lua, except assignment and identity test. However, +by using metatables, the programmer can define operations for userdata values +(see |luaref-langMetatables|). Userdata values cannot be created or modified +in Lua, only through the C API. This guarantees the integrity of data owned by +the host program. + + *luaref-thread* +The type `thread` represents independent threads of execution and it is used to +implement coroutines (see |luaref-langCoro|). Do not confuse Lua threads with +operating-system threads. Lua supports coroutines on all systems, even those +that do not support threads. + + *luaref-table* +The type `table` implements associative arrays, that is, arrays that can be +indexed not only with numbers, but with any value (except `nil`). Tables can +be heterogeneous; that is, they can contain values of all types (except +`nil`). Tables are the sole data structuring mechanism in Lua; they may be +used to represent ordinary arrays, symbol tables, sets, records, graphs, +trees, etc. To represent records, Lua uses the field name as an index. The +language supports this representation by providing `a.name` as syntactic sugar +for `a["name"]`. There are several convenient ways to create tables in Lua +(see |luaref-langTableConst|). + +Like indices, the value of a table field can be of any type (except `nil`). In +particular, because functions are first-class values, table fields may contain +functions. Thus tables may also carry methods (see |luaref-langFuncDefs|). + +Tables, functions, threads and (full) userdata values are objects: variables +do not actually contain these values, only references to them. Assignment, +parameter passing, and function returns always manipulate references to such +values; these operations do not imply any kind of copy. + +The library function `type` returns a string describing the type of a given +value (see |luaref-type|). + +------------------------------------------------------------------------------ +2.2.1 Coercion *luaref-langCoercion* + +Lua provides automatic conversion between string and number values at run +time. Any arithmetic operation applied to a string tries to convert that +string to a number, following the usual conversion rules. Conversely, whenever +a number is used where a string is expected, the number is converted to a +string, in a reasonable format. For complete control of how numbers are +converted to strings, use the `format` function from the string library (see +|luaref-string.format|). + +============================================================================== +2.3 Variables *luaref-langVariables* + +Variables are places that store values. There are three kinds of variables in +Lua: global variables, local variables, and table fields. + +A single name can denote a global variable or a local variable (or a +function's formal parameter, which is a particular form of local variable): +> + var ::= Name +< +Name denotes identifiers, as defined in |luaref-langLexConv|. + +Any variable is assumed to be global unless explicitly declared as a local +(see |luaref-langLocalDec|). Local variables are lexically scoped: local +variables can be freely accessed by functions defined inside their scope (see +|luaref-langVisibRules|). + +Before the first assignment to a variable, its value is `nil`. + +Square brackets are used to index a table: +> + var ::= prefixexp [ exp ] +< +The first expression (`prefixexp`) should result in a table value; the second +expression (`exp`) identifies a specific entry inside that table. The +expression denoting the table to be indexed has a restricted syntax; see +|luaref-langExpressions| for details. + +The syntax `var.NAME` is just syntactic sugar for `var["NAME"]` : +> + var ::= prefixexp . Name +< +All global variables live as fields in ordinary Lua tables, called environment +tables or simply environments (see |luaref-langEnvironments|). Each function +has its own reference to an environment, so that all global variables in this +function will refer to this environment table. When a function is created, it +inherits the environment from the function that created it. To get the +environment table of a Lua function, you call `getfenv` (see +|luaref-getfenv|). To replace it, you call `setfenv` (see |luaref-setfenv|). +(You can only manipulate the environment of C functions through the debug +library; see |luaref-libDebug|.) + +An access to a global variable `x` is equivalent to `_env.x`, which in turn is +equivalent to +> + gettable_event(_env, "x") +< +where `_env` is the environment of the running function. (The `_env` variable is +not defined in Lua. We use it here only for explanatory purposes.) + +The meaning of accesses to global variables and table fields can be changed +via metatables. An access to an indexed variable `t[i]` is equivalent to a +call `gettable_event(t,i)`. (See |luaref-langMetatables| for a complete +description of the `gettable_event` function. This function is not defined or +callable in Lua. We use it here only for explanatory purposes.) + +============================================================================== +2.4 Statements *luaref-langStats* + +Lua supports an almost conventional set of statements, similar to those in +Pascal or C. This set includes assignment, control structures, function +calls, and variable declarations. + +------------------------------------------------------------------------------ +2.4.1 Chunks *luaref-chunk* *luaref-langChunks* + +The unit of execution of Lua is called a chunk. A chunk is simply a sequence +of statements, which are executed sequentially. Each statement can be +optionally followed by a semicolon: +> + chunk ::= {stat [ ; ]} +< +There are no empty statements and thus `;;` is not legal. + +Lua handles a chunk as the body of an anonymous function with a variable +number of arguments (see |luaref-langFuncDefs|). As such, chunks can define +local variables, receive arguments, and return values. + +A chunk may be stored in a file or in a string inside the host program. When a +chunk is executed, first it is pre-compiled into instructions for a virtual +machine, and then the compiled code is executed by an interpreter for the +virtual machine. + +Chunks may also be pre-compiled into binary form; see program `luac` for +details. Programs in source and compiled forms are interchangeable; Lua +automatically detects the file type and acts accordingly. + +------------------------------------------------------------------------------ +2.4.2 Blocks *luaref-block* *luaref-langBlocks* + +A block is a list of statements; syntactically, a block is the same as a +chunk: +> + block ::= chunk +< + *luaref-do* *luaref-end* +A block may be explicitly delimited to produce a single statement: +> + stat ::= do block end +< +Explicit blocks are useful to control the scope of variable declarations. +Explicit blocks are also sometimes used to add a `return` or `break` statement +in the middle of another block (see |luaref-langContStructs|). + +------------------------------------------------------------------------------ +2.4.3 Assignment *luaref-langAssign* + +Lua allows multiple assignment. Therefore, the syntax for assignment defines a +list of variables on the left side and a list of expressions on the right +side. The elements in both lists are separated by commas: +> + stat ::= varlist1 = explist1 + varlist1 ::= var { , var } + explist1 ::= exp { , exp } +< +Expressions are discussed in |luaref-langExpressions|. + +Before the assignment, the list of values is adjusted to the length of the +list of variables. If there are more values than needed, the excess values are +thrown away. If there are fewer values than needed, the list is extended with +as many `nil`s as needed. If the list of expressions ends with a function +call, then all values returned by this call enter in the list of values, +before the adjustment (except when the call is enclosed in parentheses; see +|luaref-langExpressions|). + +The assignment statement first evaluates all its expressions and only then are +the assignments performed. Thus the code +> + i = 3 + i, a[i] = i+1, 20 +< +sets `a[3]` to 20, without affecting `a[4]` because the `i` in `a[i]` is evaluated (to +3) before it is assigned 4. Similarly, the line +> + x, y = y, x +< +exchanges the values of `x` and `y`. + +The meaning of assignments to global variables and table fields can be changed +via metatables. An assignment to an indexed variable `t[i] = val` is +equivalent to `settable_event(t,i,val)`. (See |luaref-langMetatables| for a +complete description of the `settable_event` function. This function is not +defined or callable in Lua. We use it here only for explanatory purposes.) + +An assignment to a global variable `x = val` is equivalent to the +assignment `_env.x = val`, which in turn is equivalent to +> + settable_event(_env, "x", val) +< +where `_env` is the environment of the running function. (The `_env` variable is +not defined in Lua. We use it here only for explanatory purposes.) + +------------------------------------------------------------------------------ +2.4.4 Control Structures *luaref-langContStructs* + + *luaref-if* *luaref-then* *luaref-else* *luaref-elseif* + *luaref-while* *luaref-repeat* *luaref-until* +The control structures `if`, `while`, and `repeat` have the usual meaning and +familiar syntax: +> + stat ::= while exp do block end + stat ::= repeat block until exp + stat ::= if exp then block { elseif exp then block } + [ else block ] end +< +Lua also has a `for` statement, in two flavors (see |luaref-langForStat|). + +The condition expression of a control structure may return any value. +Both `false` and `nil` are considered false. All values different +from `nil` and `false` are considered true (in particular, the number 0 and the +empty string are also true). + +In the `repeat-until` loop, the inner block does not end at the `until` keyword, +but only after the condition. So, the condition can refer to local variables +declared inside the loop block. + + *luaref-return* +The `return` statement is used to return values from a function or a chunk +(which is just a function). Functions and chunks may return more than one +value, so the syntax for the `return` statement is + + `stat ::=` `return` `[explist1]` + + *luaref-break* +The `break` statement is used to terminate the execution of a `while`, `repeat`, +or `for` loop, skipping to the next statement after the loop: + + `stat ::=` `break` + +A `break` ends the innermost enclosing loop. + +The `return` and `break` statements can only be written as the `last` +statement of a block. If it is really necessary to `return` or `break` in the +middle of a block, then an explicit inner block can be used, as in the idioms +`do return end` and `do break end`, because now `return` and `break` are +the last statements in their (inner) blocks. + +------------------------------------------------------------------------------ +2.4.5 For Statement *luaref-for* *luaref-langForStat* + +The `for` statement has two forms: one numeric and one generic. + +The numeric `for` loop repeats a block of code while a control variable runs +through an arithmetic progression. It has the following syntax: +> + stat ::= for Name = exp , exp [ , exp ] do block end +< +The `block` is repeated for `name` starting at the value of the first `exp`, until +it passes the second `exp` by steps of the third `exp`. More precisely, +a `for` statement like + + `for var =` `e1, e2, e3` `do` `block` `end` + +is equivalent to the code: + + `do` + `local` `var, limit, step` `= tonumber(e1), tonumber(e2), tonumber(e3)` + `if not (` `var` `and` `limit` `and` `step` `) then error() end` + `while (` `step` `>0 and` `var` `<=` `limit` `)` + `or (` `step` `<=0 and` `var` `>=` `limit` `) do` + `block` + `var` `=` `var` `+` `step` + `end` + `end` + +Note the following: + + - All three control expressions are evaluated only once, before the loop + starts. They must all result in numbers. + - `var`, `limit` and `step` are invisible variables. The names are here for + explanatory purposes only. + - If the third expression (the step) is absent, then a step of 1 is used. + - You can use `break` to exit a `for` loop. + - The loop variable `var` is local to the loop; you cannot use its value + after the `for` ends or is broken. If you need this value, assign it to + another variable before breaking or exiting the loop. + + *luaref-in* +The generic `for` statement works over functions, called iterators. On each +iteration, the iterator function is called to produce a new value, stopping +when this new value is `nil`. The generic `for` loop has the following syntax: +> + stat ::= for namelist in explist1 do block end + namelist ::= Name { , Name } +< +A `for` statement like + + `for` `var1, ..., varn` `in` `explist` `do` `block` `end` + +is equivalent to the code: + + `do` + `local` `f, s, var` `=` `explist` + `while true do` + `local` `var1, ..., varn` `=` `f(s, var)` + `var` `=` `var1` + `if` `var` `== nil then break end` + `block` + `end` + `end` + +Note the following: + + - `explist` is evaluated only once. Its results are an iterator function, + a `state`, and an initial value for the first iterator variable. + - `f`, `s`, and `var` are invisible variables. The names are here for + explanatory purposes only. + - You can use `break` to exit a `for` loop. + - The loop variables `var1, ..., varn` are local to the loop; you cannot use + their values after the `for` ends. If you need these values, then assign + them to other variables before breaking or exiting the loop. + +------------------------------------------------------------------------------ +2.4.6 Function Calls as Statements *luaref-langFuncStat* + +To allow possible side-effects, function calls can be executed as statements: +> + stat ::= functioncall +< +In this case, all returned values are thrown away. Function calls are +explained in |luaref-langFuncCalls|. + +------------------------------------------------------------------------------ +2.4.7 Local Declarations *luaref-local* *luaref-langLocalDec* + +Local variables may be declared anywhere inside a block. The declaration may +include an initial assignment: +> + stat ::= local namelist [ = explist1 ] + namelist ::= Name { , Name } +< +If present, an initial assignment has the same semantics of a multiple +assignment (see |luaref-langAssign|). Otherwise, all variables are initialized +with `nil`. + +A chunk is also a block (see |luaref-langChunks|), and so local variables can be +declared in a chunk outside any explicit block. The scope of such local +variables extends until the end of the chunk. + +The visibility rules for local variables are explained in +|luaref-langVisibRules|. + +============================================================================== +2.5 Expressions *luaref-langExpressions* + +The basic expressions in Lua are the following: +> + exp ::= prefixexp + exp ::= nil | false | true + exp ::= Number + exp ::= String + exp ::= function + exp ::= tableconstructor + exp ::= ... + exp ::= exp binop exp + exp ::= unop exp + prefixexp ::= var | functioncall | ( exp ) +< +Numbers and literal strings are explained in |luaref-langLexConv|; variables are +explained in |luaref-langVariables|; function definitions are explained in +|luaref-langFuncDefs|; function calls are explained in |luaref-langFuncCalls|; +table constructors are explained in |luaref-langTableConst|. Vararg expressions, +denoted by three dots (`...`), can only be used inside vararg functions; +they are explained in |luaref-langFuncDefs|. + +Binary operators comprise arithmetic operators (see |luaref-langArithOp|), +relational operators (see |luaref-langRelOp|), logical operators (see +|luaref-langLogOp|), and the concatenation operator (see |luaref-langConcat|). +Unary operators comprise the unary minus (see |luaref-labgArithOp|), the unary +`not` (see |luaref-langLogOp|), and the unary length operator (see +|luaref-langLength|). + +Both function calls and vararg expressions may result in multiple values. If +the expression is used as a statement (see |luaref-langFuncStat|) +(only possible for function calls), then its return list is adjusted to zero +elements, thus discarding all returned values. If the expression is used as +the last (or the only) element of a list of expressions, then no adjustment is +made (unless the call is enclosed in parentheses). In all other contexts, Lua +adjusts the result list to one element, discarding all values except the first +one. + +Here are some examples: +> + f() -- adjusted to 0 results + g(f(), x) -- f() is adjusted to 1 result + g(x, f()) -- g gets x plus all results from f() + a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) + a,b = ... -- a gets the first vararg parameter, b gets + -- the second (both a and b may get nil if there + -- is no corresponding vararg parameter) + + a,b,c = x, f() -- f() is adjusted to 2 results + a,b,c = f() -- f() is adjusted to 3 results + return f() -- returns all results from f() + return ... -- returns all received vararg parameters + return x,y,f() -- returns x, y, and all results from f() + {f()} -- creates a list with all results from f() + {...} -- creates a list with all vararg parameters + {f(), nil} -- f() is adjusted to 1 result +< +An expression enclosed in parentheses always results in only one value. Thus, +`(f(x,y,z))` is always a single value, even if `f` returns several values. +(The value of `(f(x,y,z))` is the first value returned by `f` or `nil` if `f` does not +return any values.) + +------------------------------------------------------------------------------ +2.5.1 Arithmetic Operators *luaref-langArithOp* + +Lua supports the usual arithmetic operators: the binary `+` (addition), +`-` (subtraction), `*` (multiplication), `/` (division), `%` (modulo) +and `^` (exponentiation); and unary `-` (negation). If the operands are numbers, +or strings that can be converted to numbers (see |luaref-langCoercion|), then all +operations have the usual meaning. Exponentiation works for any exponent. For +instance, `x^(-0.5)` computes the inverse of the square root of `x`. Modulo is +defined as +> + a % b == a - math.floor(a/b)*b +< +That is, it is the remainder of a division that rounds the quotient towards +minus infinity. + +------------------------------------------------------------------------------ +2.5.2 Relational Operators *luaref-langRelOp* + +The relational operators in Lua are +> + == ~= < > <= >= +< +These operators always result in `false` or `true`. + +Equality (`==`) first compares the type of its operands. If the types are +different, then the result is `false`. Otherwise, the values of the operands +are compared. Numbers and strings are compared in the usual way. Objects +(tables, userdata, threads, and functions) are compared by reference: two +objects are considered equal only if they are the same object. Every time you +create a new object (a table, userdata, or function), this new object is +different from any previously existing object. + +You can change the way that Lua compares tables and userdata using the "eq" +metamethod (see |luaref-langMetatables|). + +The conversion rules of coercion |luaref-langCoercion| do not apply to +equality comparisons. Thus, `"0"==0` evaluates to `false`, and `t[0]` and +`t["0"]` denote different entries in a table. + +The operator `~=` is exactly the negation of equality (`==`). + +The order operators work as follows. If both arguments are numbers, then they +are compared as such. Otherwise, if both arguments are strings, then their +values are compared according to the current locale. Otherwise, Lua tries to +call the "lt" or the "le" metamethod (see |luaref-langMetatables|). + +------------------------------------------------------------------------------ +2.5.3 Logical Operators *luaref-langLogOp* + +The logical operators in Lua are +> + and or not +< +Like the control structures (see |luaref-langContStructs|), all logical operators +consider both `false` and `nil` as false and anything else as true. + + *luaref-not* *luaref-and* *luaref-or* +The negation operator `not` always returns `false` or `true`. The conjunction +operator `and` returns its first argument if this value is `false` or `nil`; +otherwise, `and` returns its second argument. The disjunction +operator `or` returns its first argument if this value is different +from `nil` and `false`; otherwise, `or` returns its second argument. +Both `and` and `or` use short-cut evaluation, that is, the second operand is +evaluated only if necessary. Here are some examples: +> + 10 or 20 --> 10 + 10 or error() --> 10 + nil or "a" --> "a" + nil and 10 --> nil + false and error() --> false + false and nil --> false + false or nil --> nil + 10 and 20 --> 20 +< +(In this manual, `-->` indicates the result of the preceding expression.) + +------------------------------------------------------------------------------ +2.5.4 Concatenation *luaref-langConcat* + +The string concatenation operator in Lua is denoted by two dots (`..`). +If both operands are strings or numbers, then they are converted to strings +according to the rules mentioned in |luaref-langCoercion|. Otherwise, the +"concat" metamethod is called (see |luaref-langMetatables|). + +------------------------------------------------------------------------------ +2.5.5 The Length Operator *luaref-langLength* + +The length operator is denoted by the unary operator `#`. The length of a +string is its number of bytes (that is, the usual meaning of string length +when each character is one byte). + +The length of a table `t` is defined to be any integer index `n` such that `t[n]` is +not `nil` and `t[n+1]` is `nil`; moreover, if `t[1]` is `nil`, `n` may be zero. For a +regular array, with non-nil values from 1 to a given `n`, its length is exactly +that `n`, the index of its last value. If the array has "holes" (that +is, `nil` values between other non-nil values), then `#t` may be any of the +indices that directly precedes a `nil` value (that is, it may consider any +such `nil` value as the end of the array). + +------------------------------------------------------------------------------ +2.5.6 Precedence *luaref-langPrec* + +Operator precedence in Lua follows the table below, from lower to higher +priority: +> + or + and + < > <= >= ~= == + .. + + - + * / + not # - (unary) + ^ +< +As usual, you can use parentheses to change the precedences in an expression. +The concatenation (`..`) and exponentiation (`^`) operators are right +associative. All other binary operators are left associative. + +------------------------------------------------------------------------------ +2.5.7 Table Constructors *luaref-langTableConst* + +Table constructors are expressions that create tables. Every time a +constructor is evaluated, a new table is created. Constructors can be used to +create empty tables, or to create a table and initialize some of its fields. +The general syntax for constructors is +> + tableconstructor ::= { [ fieldlist ] } + fieldlist ::= field { fieldsep field } [ fieldsep ] + field ::= [ exp ] = exp | Name = exp | exp + fieldsep ::= , | ; +< +Each field of the form `[exp1] = exp2` adds to the new table an entry with +key `exp1` and value `exp2`. A field of the form `name = exp` is equivalent to +`["name"] = exp`. Finally, fields of the form `exp` are equivalent to +`[i] = exp`, where `i` are consecutive numerical integers, starting with 1. +Fields in the other formats do not affect this counting. For example, +> + a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } +< +is equivalent to +> + do + local t = {} + t[f(1)] = g + t[1] = "x" -- 1st exp + t[2] = "y" -- 2nd exp + t.x = 1 -- temp["x"] = 1 + t[3] = f(x) -- 3rd exp + t[30] = 23 + t[4] = 45 -- 4th exp + a = t + end +< +If the last field in the list has the form `exp` and the expression is a +function call, then all values returned by the call enter the list +consecutively (see |luaref-langFuncCalls|). To avoid this, enclose the function +call in parentheses (see |luaref-langExpressions|). + +The field list may have an optional trailing separator, as a convenience for +machine-generated code. + +------------------------------------------------------------------------------ +2.5.8 Function Calls *luaref-function* *luaref-langFuncCalls* + +A function call in Lua has the following syntax: +> + functioncall ::= prefixexp args +< +In a function call, first `prefixexp` and `args` are evaluated. If the value +of `prefixexp` has type `function`, then this function is called with the given +arguments. Otherwise, the `prefixexp` "call" metamethod is called, having as +first parameter the value of `prefixexp`, followed by the original call +arguments (see |luaref-langMetatables|). + +The form +> + functioncall ::= prefixexp : Name args +< +can be used to call "methods". A call `v:name(` `args` `)` is syntactic sugar +for `v.name(v,` `args` `)`, except that `v` is evaluated only once. + +Arguments have the following syntax: +> + args ::= ( [ explist1 ] ) + args ::= tableconstructor + args ::= String +< +All argument expressions are evaluated before the call. A call of the +form `f{` `fields` `}` is syntactic sugar for `f({` `fields` `})`, that is, the +argument list is a single new table. A call of the form `f'` `string` `'` +(or `f"` `string` `"` or `f[[` `string` `]]`) is syntactic sugar for +`f('` `string` `')`, that is, the argument list is a single literal string. + +As an exception to the free-format syntax of Lua, you cannot put a line break +before the `(` in a function call. This restriction avoids some ambiguities +in the language. If you write +> + a = f + (g).x(a) +< +Lua would see that as a single statement, `a = f(g).x(a)`. So, if you want two +statements, you must add a semi-colon between them. If you actually want to +call `f`, you must remove the line break before `(g)`. + + *luaref-tailcall* +A call of the form `return` `functioncall` is called a tail call. Lua +implements proper tail calls (or proper tail recursion): in a tail call, the +called function reuses the stack entry of the calling function. Therefore, +there is no limit on the number of nested tail calls that a program can +execute. However, a tail call erases any debug information about the calling +function. Note that a tail call only happens with a particular syntax, where +the `return` has one single function call as argument; this syntax makes the +calling function return exactly the returns of the called function. So, none +of the following examples are tail calls: +> + return (f(x)) -- results adjusted to 1 + return 2 * f(x) + return x, f(x) -- additional results + f(x); return -- results discarded + return x or f(x) -- results adjusted to 1 +< + +------------------------------------------------------------------------------ +2.5.9 Function Definitions *luaref-langFuncDefs* + +The syntax for function definition is +> + function ::= function funcbody + funcbody ::= ( [ parlist1 ] ) block end +< +The following syntactic sugar simplifies function definitions: +> + stat ::= function funcname funcbody + stat ::= local function Name funcbody + funcname ::= Name { . Name } [ : Name ] +< +The statement + + `function f ()` `body` `end` + +translates to + + `f = function ()` `body` `end` + +The statement + + `function t.a.b.c.f ()` `body` `end` + +translates to + + `t.a.b.c.f = function ()` `body` `end` + +The statement + + `local function f ()` `body` `end` + +translates to + + `local f; f = function f ()` `body` `end` + +not to + + `local f = function f ()` `body` `end` + +(This only makes a difference when the body of the function contains +references to `f`.) + + *luaref-closure* +A function definition is an executable expression, whose value has type +`function`. When Lua pre-compiles a chunk, all its function bodies are +pre-compiled too. Then, whenever Lua executes the function definition, the +function is instantiated (or closed). This function instance (or closure) is +the final value of the expression. Different instances of the same function +may refer to different external local variables and may have different +environment tables. + +Parameters act as local variables that are initialized with the argument +values: +> + parlist1 ::= namelist [ , ... ] | ... +< + *luaref-vararg* +When a function is called, the list of arguments is adjusted to the length of +the list of parameters, unless the function is a variadic or vararg function, +which is indicated by three dots (`...`) at the end of its parameter list. A +vararg function does not adjust its argument list; instead, it collects all +extra arguments and supplies them to the function through a vararg expression, +which is also written as three dots. The value of this expression is a list of +all actual extra arguments, similar to a function with multiple results. If a +vararg expression is used inside another expression or in the middle of a list +of expressions, then its return list is adjusted to one element. If the +expression is used as the last element of a list of expressions, then no +adjustment is made (unless the call is enclosed in parentheses). + +As an example, consider the following definitions: +> + function f(a, b) end + function g(a, b, ...) end + function r() return 1,2,3 end +< +Then, we have the following mapping from arguments to parameters and to the +vararg expression: +> + CALL PARAMETERS + + f(3) a=3, b=nil + f(3, 4) a=3, b=4 + f(3, 4, 5) a=3, b=4 + f(r(), 10) a=1, b=10 + f(r()) a=1, b=2 + + g(3) a=3, b=nil, ... --> (nothing) + g(3, 4) a=3, b=4, ... --> (nothing) + g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 + g(5, r()) a=5, b=1, ... --> 2 3 +< +Results are returned using the `return` statement (see |luaref-langContStructs|). +If control reaches the end of a function without encountering +a `return` statement, then the function returns with no results. + + *luaref-colonsyntax* +The colon syntax is used for defining methods, that is, functions that have an +implicit extra parameter `self`. Thus, the statement + + `function t.a.b.c:f (` `params` `)` `body` `end` + +is syntactic sugar for + + `t.a.b.c:f = function (self, (` `params` `)` `body` `end` + +============================================================================== +2.6 Visibility Rules *luaref-langVisibRules* + +Lua is a lexically scoped language. The scope of variables begins at the first +statement after their declaration and lasts until the end of the innermost +block that includes the declaration. Consider the following example: +> + x = 10 -- global variable + do -- new block + local x = x -- new `x`, with value 10 + print(x) --> 10 + x = x+1 + do -- another block + local x = x+1 -- another `x` + print(x) --> 12 + end + print(x) --> 11 + end + print(x) --> 10 (the global one) +< +Notice that, in a declaration like `local x = x`, the new `x` being declared is +not in scope yet, and so the second `x` refers to the outside variable. + + *luaref-upvalue* +Because of the lexical scoping rules, local variables can be freely accessed +by functions defined inside their scope. A local variable used by an inner +function is called an upvalue, or external local variable, inside the inner +function. + +Notice that each execution of a local statement defines new local variables. +Consider the following example: +> + a = {} + local x = 20 + for i=1,10 do + local y = 0 + a[i] = function () y=y+1; return x+y end + end +< +The loop creates ten closures (that is, ten instances of the anonymous +function). Each of these closures uses a different `y` variable, while all of +them share the same `x`. + +============================================================================== +2.7 Error Handling *luaref-langError* + +Because Lua is an embedded extension language, all Lua actions start from +C code in the host program calling a function from the Lua library (see +|luaref-lua_pcall|). Whenever an error occurs during Lua compilation or +execution, control returns to C, which can take appropriate measures (such as +print an error message). + +Lua code can explicitly generate an error by calling the `error` function (see +|luaref-error|). If you need to catch errors in Lua, you can use +the `pcall` function (see |luaref-pcall|). + +============================================================================== +2.8 Metatables *luaref-metatable* *luaref-langMetatables* + +Every value in Lua may have a metatable. This metatable is an ordinary Lua +table that defines the behavior of the original table and userdata under +certain special operations. You can change several aspects of the behavior of +an object by setting specific fields in its metatable. For instance, when a +non-numeric value is the operand of an addition, Lua checks for a function in +the field `"__add"` in its metatable. If it finds one, Lua calls that function +to perform the addition. + +We call the keys in a metatable events and the values metamethods. In the +previous example, the event is "add" and the metamethod is the function that +performs the addition. + +You can query the metatable of any value through the `getmetatable` function +(see |luaref-getmetatable|). + +You can replace the metatable of tables through the `setmetatable` function (see +|luaref-setmetatable|). You cannot change the metatable of other types from Lua +(except using the debug library); you must use the C API for that. + +Tables and userdata have individual metatables (although multiple tables and +userdata can share a same table as their metatable); values of all other types +share one single metatable per type. So, there is one single metatable for all +numbers, and for all strings, etc. + +A metatable may control how an object behaves in arithmetic operations, order +comparisons, concatenation, length operation, and indexing. A metatable can +also define a function to be called when a userdata is garbage collected. For +each of those operations Lua associates a specific key called an event. When +Lua performs one of those operations over a value, it checks whether this +value has a metatable with the corresponding event. If so, the value +associated with that key (the metamethod) controls how Lua will perform the +operation. + +Metatables control the operations listed next. Each operation is identified by +its corresponding name. The key for each operation is a string with its name +prefixed by two underscores, `__`; for instance, the key for operation "add" +is the string "__add". The semantics of these operations is better explained +by a Lua function describing how the interpreter executes that operation. + +The code shown here in Lua is only illustrative; the real behavior is hard +coded in the interpreter and it is much more efficient than this simulation. +All functions used in these descriptions (`rawget`, `tonumber`, etc.) are +described in |luaref-libBasic|. In particular, to retrieve the metamethod of a +given object, we use the expression +> + metatable(obj)[event] +< +This should be read as +> + rawget(metatable(obj) or {}, event) +< +That is, the access to a metamethod does not invoke other metamethods, and the +access to objects with no metatables does not fail (it simply results +in `nil`). + +"add": *__add()* +------ +the `+` operation. + +The function `getbinhandler` below defines how Lua chooses a handler for a +binary operation. First, Lua tries the first operand. If its type does not +define a handler for the operation, then Lua tries the second operand. +> + function getbinhandler (op1, op2, event) + return metatable(op1)[event] or metatable(op2)[event] + end +< +By using this function, the behavior of the `op1 + op2` is +> + function add_event (op1, op2) + local o1, o2 = tonumber(op1), tonumber(op2) + if o1 and o2 then -- both operands are numeric? + return o1 + o2 -- `+` here is the primitive `add` + else -- at least one of the operands is not numeric + local h = getbinhandler(op1, op2, "__add") + if h then + -- call the handler with both operands + return h(op1, op2) + else -- no handler available: default behavior + error(...) + end + end + end +< +"sub": *__sub()* +------ +the `-` operation. Behavior similar to the "add" operation. + +"mul": *__mul()* +------ +the `*` operation. Behavior similar to the "add" operation. + +"div": *__div()* +------ +the `/` operation. Behavior similar to the "add" operation. + +"mod": *__mod()* +------ +the `%` operation. Behavior similar to the "add" operation, with the +operation `o1 - floor(o1/o2)*o2` as the primitive operation. + +"pow": *__pow()* +------ +the `^` (exponentiation) operation. Behavior similar to the "add" operation, +with the function `pow` (from the C math library) as the primitive operation. + +"unm": *__unm()* +------ +the unary `-` operation. +> + function unm_event (op) + local o = tonumber(op) + if o then -- operand is numeric? + return -o -- `-` here is the primitive `unm` + else -- the operand is not numeric. + -- Try to get a handler from the operand + local h = metatable(op).__unm + if h then + -- call the handler with the operand + return h(op) + else -- no handler available: default behavior + error(...) + end + end + end +< +"concat": *__concat()* +--------- +the `..` (concatenation) operation. +> + function concat_event (op1, op2) + if (type(op1) == "string" or type(op1) == "number") and + (type(op2) == "string" or type(op2) == "number") then + return op1 .. op2 -- primitive string concatenation + else + local h = getbinhandler(op1, op2, "__concat") + if h then + return h(op1, op2) + else + error(...) + end + end + end +< +"len": *__len()* +------ +the `#` operation. +> + function len_event (op) + if type(op) == "string" then + return strlen(op) -- primitive string length + elseif type(op) == "table" then + return #op -- primitive table length + else + local h = metatable(op).__len + if h then + -- call the handler with the operand + return h(op) + else -- no handler available: default behavior + error(...) + end + end + end +< +"eq": *__eq()* +----- +the `==` operation. + +The function `getcomphandler` defines how Lua chooses a metamethod for +comparison operators. A metamethod only is selected when both objects being +compared have the same type and the same metamethod for the selected +operation. +> + function getcomphandler (op1, op2, event) + if type(op1) ~= type(op2) then return nil end + local mm1 = metatable(op1)[event] + local mm2 = metatable(op2)[event] + if mm1 == mm2 then return mm1 else return nil end + end +< +The "eq" event is defined as follows: +> + function eq_event (op1, op2) + if type(op1) ~= type(op2) then -- different types? + return false -- different objects + end + if op1 == op2 then -- primitive equal? + return true -- objects are equal + end + -- try metamethod + local h = getcomphandler(op1, op2, "__eq") + if h then + return h(op1, op2) + else + return false + end + end +< +`a ~= b` is equivalent to `not (a == b)`. + +"lt": *__lt()* +----- +the `<` operation. +> + function lt_event (op1, op2) + if type(op1) == "number" and type(op2) == "number" then + return op1 < op2 -- numeric comparison + elseif type(op1) == "string" and type(op2) == "string" then + return op1 < op2 -- lexicographic comparison + else + local h = getcomphandler(op1, op2, "__lt") + if h then + return h(op1, op2) + else + error(...); + end + end + end +< +`a > b` is equivalent to `b < a`. + +"le": *__le()* +----- +the `<=` operation. +> + function le_event (op1, op2) + if type(op1) == "number" and type(op2) == "number" then + return op1 <= op2 -- numeric comparison + elseif type(op1) == "string" and type(op2) == "string" then + return op1 <= op2 -- lexicographic comparison + else + local h = getcomphandler(op1, op2, "__le") + if h then + return h(op1, op2) + else + h = getcomphandler(op1, op2, "__lt") + if h then + return not h(op2, op1) + else + error(...); + end + end + end + end +< +`a >= b` is equivalent to `b <= a`. Note that, in the absence of a "le" +metamethod, Lua tries the "lt", assuming that `a <= b` is equivalent +to `not (b < a)`. + +"index": *__index()* +-------- +The indexing access `table[key]`. +> + function gettable_event (table, key) + local h + if type(table) == "table" then + local v = rawget(table, key) + if v ~= nil then return v end + h = metatable(table).__index + if h == nil then return nil end + else + h = metatable(table).__index + if h == nil then + error(...); + end + end + if type(h) == "function" then + return h(table, key) -- call the handler + else return h[key] -- or repeat operation on it + end +< +"newindex": *__newindex()* +----------- +The indexing assignment `table[key] = value`. +> + function settable_event (table, key, value) + local h + if type(table) == "table" then + local v = rawget(table, key) + if v ~= nil then rawset(table, key, value); return end + h = metatable(table).__newindex + if h == nil then rawset(table, key, value); return end + else + h = metatable(table).__newindex + if h == nil then + error(...); + end + end + if type(h) == "function" then + return h(table, key,value) -- call the handler + else h[key] = value -- or repeat operation on it + end +< +"call": *__call()* +------- +called when Lua calls a value. +> + function function_event (func, ...) + if type(func) == "function" then + return func(...) -- primitive call + else + local h = metatable(func).__call + if h then + return h(func, ...) + else + error(...) + end + end + end +< + +============================================================================== +2.9 Environments *luaref-environment* *luaref-langEnvironments* + +Besides metatables, objects of types thread, function, and userdata have +another table associated with them, called their environment. Like metatables, +environments are regular tables and multiple objects can share the same +environment. + +Environments associated with userdata have no meaning for Lua. It is only a +convenience feature for programmers to associate a table to a userdata. + +Environments associated with threads are called global environments. They are +used as the default environment for their threads and non-nested functions +created by the thread (through `loadfile` |luaref-loadfile|, `loadstring` +|luaref-loadstring| or `load` |luaref-load|) and can be directly accessed by C +code (see |luaref-apiPseudoIndices|). + +Environments associated with C functions can be directly accessed by C code +(see |luaref-apiPseudoIndices|). They are used as the default environment for +other C functions created by the function. + +Environments associated with Lua functions are used to resolve all accesses to +global variables within the function (see |luaref-langVariables|). They are +used as the default environment for other Lua functions created by the +function. + +You can change the environment of a Lua function or the running thread by +calling `setfenv` (see |luaref-setenv|). You can get the environment of a Lua +function or the running thread by calling `getfenv` (see |luaref-getfenv|). To +manipulate the environment of other objects (userdata, C functions, other +threads) you must use the C API. + +============================================================================== +2.10 Garbage Collection *luaref-langGC* + +Lua performs automatic memory management. This means that you do not have to +worry neither about allocating memory for new objects nor about freeing it +when the objects are no longer needed. Lua manages memory automatically by +running a garbage collector from time to time to collect all dead objects +(that is, these objects that are no longer accessible from Lua). All objects +in Lua are subject to automatic management: tables, userdata, functions, +threads, and strings. + +Lua implements an incremental mark-and-sweep collector. It uses two numbers to +control its garbage-collection cycles: the garbage-collector pause and the +garbage-collector step multiplier. + +The garbage-collector pause controls how long the collector waits before +starting a new cycle. Larger values make the collector less aggressive. Values +smaller than 1 mean the collector will not wait to start a new cycle. A value +of 2 means that the collector waits for the total memory in use to double +before starting a new cycle. + +The step multiplier controls the relative speed of the collector relative to +memory allocation. Larger values make the collector more aggressive but also +increase the size of each incremental step. Values smaller than 1 make the +collector too slow and may result in the collector never finishing a cycle. +The default, 2, means that the collector runs at "twice" the speed of memory +allocation. + +You can change these numbers by calling `lua_gc` (see |luaref-lua_gc|) in C or +`collectgarbage` (see |luaref-collectgarbage|) in Lua. Both get percentage +points as arguments (so an argument of 100 means a real value of 1). With +these functions you can also control the collector directly (e.g., stop and +restart it). + +------------------------------------------------------------------------------ +2.10.1 Garbage-Collection Metamethods *luaref-langGCMeta* + +Using the C API, you can set garbage-collector metamethods for userdata (see +|luaref-langMetatables|). These metamethods are also called finalizers. +Finalizers allow you to coordinate Lua's garbage collection with external +resource management (such as closing files, network or database connections, +or freeing your own memory). + + *__gc* +Garbage userdata with a field `__gc` in their metatables are not collected +immediately by the garbage collector. Instead, Lua puts them in a list. After +the collection, Lua does the equivalent of the following function for each +userdata in that list: +> + function gc_event (udata) + local h = metatable(udata).__gc + if h then + h(udata) + end + end +< +At the end of each garbage-collection cycle, the finalizers for userdata are +called in reverse order of their creation, among these collected in that +cycle. That is, the first finalizer to be called is the one associated with +the userdata created last in the program. + +------------------------------------------------------------------------------ +2.10.2 - Weak Tables *luaref-weaktable* *luaref-langWeaktables* + +A weak table is a table whose elements are weak references. A weak reference +is ignored by the garbage collector. In other words, if the only references to +an object are weak references, then the garbage collector will collect this +object. + + *__mode* +A weak table can have weak keys, weak values, or both. A table with weak keys +allows the collection of its keys, but prevents the collection of its values. +A table with both weak keys and weak values allows the collection of both keys +and values. In any case, if either the key or the value is collected, the +whole pair is removed from the table. The weakness of a table is controlled by +the value of the `__mode` field of its metatable. If the `__mode` field is a +string containing the character `k`, the keys in the table are weak. +If `__mode` contains `v`, the values in the table are weak. + +After you use a table as a metatable, you should not change the value of its +field `__mode`. Otherwise, the weak behavior of the tables controlled by this +metatable is undefined. + +============================================================================== +2.11 Coroutines *luaref-coroutine* *luaref-langCoro* + +Lua supports coroutines, also called collaborative multithreading. A coroutine +in Lua represents an independent thread of execution. Unlike threads in +multithread systems, however, a coroutine only suspends its execution by +explicitly calling a yield function. + +You create a coroutine with a call to `coroutine.create` (see +|luaref-coroutine.create|). Its sole argument is a function that is the main +function of the coroutine. The `create` function only creates a new coroutine +and returns a handle to it (an object of type `thread`); it does not start the +coroutine execution. + +When you first call `coroutine.resume` (see |luaref-coroutine.resume|), +passing as its first argument the thread returned by `coroutine.create`, the +coroutine starts its execution, at the first line of its main function. Extra +arguments passed to `coroutine.resume` are passed on to the coroutine main +function. After the coroutine starts running, it runs until it terminates or +`yields`. + +A coroutine can terminate its execution in two ways: normally, when its main +function returns (explicitly or implicitly, after the last instruction); and +abnormally, if there is an unprotected error. In the first case, +`coroutine.resume` returns `true`, plus any values returned by the coroutine +main function. In case of errors, `coroutine.resume` returns `false` plus an +error message. + +A coroutine yields by calling `coroutine.yield` (see +|luaref-coroutine.yield|). When a coroutine yields, the corresponding +`coroutine.resume` returns immediately, even if the yield happens inside +nested function calls (that is, not in the main function, but in a function +directly or indirectly called by the main function). In the case of a yield, +`coroutine.resume` also returns `true`, plus any values passed to +`coroutine.yield`. The next time you resume the same coroutine, it continues +its execution from the point where it yielded, with the call to +`coroutine.yield` returning any extra arguments passed to `coroutine.resume`. + +Like `coroutine.create`, the `coroutine.wrap` function (see +|luaref-coroutine.wrap|) also creates a coroutine, but instead of returning +the coroutine itself, it returns a function that, when called, resumes the +coroutine. Any arguments passed to this function go as extra arguments to +`coroutine.resume`. `coroutine.wrap` returns all the values returned by +`coroutine.resume`, except the first one (the boolean error code). Unlike +`coroutine.resume`, `coroutine.wrap` does not catch errors; any error is +propagated to the caller. + +As an example, consider the next code: +> + function foo1 (a) + print("foo", a) + return coroutine.yield(2*a) + end + + co = coroutine.create(function (a,b) + print("co-body", a, b) + local r = foo1(a+1) + print("co-body", r) + local r, s = coroutine.yield(a+b, a-b) + print("co-body", r, s) + return b, "end" + end) + + print("main", coroutine.resume(co, 1, 10)) + print("main", coroutine.resume(co, "r")) + print("main", coroutine.resume(co, "x", "y")) + print("main", coroutine.resume(co, "x", "y")) +< +When you run it, it produces the following output: +> + co-body 1 10 + foo 2 + main true 4 + co-body r + main true 11 -9 + co-body x y + main true 10 end + main false cannot resume dead coroutine +< + +============================================================================== +3 THE APPLICATION PROGRAM INTERFACE *luaref-API* +============================================================================== + +This section describes the C API for Lua, that is, the set of C functions +available to the host program to communicate with Lua. All API functions and +related types and constants are declared in the header file `lua.h`. + +Even when we use the term "function", any facility in the API may be provided +as a `macro` instead. All such macros use each of its arguments exactly once +(except for the first argument, which is always a Lua state), and so do not +generate hidden side-effects. + +As in most C libraries, the Lua API functions do not check their arguments for +validity or consistency. However, you can change this behavior by compiling +Lua with a proper definition for the macro `luai_apicheck`,in file +`luaconf.h`. + +============================================================================== +3.1 The Stack *luaref-stack* *luaref-apiStack* + +Lua uses a virtual stack to pass values to and from C. Each element in this +stack represents a Lua value (`nil`, number, string, etc.). + +Whenever Lua calls C, the called function gets a new stack, which is +independent of previous stacks and of stacks of C functions that are still +active. This stack initially contains any arguments to the C function and it +is where the C function pushes its results to be returned to the caller (see +|luaref-lua_CFunction|). + + *luaref-stackindex* +For convenience, most query operations in the API do not follow a strict stack +discipline. Instead, they can refer to any element in the stack by using an +index: a positive index represents an absolute stack position (starting at 1); +a negative index represents an offset from the top of the stack. More +specifically, if the stack has `n` elements, then index 1 represents the first +element (that is, the element that was pushed onto the stack first) and index +`n` represents the last element; index `-1` also represents the last element +(that is, the element at the top) and index `-n` represents the first element. +We say that an index is valid if it lies between 1 and the stack top (that is, +if `1 <= abs(index) <= top`). + +============================================================================== +3.2 Stack Size *luaref-apiStackSize* + +When you interact with Lua API, you are responsible for ensuring consistency. +In particular, you are responsible for controlling stack overflow. You can +use the function `lua_checkstack` to grow the stack size (see +|luaref-lua_checkstack|). + +Whenever Lua calls C, it ensures that at least `LUA_MINSTACK` stack positions +are available. `LUA_MINSTACK` is defined as 20, so that usually you do not +have to worry about stack space unless your code has loops pushing elements +onto the stack. + +Most query functions accept as indices any value inside the available stack +space, that is, indices up to the maximum stack size you have set through +`lua_checkstack`. Such indices are called acceptable indices. More formally, +we define an acceptable index as follows: +> + (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace) +< +Note that 0 is never an acceptable index. + +============================================================================== +3.3 Pseudo-Indices *luaref-pseudoindex* *luaref-apiPseudoIndices* + +Unless otherwise noted, any function that accepts valid indices can also be +called with pseudo-indices, which represent some Lua values that are +accessible to the C code but which are not in the stack. Pseudo-indices are +used to access the thread environment, the function environment, the registry, +and the upvalues of a C function (see |luaref-apiCClosures|). + +The thread environment (where global variables live) is always at pseudo-index +`LUA_GLOBALSINDEX`. The environment of the running C function is always at +pseudo-index `LUA_ENVIRONINDEX`. + +To access and change the value of global variables, you can use regular table +operations over an environment table. For instance, to access the value of a +global variable, do +> + lua_getfield(L, LUA_GLOBALSINDEX, varname); +< + +============================================================================== +3.4 C Closures *luaref-cclosure* *luaref-apiCClosures* + +When a C function is created, it is possible to associate some values with it, +thus creating a C closure; these values are called upvalues and are accessible +to the function whenever it is called (see |luaref-lua_pushcclosure|). + +Whenever a C function is called, its upvalues are located at specific +pseudo-indices. These pseudo-indices are produced by the macro +`lua_upvalueindex` (see |luaref-lua_upvalueindex|). The first value associated +with a function is at position `lua_upvalueindex(1)`, and so on. Any access to +`lua_upvalueindex(` `n` `)`, where `n` is greater than the number of upvalues of +the current function, produces an acceptable (but invalid) index. + +============================================================================== +3.5 Registry *luaref-registry* *luaref-apiRegistry* + +Lua provides a registry, a pre-defined table that can be used by any C code to +store whatever Lua value it needs to store. This table is always located at +pseudo-index `LUA_REGISTRYINDEX`. Any C library can store data into this +table, but it should take care to choose keys different from those used by +other libraries, to avoid collisions. Typically, you should use as key a +string containing your library name or a light userdata with the address of a +C object in your code. + +The integer keys in the registry are used by the reference mechanism, +implemented by the auxiliary library, and therefore should not be used for +other purposes. + +============================================================================== +3.6 Error Handling in C *luaref-apiError* + +Internally, Lua uses the C `longjmp` facility to handle errors. (You can also +choose to use exceptions if you use C++; see file `luaconf.h`.) When Lua faces +any error (such as memory allocation errors, type errors, syntax errors, and +runtime errors) it raises an error; that is, it does a long jump. A protected +environment uses `setjmp` to set a recover point; any error jumps to the most +recent active recover point. + +Almost any function in the API may raise an error, for instance due to a +memory allocation error. The following functions run in protected mode (that +is, they create a protected environment to run), so they never raise an error: +`lua_newstate`, `lua_close`, `lua_load`, `lua_pcall`, and `lua_cpcall` (see +|luaref-lua_newstate|, |luaref-lua_close|, |luaref-lua_load|, +|luaref-lua_pcall|, and |luaref-lua_cpcall|). + +Inside a C function you can raise an error by calling `lua_error` (see +|luaref-lua_error|). + +============================================================================== +3.7 Functions and Types *luaref-apiFunctions* + +Here we list all functions and types from the C API in alphabetical order. + +lua_Alloc *lua_Alloc()* +> + typedef void * (*lua_Alloc) (void *ud, + void *ptr, + size_t osize, + size_t nsize); +< + The type of the memory-allocation function used by Lua states. The + allocator function must provide a functionality similar to `realloc`, + but not exactly the same. Its arguments are `ud`, an opaque pointer + passed to `lua_newstate` (see |luaref-lua_newstate|); `ptr`, a pointer + to the block being allocated/reallocated/freed; `osize`, the original + size of the block; `nsize`, the new size of the block. `ptr` is `NULL` + if and only if `osize` is zero. When `nsize` is zero, the allocator + must return `NULL`; if `osize` is not zero, it should free the block + pointed to by `ptr`. When `nsize` is not zero, the allocator returns + `NULL` if and only if it cannot fill the request. When `nsize` is not + zero and `osize` is zero, the allocator should behave like `malloc`. + When `nsize` and `osize` are not zero, the allocator behaves like + `realloc`. Lua assumes that the allocator never fails when `osize >= + nsize`. + + Here is a simple implementation for the allocator function. It is used + in the auxiliary library by `luaL_newstate` (see + |luaref-luaL_newstate|). +> + static void *l_alloc (void *ud, void *ptr, size_t osize, + size_t nsize) { + (void)ud; (void)osize; /* not used */ + if (nsize == 0) { + free(ptr); + return NULL; + } + else + return realloc(ptr, nsize); + } +< + This code assumes that `free(NULL)` has no effect and that + `realloc(NULL, size)` is equivalent to `malloc(size)`. ANSI C ensures both + behaviors. + +lua_atpanic *lua_atpanic()* +> + lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf); +< + Sets a new panic function and returns the old one. + + If an error happens outside any protected environment, Lua calls a + `panic` `function` and then calls `exit(EXIT_FAILURE)`, thus exiting + the host application. Your panic function may avoid this exit by never + returning (e.g., doing a long jump). + + The panic function can access the error message at the top of the + stack. + +lua_call *lua_call()* +> + void lua_call (lua_State *L, int nargs, int nresults); +< + Calls a function. + + To call a function you must use the following protocol: first, the + function to be called is pushed onto the stack; then, the arguments to + the function are pushed in direct order; that is, the first argument + is pushed first. Finally you call `lua_call`; `nargs` is the number of + arguments that you pushed onto the stack. All arguments and the + function value are popped from the stack when the function is called. + The function results are pushed onto the stack when the function + returns. The number of results is adjusted to `nresults`, unless + `nresults` is `LUA_MULTRET`. In this case, `all` results from the + function are pushed. Lua takes care that the returned values fit into + the stack space. The function results are pushed onto the stack in + direct order (the first result is pushed first), so that after the + call the last result is on the top of the stack. + + Any error inside the called function is propagated upwards (with a + `longjmp`). + + The following example shows how the host program may do the equivalent + to this Lua code: +> + a = f("how", t.x, 14) +< + Here it is in C: +> + lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be called + lua_pushstring(L, "how"); // 1st argument + lua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexed + lua_getfield(L, -1, "x"); // push result of t.x (2nd arg) + lua_remove(L, -2); // remove 't' from the stack + lua_pushinteger(L, 14); // 3rd argument + lua_call(L, 3, 1); // call 'f' with 3 arguments and 1 result + lua_setfield(L, LUA_GLOBALSINDEX, "a"); // set global 'a' +< + Note that the code above is "balanced": at its end, the stack is back + to its original configuration. This is considered good programming + practice. + +lua_CFunction *luaref-cfunction* *lua_CFunction()* +> + typedef int (*lua_CFunction) (lua_State *L); +< + Type for C functions. + + In order to communicate properly with Lua, a C function must use the + following protocol, which defines the way parameters and results are + passed: a C function receives its arguments from Lua in its stack in + direct order (the first argument is pushed first). So, when the + function starts, `lua_gettop(L)` (see |luaref-lua_gettop|) returns the + number of arguments received by the function. The first argument (if + any) is at index 1 and its last argument is at index `lua_gettop(L)`. + To return values to Lua, a C function just pushes them onto the stack, + in direct order (the first result is pushed first), and returns the + number of results. Any other value in the stack below the results will + be properly discarded by Lua. Like a Lua function, a C function called + by Lua can also return many results. + + *luaref-cfunctionexample* + As an example, the following function receives a variable number of + numerical arguments and returns their average and sum: +> + static int foo (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + lua_Number sum = 0; + int i; + for (i = 1; i <= n; i++) { + if (!lua_isnumber(L, i)) { + lua_pushstring(L, "incorrect argument"); + lua_error(L); + } + sum += lua_tonumber(L, i); + } + lua_pushnumber(L, sum/n); /* first result */ + lua_pushnumber(L, sum); /* second result */ + return 2; /* number of results */ + } +< + +lua_checkstack *lua_checkstack()* +> + int lua_checkstack (lua_State *L, int extra); +< + Ensures that there are at least `extra` free stack slots in the stack. + It returns false if it cannot grow the stack to that size. This + function never shrinks the stack; if the stack is already larger than + the new size, it is left unchanged. + +lua_close *lua_close()* +> + void lua_close (lua_State *L); +< + Destroys all objects in the given Lua state (calling the corresponding + garbage-collection metamethods, if any) and frees all dynamic memory + used by this state. On several platforms, you may not need to call + this function, because all resources are naturally released when the + host program ends. On the other hand, long-running programs, such as a + daemon or a web server, might need to release states as soon as they + are not needed, to avoid growing too large. + +lua_concat *lua_concat()* +> + void lua_concat (lua_State *L, int n); +< + Concatenates the `n` values at the top of the stack, pops them, and + leaves the result at the top. If `n` is 1, the result is the single + string on the stack (that is, the function does nothing); if `n` is 0, + the result is the empty string. Concatenation is done following the + usual semantics of Lua (see |luaref-langConcat|). + +lua_cpcall *lua_cpcall()* +> + int lua_cpcall (lua_State *L, lua_CFunction func, void *ud); +< + Calls the C function `func` in protected mode. `func` starts with only + one element in its stack, a light userdata containing `ud`. In case of + errors, `lua_cpcall` returns the same error codes as `lua_pcall` (see + |luaref-lua_pcall|), plus the error object on the top of the stack; + otherwise, it returns zero, and does not change the stack. All values + returned by `func` are discarded. + +lua_createtable *lua_createtable()* +> + void lua_createtable (lua_State *L, int narr, int nrec); +< + Creates a new empty table and pushes it onto the stack. The new table + has space pre-allocated for `narr` array elements and `nrec` non-array + elements. This pre-allocation is useful when you know exactly how many + elements the table will have. Otherwise you can use the function + `lua_newtable` (see |luaref-lua_newtable|). + +lua_dump *lua_dump()* +> + int lua_dump (lua_State *L, lua_Writer writer, void *data); +< + Dumps a function as a binary chunk. Receives a Lua function on the top + of the stack and produces a binary chunk that, if loaded again, + results in a function equivalent to the one dumped. As it produces + parts of the chunk, `lua_dump` calls function `writer` (see + |luaref-lua_Writer|) with the given `data` to write them. + + The value returned is the error code returned by the last call to the + writer; 0 means no errors. + + This function does not pop the Lua function from the stack. + +lua_equal *lua_equal()* +> + int lua_equal (lua_State *L, int index1, int index2); +< + Returns 1 if the two values in acceptable indices `index1` and + `index2` are equal, following the semantics of the Lua `==` operator + (that is, may call metamethods). Otherwise returns 0. Also returns 0 + if any of the indices is non valid. + +lua_error *lua_error()* +> + int lua_error (lua_State *L); +< + Generates a Lua error. The error message (which can actually be a Lua + value of any type) must be on the stack top. This function does a long + jump, and therefore never returns (see |luaref-luaL_error|). + +lua_gc *lua_gc()* +> + int lua_gc (lua_State *L, int what, int data); +< + Controls the garbage collector. + + This function performs several tasks, according to the value of the + parameter `what`: + + `LUA_GCSTOP` stops the garbage collector. + `LUA_GCRESTART` restarts the garbage collector. + `LUA_GCCOLLECT` performs a full garbage-collection cycle. + `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in + use by Lua. + `LUA_GCCOUNTB` returns the remainder of dividing the current + amount of bytes of memory in use by Lua by 1024. + `LUA_GCSTEP` performs an incremental step of garbage collection. + The step "size" is controlled by `data` (larger + values mean more steps) in a non-specified way. If + you want to control the step size you must + experimentally tune the value of `data`. The + function returns 1 if the step finished a + garbage-collection cycle. + `LUA_GCSETPAUSE` sets `data` /100 as the new value for the + `pause` of the collector (see |luaref-langGC|). + The function returns the previous value of the + pause. + `LUA_GCSETSTEPMUL` sets `data` /100 as the new value for the + `step` `multiplier` of the collector (see + |luaref-langGC|). The function returns the + previous value of the step multiplier. + +lua_getallocf *lua_getallocf()* +> + lua_Alloc lua_getallocf (lua_State *L, void **ud); +< + Returns the memory-allocation function of a given state. If `ud` is + not `NULL`, Lua stores in `*ud` the opaque pointer passed to + `lua_newstate` (see |luaref-lua_newstate|). + +lua_getfenv *lua_getfenv()* +> + void lua_getfenv (lua_State *L, int index); +< + Pushes onto the stack the environment table of the value at the given + index. + +lua_getfield *lua_getfield()* +> + void lua_getfield (lua_State *L, int index, const char *k); +< + Pushes onto the stack the value `t[k]`, where `t` is the value at the + given valid index `index`. As in Lua, this function may trigger a + metamethod for the "index" event (see |luaref-langMetatables|). + +lua_getglobal *lua_getglobal()* +> + void lua_getglobal (lua_State *L, const char *name); +< + Pushes onto the stack the value of the global `name`. It is defined as + a macro: +> + #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s) +< + +lua_getmetatable *lua_getmetatable()* +> + int lua_getmetatable (lua_State *L, int index); +< + Pushes onto the stack the metatable of the value at the given + acceptable index. If the index is not valid, or if the value does not + have a metatable, the function returns 0 and pushes nothing on the + stack. + +lua_gettable *lua_gettable()* +> + void lua_gettable (lua_State *L, int index); +< + Pushes onto the stack the value `t[k]`, where `t` is the value at the + given valid index `index` and `k` is the value at the top of the + stack. + + This function pops the key from the stack (putting the resulting value + in its place). As in Lua, this function may trigger a metamethod for + the "index" event (see |luaref-langMetatables|). + +lua_gettop *lua_gettop()* +> + int lua_gettop (lua_State *L); +< + Returns the index of the top element in the stack. Because indices + start at 1, this result is equal to the number of elements in the + stack (and so + 0 means an empty stack). + +lua_insert *lua_insert()* +> + void lua_insert (lua_State *L, int index); +< + Moves the top element into the given valid index, shifting up the + elements above this index to open space. Cannot be called with a + pseudo-index, because a pseudo-index is not an actual stack position. + +lua_Integer *lua_Integer()* +> + typedef ptrdiff_t lua_Integer; +< + The type used by the Lua API to represent integral values. + + By default it is a `ptrdiff_t`, which is usually the largest integral + type the machine handles "comfortably". + +lua_isboolean *lua_isboolean()* +> + int lua_isboolean (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index has type boolean, + and 0 otherwise. + +lua_iscfunction *lua_iscfunction()* +> + int lua_iscfunction (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a C function, + and 0 otherwise. + +lua_isfunction *lua_isfunction()* +> + int lua_isfunction (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a function + (either C or Lua), and 0 otherwise. + +lua_islightuserdata *lua_islightuserdata()* +> + int lua_islightuserdata (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a light + userdata, and 0 otherwise. + +lua_isnil *lua_isnil()* +> + int lua_isnil (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is `nil`, and 0 + otherwise. + +lua_isnumber *lua_isnumber()* +> + int lua_isnumber (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a number or a + string convertible to a number, and 0 otherwise. + +lua_isstring *lua_isstring()* +> + int lua_isstring (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a string or a + number (which is always convertible to a string), and 0 otherwise. + +lua_istable *lua_istable()* +> + int lua_istable (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a table, and + 0 otherwise. + +lua_isthread *lua_isthread()* +> + int lua_isthread (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a thread, and + 0 otherwise. + +lua_isuserdata *lua_isuserdata()* +> + int lua_isuserdata (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a userdata + (either full or light), and 0 otherwise. + +lua_lessthan *lua_lessthan()* +> + int lua_lessthan (lua_State *L, int index1, int index2); +< + Returns 1 if the value at acceptable index `index1` is smaller than + the value at acceptable index `index2`, following the semantics of the + Lua `<` operator (that is, may call metamethods). Otherwise returns 0. + Also returns 0 if any of the indices is non valid. + +lua_load *lua_load()* +> + int lua_load (lua_State *L, + lua_Reader reader, + void *data, + const char *chunkname); +< + Loads a Lua chunk. If there are no errors, `lua_load` pushes the + compiled chunk as a Lua function on top of the stack. Otherwise, it + pushes an error message. The return values of `lua_load` are: + + - `0`: no errors; + - `LUA_ERRSYNTAX` : syntax error during pre-compilation; + - `LUA_ERRMEM` : memory allocation error. + + This function only loads a chunk; it does not run it. + + `lua_load` automatically detects whether the chunk is text or binary, + and loads it accordingly (see program `luac`, |luaref-luac|). + + The `lua_load` function uses a user-supplied `reader` function to read + the chunk (see |luaref-lua_Reader|). The `data` argument is an opaque + value passed to the reader function. + + The `chunkname` argument gives a name to the chunk, which is used for + error messages and in debug information (see |luaref-apiDebug|). + +lua_newstate *lua_newstate()* +> + lua_State *lua_newstate (lua_Alloc f, void *ud); +< + Creates a new, independent state. Returns `NULL` if cannot create the + state (due to lack of memory). The argument `f` is the allocator + function; Lua does all memory allocation for this state through this + function. The second argument, `ud`, is an opaque pointer that Lua + simply passes to the allocator in every call. + +lua_newtable *lua_newtable()* +> + void lua_newtable (lua_State *L); +< + Creates a new empty table and pushes it onto the stack. It is + equivalent to `lua_createtable(L, 0, 0)` (see + |luaref-lua_createtable|). + +lua_newthread *lua_newthread()* +> + lua_State *lua_newthread (lua_State *L); +< + Creates a new thread, pushes it on the stack, and returns a pointer to + a `lua_State` (see |luaref-lua_State|) that represents this new + thread. The new state returned by this function shares with the + original state all global objects (such as tables), but has an + independent execution stack. + + There is no explicit function to close or to destroy a thread. Threads + are subject to garbage collection, like any Lua object. + +lua_newuserdata *lua_newuserdata()* +> + void *lua_newuserdata (lua_State *L, size_t size); +< + This function allocates a new block of memory with the given size, + pushes onto the stack a new full userdata with the block address, and + returns this address. + *luaref-userdata* + Userdata represents C values in Lua. A full userdata represents a + block of memory. It is an object (like a table): you must create it, + it can have its own metatable, and you can detect when it is being + collected. A full userdata is only equal to itself (under raw + equality). + + When Lua collects a full userdata with a `gc` metamethod, Lua calls + the metamethod and marks the userdata as finalized. When this userdata + is collected again then Lua frees its corresponding memory. + +lua_next *lua_next()* +> + int lua_next (lua_State *L, int index); +< + Pops a key from the stack, and pushes a key-value pair from the table + at the given index (the "next" pair after the given key). If there are + no more elements in the table, then `lua_next` returns 0 (and pushes + nothing). + + *luaref-tabletraversal* + A typical traversal looks like this: +> + /* table is in the stack at index 't' */ + lua_pushnil(L); /* first key */ + while (lua_next(L, t) != 0) { + /* uses 'key' (at index -2) and 'value' (at index -1) */ + printf("%s - %s\n", + lua_typename(L, lua_type(L, -2)), + lua_typename(L, lua_type(L, -1))); + /* removes 'value'; keeps 'key' for next iteration */ + lua_pop(L, 1); + } +< + While traversing a table, do not call `lua_tolstring` (see + |luaref-lua_tolstring|) directly on a key, unless you know that the + key is actually a string. Recall that `lua_tolstring` `changes` the + value at the given index; this confuses the next call to `lua_next`. + +lua_Number *lua_Number()* +> + typedef double lua_Number; +< + The type of numbers in Lua. By default, it is double, but that can be + changed in `luaconf.h`. + + Through the configuration file you can change Lua to operate with + another type for numbers (e.g., float or long). + +lua_objlen *lua_objlen()* +> + size_t lua_objlen (lua_State *L, int index); +< + Returns the "length" of the value at the given acceptable index: for + strings, this is the string length; for tables, this is the result of + the length operator (`#`); for userdata, this is the size of the + block of memory allocated for the userdata; for other values, it is 0. + +lua_pcall *lua_pcall()* +> + lua_pcall (lua_State *L, int nargs, int nresults, int errfunc); +< + Calls a function in protected mode. + + Both `nargs` and `nresults` have the same meaning as in `lua_call` + (see |luaref-lua_call|). If there are no errors during the call, + `lua_pcall` behaves exactly like `lua_call`. However, if there is any + error, `lua_pcall` catches it, pushes a single value on the stack (the + error message), and returns an error code. Like `lua_call`, + `lua_pcall` always removes the function and its arguments from the + stack. + + If `errfunc` is 0, then the error message returned on the stack is + exactly the original error message. Otherwise, `errfunc` is the stack + index of an `error` `handler function`. (In the current + implementation, this index cannot be a pseudo-index.) In case of + runtime errors, this function will be called with the error message + and its return value will be the message returned on the stack by + `lua_pcall`. + + Typically, the error handler function is used to add more debug + information to the error message, such as a stack traceback. Such + information cannot be gathered after the return of `lua_pcall`, since + by then the stack has unwound. + + The `lua_pcall` function returns 0 in case of success or one of the + following error codes (defined in `lua.h`): + + - `LUA_ERRRUN` a runtime error. + - `LUA_ERRMEM` memory allocation error. For such errors, Lua does + not call the error handler function. + - `LUA_ERRERR` error while running the error handler function. + +lua_pop *lua_pop()* +> + void lua_pop (lua_State *L, int n); +< + Pops `n` elements from the stack. + +lua_pushboolean *lua_pushboolean()* +> + void lua_pushboolean (lua_State *L, int b); +< + Pushes a boolean value with value `b` onto the stack. + +lua_pushcclosure *lua_pushcclosure()* +> + void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); +< + Pushes a new C closure onto the stack. + + When a C function is created, it is possible to associate some values + with it, thus creating a C closure (see |luaref-apiCClosures|); these + values are then accessible to the function whenever it is called. To + associate values with a C function, first these values should be + pushed onto the stack (when there are multiple values, the first value + is pushed first). Then `lua_pushcclosure` is called to create and push + the C function onto the stack, with the argument `n` telling how many + values should be associated with the function. `lua_pushcclosure` also + pops these values from the stack. + +lua_pushcfunction *lua_pushcfunction()* +> + void lua_pushcfunction (lua_State *L, lua_CFunction f); +< + Pushes a C function onto the stack. This function receives a pointer + to a C function and pushes onto the stack a Lua value of type + `function` that, when called, invokes the corresponding C function. + + Any function to be registered in Lua must follow the correct protocol + to receive its parameters and return its results (see + |luaref-lua_CFunction|). + + `lua_pushcfunction` is defined as a macro: +> + #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0) +< + +lua_pushfstring *lua_pushfstring()* +> + const char *lua_pushfstring (lua_State *L, const char *fmt, ...); +< + Pushes onto the stack a formatted string and returns a pointer to this + string. It is similar to the C function `sprintf`, but has some + important differences: + + - You do not have to allocate space for the result: the result is a + Lua string and Lua takes care of memory allocation (and + deallocation, through garbage collection). + - The conversion specifiers are quite restricted. There are no flags, + widths, or precisions. The conversion specifiers can only be `%%` + (inserts a `%` in the string), `%s` (inserts a zero-terminated + string, with no size restrictions), `%f` (inserts a + `lua_Number`), `%p` (inserts a pointer as a hexadecimal numeral), + `%d` (inserts an `int`), and `%c` (inserts an `int` as a + character). + +lua_pushinteger *lua_pushinteger()* +> + void lua_pushinteger (lua_State *L, lua_Integer n); +< + Pushes a number with value `n` onto the stack. + +lua_pushlightuserdata *lua_pushlightuserdata()* +> + void lua_pushlightuserdata (lua_State *L, void *p); +< + Pushes a light userdata onto the stack. + *luaref-lightuserdata* + Userdata represents C values in Lua. A light userdata represents a + pointer. It is a value (like a number): you do not create it, it has + no individual metatable, and it is not collected (as it was never + created). A light userdata is equal to "any" light userdata with the + same C address. + +lua_pushlstring *lua_pushlstring()* +> + void lua_pushlstring (lua_State *L, const char *s, size_t len); +< + Pushes the string pointed to by `s` with size `len` onto the stack. + Lua makes (or reuses) an internal copy of the given string, so the + memory at `s` can be freed or reused immediately after the function + returns. The string can contain embedded zeros. + +lua_pushnil *lua_pushnil()* +> + void lua_pushnil (lua_State *L); +< + Pushes a nil value onto the stack. + +lua_pushnumber *lua_pushnumber()* +> + void lua_pushnumber (lua_State *L, lua_Number n); +< + Pushes a number with value `n` onto the stack. + +lua_pushstring *lua_pushstring()* +> + void lua_pushstring (lua_State *L, const char *s); +< + Pushes the zero-terminated string pointed to by `s` onto the stack. + Lua makes (or reuses) an internal copy of the given string, so the + memory at `s` can be freed or reused immediately after the function + returns. The string cannot contain embedded zeros; it is assumed to + end at the first zero. + +lua_pushthread *lua_pushthread()* +> + int lua_pushthread (lua_State *L); +< + Pushes the thread represented by `L` onto the stack. Returns 1 if this + thread is the main thread of its state. + +lua_pushvalue *lua_pushvalue()* +> + void lua_pushvalue (lua_State *L, int index); +< + Pushes a copy of the element at the given valid index onto the stack. + +lua_pushvfstring *lua_pushvfstring()* +> + const char *lua_pushvfstring (lua_State *L, + const char *fmt, + va_list argp); +< + Equivalent to `lua_pushfstring` (see |luaref-pushfstring|), except + that it receives a `va_list` instead of a variable number of + arguments. + +lua_rawequal *lua_rawequal()* +> + int lua_rawequal (lua_State *L, int index1, int index2); +< + Returns 1 if the two values in acceptable indices `index1` and + `index2` are primitively equal (that is, without calling metamethods). + Otherwise returns 0. Also returns 0 if any of the indices are non + valid. + +lua_rawget *lua_rawget()* +> + void lua_rawget (lua_State *L, int index); +< + Similar to `lua_gettable` (see |luaref-lua_gettable|), but does a raw + access (i.e., without metamethods). + +lua_rawgeti *lua_rawgeti()* +> + void lua_rawgeti (lua_State *L, int index, int n); +< + Pushes onto the stack the value `t[n]`, where `t` is the value at the + given valid index `index`. The access is raw; that is, it does not + invoke metamethods. + +lua_rawset *lua_rawset()* +> + void lua_rawset (lua_State *L, int index); +< + Similar to `lua_settable` (see |luaref-lua_settable|), but does a raw + assignment (i.e., without metamethods). + +lua_rawseti *lua_rawseti()* +> + void lua_rawseti (lua_State *L, int index, int n); +< + Does the equivalent of `t[n] = v`, where `t` is the value at the given + valid index `index` and `v` is the value at the top of the stack. + + This function pops the value from the stack. The assignment is raw; + that is, it does not invoke metamethods. + +lua_Reader *lua_Reader()* +> + typedef const char * (*lua_Reader) (lua_State *L, + void *data, + size_t *size); +< + The reader function used by `lua_load` (see |luaref-lua_load|). Every + time it needs another piece of the chunk, `lua_load` calls the reader, + passing along its `data` parameter. The reader must return a pointer + to a block of memory with a new piece of the chunk and set `size` to + the block size. The block must exist until the reader function is + called again. To signal the end of the chunk, the reader must return + `NULL`. The reader function may return pieces of any size greater than + zero. + +lua_register *lua_register()* +> + void lua_register (lua_State *L, + const char *name, + lua_CFunction f); +< + Sets the C function `f` as the new value of global `name`. It is + defined as a macro: +> + #define lua_register(L,n,f) \ + (lua_pushcfunction(L, f), lua_setglobal(L, n)) +< + +lua_remove *lua_remove()* +> + void lua_remove (lua_State *L, int index); +< + Removes the element at the given valid index, shifting down the + elements above this index to fill the gap. Cannot be called with a + pseudo-index, because a pseudo-index is not an actual stack position. + +lua_replace *lua_replace()* +> + void lua_replace (lua_State *L, int index); +< + Moves the top element into the given position (and pops it), without + shifting any element (therefore replacing the value at the given + position). + +lua_resume *lua_resume()* +> + int lua_resume (lua_State *L, int narg); +< + Starts and resumes a coroutine in a given thread. + + To start a coroutine, you first create a new thread (see + |luaref-lua_newthread|); then you push onto its stack the main + function plus any arguments; then you call `lua_resume` (see + |luaref-lua_resume|) with `narg` being the number of arguments. This + call returns when the coroutine suspends or finishes its execution. + When it returns, the stack contains all values passed to `lua_yield` + (see |luaref-lua_yield|), or all values returned by the body function. + `lua_resume` returns `LUA_YIELD` if the coroutine yields, 0 if the + coroutine finishes its execution without errors, or an error code in + case of errors (see |luaref-lua_pcall|). In case of errors, the stack + is not unwound, so you can use the debug API over it. The error + message is on the top of the stack. To restart a coroutine, you put on + its stack only the values to be passed as results from `lua_yield`, + and then call `lua_resume`. + +lua_setallocf *lua_setallocf()* +> + void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); +< + Changes the allocator function of a given state to `f` with user data + `ud`. + +lua_setfenv *lua_setfenv()* +> + int lua_setfenv (lua_State *L, int index); +< + Pops a table from the stack and sets it as the new environment for the + value at the given index. If the value at the given index is neither a + function nor a thread nor a userdata, `lua_setfenv` returns 0. + Otherwise it returns 1. + +lua_setfield *lua_setfield()* +> + void lua_setfield (lua_State *L, int index, const char *k); +< + Does the equivalent to `t[k] = v`, where `t` is the value at the given + valid index `index` and `v` is the value at the top of the stack. + + This function pops the value from the stack. As in Lua, this function + may trigger a metamethod for the "newindex" event (see + |luaref-langMetatables|). + +lua_setglobal *lua_setglobal()* +> + void lua_setglobal (lua_State *L, const char *name); +< + Pops a value from the stack and sets it as the new value of global + `name`. It is defined as a macro: +> + #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s) +< + +lua_setmetatable *lua_setmetatable()* +> + int lua_setmetatable (lua_State *L, int index); +< + Pops a table from the stack and sets it as the new metatable for the + value at the given acceptable index. + +lua_settable *lua_settable()* +> + void lua_settable (lua_State *L, int index); +< + Does the equivalent to `t[k] = v`, where `t` is the value at the given + valid index `index`, `v` is the value at the top of the stack, and `k` + is the value just below the top. + + This function pops both the key and the value from the stack. As in + Lua, this function may trigger a metamethod for the "newindex" event + (see |luaref-langMetatables|). + +lua_settop *lua_settop()* +> + void lua_settop (lua_State *L, int index); +< + Accepts any acceptable index, or 0, and sets the stack top to this + index. If the new top is larger than the old one, then the new + elements are filled with `nil`. If `index` is 0, then all stack + elements are removed. + +lua_State *lua_State()* +> + typedef struct lua_State lua_State; +< + Opaque structure that keeps the whole state of a Lua interpreter. The + Lua library is fully reentrant: it has no global variables. All + information about a state is kept in this structure. + + A pointer to this state must be passed as the first argument to every + function in the library, except to `lua_newstate` (see + |luaref-lua_newstate|), which creates a Lua state from scratch. + +lua_status *lua_status()* +> + int lua_status (lua_State *L); +< + Returns the status of the thread `L`. + + The status can be 0 for a normal thread, an error code if the thread + finished its execution with an error, or `LUA_YIELD` if the thread is + suspended. + +lua_toboolean *lua_toboolean()* +> + int lua_toboolean (lua_State *L, int index); +< + Converts the Lua value at the given acceptable index to a C boolean + value (0 or 1). Like all tests in Lua, `lua_toboolean` returns 1 for + any Lua value different from `false` and `nil`; otherwise it returns + 0. It also returns 0 when called with a non-valid index. (If you want + to accept only actual boolean values, use `lua_isboolean` + |luaref-lua_isboolean| to test the value's type.) + +lua_tocfunction *lua_tocfunction()* +> + lua_CFunction lua_tocfunction (lua_State *L, int index); +< + Converts a value at the given acceptable index to a C function. That + value must be a C function; otherwise it returns `NULL`. + +lua_tointeger *lua_tointeger()* +> + lua_Integer lua_tointeger (lua_State *L, int idx); +< + Converts the Lua value at the given acceptable index to the signed + integral type `lua_Integer` (see |luaref-lua_Integer|). The Lua value + must be a number or a string convertible to a number (see + |luaref-langCoercion|); otherwise, `lua_tointeger` returns 0. + + If the number is not an integer, it is truncated in some non-specified + way. + +lua_tolstring *lua_tolstring()* +> + const char *lua_tolstring (lua_State *L, int index, size_t *len); +< + Converts the Lua value at the given acceptable index to a C string. If + `len` is not `NULL`, it also sets `*len` with the string length. The + Lua value must be a string or a number; otherwise, the function + returns `NULL`. If the value is a number, then `lua_tolstring` also + `changes the actual value in the stack to a` `string`. (This change + confuses `lua_next` |luaref-lua_next| when `lua_tolstring` is applied + to keys during a table traversal.) + + `lua_tolstring` returns a fully aligned pointer to a string inside the + Lua state. This string always has a zero (`\0`) after its last + character (as in C), but may contain other zeros in its body. Because + Lua has garbage collection, there is no guarantee that the pointer + returned by `lua_tolstring` will be valid after the corresponding + value is removed from the stack. + +lua_tonumber *lua_tonumber()* +> + lua_Number lua_tonumber (lua_State *L, int index); +< + Converts the Lua value at the given acceptable index to the C type + `lua_Number` (see |luaref-lua_Number|). The Lua value must be a number + or a string convertible to a number (see |luaref-langCoercion|); + otherwise, `lua_tonumber` returns 0. + +lua_topointer *lua_topointer()* +> + const void *lua_topointer (lua_State *L, int index); +< + Converts the value at the given acceptable index to a generic C + pointer (`void*`). The value may be a userdata, a table, a thread, or + a function; otherwise, `lua_topointer` returns `NULL`. Different + objects will give different pointers. There is no way to convert the + pointer back to its original value. + + Typically this function is used only for debug information. + +lua_tostring *lua_tostring()* +> + const char *lua_tostring (lua_State *L, int index); +< + Equivalent to `lua_tolstring` (see |luaref-lua_tolstring|) with `len` + equal to `NULL`. + +lua_tothread *lua_tothread()* +> + lua_State *lua_tothread (lua_State *L, int index); +< + Converts the value at the given acceptable index to a Lua thread + (represented as `lua_State*` |luaref-lua_State|). This value must be a + thread; otherwise, the function returns `NULL`. + +lua_touserdata *lua_touserdata()* +> + void *lua_touserdata (lua_State *L, int index); +< + If the value at the given acceptable index is a full userdata, returns + its block address. If the value is a light userdata, returns its + pointer. Otherwise, it returns `NULL`. + +lua_type *lua_type()* +> + int lua_type (lua_State *L, int index); +< + Returns the type of the value in the given acceptable index, or + `LUA_TNONE` for a non-valid index (that is, an index to an "empty" + stack position). The types returned by `lua_type` are coded by the + following constants defined in `lua.h` : `LUA_TNIL`, `LUA_TNUMBER`, + `LUA_TBOOLEAN`, `LUA_TSTRING`, `LUA_TTABLE`, `LUA_TFUNCTION`, + `LUA_TUSERDATA`, `LUA_TTHREAD`, and `LUA_TLIGHTUSERDATA`. + +lua_typename *lua_typename()* +> + const char *lua_typename (lua_State *L, int tp); +< + Returns the name of the type encoded by the value `tp`, which must be + one the values returned by `lua_type`. + +lua_Writer *lua_Writer()* +> + typedef int (*lua_Writer) (lua_State *L, + const void* p, + size_t sz, + void* ud); +< + The writer function used by `lua_dump` (see |luaref-lua_dump|). Every + time it produces another piece of chunk, `lua_dump` calls the writer, + passing along the buffer to be written (`p`), its size (`sz`), and the + `data` parameter supplied to `lua_dump`. + + The writer returns an error code: 0 means no errors; any other value + means an error and stops `lua_dump` from calling the writer again. + +lua_xmove *lua_xmove()* +> + void lua_xmove (lua_State *from, lua_State *to, int n); +< + Exchange values between different threads of the `same` global state. + + This function pops `n` values from the stack `from`, and pushes them + onto the stack `to`. + +lua_yield *lua_yield()* +> + int lua_yield (lua_State *L, int nresults); +< + Yields a coroutine. + + This function should only be called as the return expression of a C + function, as follows: +> + return lua_yield (L, nresults); +< + When a C function calls `lua_yield` in that way, the running coroutine + suspends its execution, and the call to `lua_resume` (see + |luaref-lua_resume|) that started this coroutine returns. The + parameter `nresults` is the number of values from the stack that are + passed as results to `lua_resume`. + + *luaref-stackexample* + As an example of stack manipulation, if the stack starts as + `10 20 30 40 50*` (from bottom to top; the `*` marks the top), then +> + lua_pushvalue(L, 3) --> 10 20 30 40 50 30* + lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30* + lua_remove(L, -3) --> 10 20 30 40 30 30* + lua_remove(L, 6) --> 10 20 30 40 30* + lua_insert(L, 1) --> 30 10 20 30 40* + lua_insert(L, -1) --> 30 10 20 30 40* (no effect) + lua_replace(L, 2) --> 30 40 20 30* + lua_settop(L, -3) --> 30 40* + lua_settop(L, 6) --> 30 40 nil nil nil nil* +< + +============================================================================== +3.8 The Debug Interface *luaref-apiDebug* + +Lua has no built-in debugging facilities. Instead, it offers a special +interface by means of functions and hooks. This interface allows the +construction of different kinds of debuggers, profilers, and other tools that +need "inside information" from the interpreter. + +lua_Debug *lua_Debug()* + + `typedef struct lua_Debug {` + `int event;` + `const char *name; /* (n) */` + `const char *namewhat; /* (n) */` + `const char *what; /* (S) */` + `const char *source; /* (S) */` + `int currentline; /* (l) */` + `int nups; /* (u) number of upvalues */` + `int linedefined; /* (S) */` + `int lastlinedefined; /* (S) */` + `char short_src[LUA_IDSIZE]; /* (S) */` + `/* private part */` + `other fields` + `} lua_Debug;` + +A structure used to carry different pieces of information about an active +function. `lua_getstack` (see |luaref-lua_getstack|) fills only the private part +of this structure, for later use. To fill the other fields of `lua_Debug` with +useful information, call `lua_getinfo` (see |luaref-lua_getinfo|). + +The fields of `lua_Debug` have the following meaning: + + `source` If the function was defined in a string, then `source` is + that string. If the function was defined in a file, then + `source` starts with a `@` followed by the file name. + `short_src` a "printable" version of `source`, to be used in error messages. + `linedefined` the line number where the definition of the function starts. + `lastlinedefined` the line number where the definition of the function ends. + `what` the string `"Lua"` if the function is a Lua function, + `"C"` if it is a C function, `"main"` if it is the main + part of a chunk, and `"tail"` if it was a function that + did a tail call. In the latter case, Lua has no other + information about the function. + `currentline` the current line where the given function is executing. + When no line information is available, `currentline` is + set to -1. + `name` a reasonable name for the given function. Because + functions in Lua are first-class values, they do not have + a fixed name: some functions may be the value of multiple + global variables, while others may be stored only in a + table field. The `lua_getinfo` function checks how the + function was called to find a suitable name. If it cannot + find a name, then `name` is set to `NULL`. + `namewhat` explains the `name` field. The value of `namewhat` can be + `"global"`, `"local"`, `"method"`, `"field"`, + `"upvalue"`, or `""` (the empty string), according to how + the function was called. (Lua uses the empty string when + no other option seems to apply.) `nups` the number of + upvalues of the function. + +lua_gethook *lua_gethook()* +> + lua_Hook lua_gethook (lua_State *L); +< + Returns the current hook function. + +lua_gethookcount *lua_gethookcount()* +> + int lua_gethookcount (lua_State *L); +< + Returns the current hook count. + +lua_gethookmask *lua_gethookmask()* +> + int lua_gethookmask (lua_State *L); +< + Returns the current hook mask. + +lua_getinfo *lua_getinfo()* +> + int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); +< + Returns information about a specific function or function invocation. + + To get information about a function invocation, the parameter `ar` + must be a valid activation record that was filled by a previous call + to `lua_getstack` (see |luaref-lua_getstack|) or given as argument to + a hook (see |luaref-lua_Hook|). + + To get information about a function you push it onto the stack and + start the `what` string with the character `>`. (In that case, + `lua_getinfo` pops the function in the top of the stack.) For + instance, to know in which line a function `f` was defined, you can + write the following code: +> + lua_Debug ar; + lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */ + lua_getinfo(L, ">S", &ar); + printf("%d\n", ar.linedefined); +< + Each character in the string `what` selects some fields of the + structure `ar` to be filled or a value to be pushed on the stack: + + `'n'` fills in the field `name` and `namewhat` + `'S'` fills in the fields `source`, `short_src`, `linedefined`, + `lastlinedefined`, and `what` + `'l'` fills in the field `currentline` + `'u'` fills in the field `nups` + `'f'` pushes onto the stack the function that is running at the + given level + `'L'` pushes onto the stack a table whose indices are the numbers + of the lines that are valid on the function. (A `valid line` is a + line with some associated code, that is, a line where you can put + a break point. Non-valid lines include empty lines and comments.) + + This function returns 0 on error (for instance, an invalid option in + `what`). + +lua_getlocal *lua_getlocal()* +> + const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n); +< + Gets information about a local variable of a given activation record. + The parameter `ar` must be a valid activation record that was filled + by a previous call to `lua_getstack` (see |luaref-lua_getstack|) or + given as argument to a hook (see |luaref-lua_Hook|). The index `n` + selects which local variable to inspect (1 is the first parameter or + active local variable, and so on, until the last active local + variable). `lua_getlocal` pushes the variable's value onto the stack + and returns its name. + + Variable names starting with `(` (open parentheses) represent + internal variables (loop control variables, temporaries, and C + function locals). + + Returns `NULL` (and pushes nothing) when the index is greater than the + number of active local variables. + +lua_getstack *lua_getstack()* +> + int lua_getstack (lua_State *L, int level, lua_Debug *ar); +< + Gets information about the interpreter runtime stack. + + This function fills parts of a `lua_Debug` (see |luaref-lua_Debug|) + structure with an identification of the `activation record` of the + function executing at a given level. Level 0 is the current running + function, whereas level `n+1` is the function that has called level + `n`. When there are no errors, `lua_getstack` returns 1; when called + with a level greater than the stack depth, it returns 0. + +lua_getupvalue *lua_getupvalue()* +> + const char *lua_getupvalue (lua_State *L, int funcindex, int n); +< + Gets information about a closure's upvalue. (For Lua functions, + upvalues are the external local variables that the function uses, and + that are consequently included in its closure.) `lua_getupvalue` gets + the index `n` of an upvalue, pushes the upvalue's value onto the + stack, and returns its name. `funcindex` points to the closure in the + stack. (Upvalues have no particular order, as they are active through + the whole function. So, they are numbered in an arbitrary order.) + + Returns `NULL` (and pushes nothing) when the index is greater than the + number of upvalues. For C functions, this function uses the empty + string `""` as a name for all upvalues. + +lua_Hook *lua_Hook()* +> + typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); +< + Type for debugging hook functions. + + Whenever a hook is called, its `ar` argument has its field `event` set + to the specific event that triggered the hook. Lua identifies these + events with the following constants: `LUA_HOOKCALL`, `LUA_HOOKRET`, + `LUA_HOOKTAILRET`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for + line events, the field `currentline` is also set. To get the value of + any other field in `ar`, the hook must call `lua_getinfo` (see + |luaref-lua_getinfo|). For return events, `event` may be + `LUA_HOOKRET`, the normal value, or `LUA_HOOKTAILRET`. In the latter + case, Lua is simulating a return from a function that did a tail call; + in this case, it is useless to call `lua_getinfo`. + + While Lua is running a hook, it disables other calls to hooks. + Therefore, if a hook calls back Lua to execute a function or a chunk, + this execution occurs without any calls to hooks. + + +lua_sethook *lua_sethook()* +> + int lua_sethook (lua_State *L, lua_Hook f, int mask, int count); +< + Sets the debugging hook function. + + Argument `f` is the hook function. `mask` specifies on which events + the hook will be called: it is formed by a bitwise `or` of the + constants `LUA_MASKCALL`, `LUA_MASKRET`, `LUA_MASKLINE`, and + `LUA_MASKCOUNT`. The `count` argument is only meaningful when the mask + includes `LUA_MASKCOUNT`. For each event, the hook is called as + explained below: + + - `The call hook`: is called when the interpreter calls a function. + The hook is called just after Lua enters the new function, before + the function gets its arguments. + - `The return hook`: is called when the interpreter returns from a + function. The hook is called just before Lua leaves the function. + You have no access to the values to be returned by the function. + - `The line hook`: is called when the interpreter is about to start + the execution of a new line of code, or when it jumps back in the + code (even to the same line). (This event only happens while Lua is + executing a Lua function.) + - `The count hook`: is called after the interpreter executes every + `count` instructions. (This event only happens while Lua is + executing a Lua function.) + + A hook is disabled by setting `mask` to zero. + +lua_setlocal *lua_setlocal()* +> + const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n); +< + Sets the value of a local variable of a given activation record. + Parameters `ar` and `n` are as in `lua_getlocal` (see + |luaref-lua_getlocal|). `lua_setlocal` assigns the value at the top of + the stack to the variable and returns its name. It also pops the value + from the stack. + + Returns `NULL` (and pops nothing) when the index is greater than the + number of active local variables. + +lua_setupvalue *lua_setupvalue()* +> + const char *lua_setupvalue (lua_State *L, int funcindex, int n); +< + Sets the value of a closure's upvalue. It assigns the value at the top + of the stack to the upvalue and returns its name. It also pops the + value from the stack. Parameters `funcindex` and `n` are as in the + `lua_getupvalue` (see |luaref-lua_getupvalue|). + + Returns `NULL` (and pops nothing) when the index is greater than the + number of upvalues. + + *luaref-debugexample* + As an example, the following function lists the names of all local + variables and upvalues for a function at a given level of the stack: +> + int listvars (lua_State *L, int level) { + lua_Debug ar; + int i; + const char *name; + if (lua_getstack(L, level, &ar) == 0) + return 0; /* failure: no such level in the stack */ + i = 1; + while ((name = lua_getlocal(L, &ar, i++)) != NULL) { + printf("local %d %s\n", i-1, name); + lua_pop(L, 1); /* remove variable value */ + } + lua_getinfo(L, "f", &ar); /* retrieves function */ + i = 1; + while ((name = lua_getupvalue(L, -1, i++)) != NULL) { + printf("upvalue %d %s\n", i-1, name); + lua_pop(L, 1); /* remove upvalue value */ + } + return 1; + } +< + +============================================================================== +4 THE AUXILIARY LIBRARY *luaref-aux* +============================================================================== + +The auxiliary library provides several convenient functions to interface C +with Lua. While the basic API provides the primitive functions for all +interactions between C and Lua, the auxiliary library provides higher-level +functions for some common tasks. + +All functions from the auxiliary library are defined in header file `lauxlib.h` +and have a prefix `luaL_`. + +All functions in the auxiliary library are built on top of the basic API, and +so they provide nothing that cannot be done with this API. + +Several functions in the auxiliary library are used to check C function +arguments. Their names are always `luaL_check*` or `luaL_opt*`. All of these +functions raise an error if the check is not satisfied. Because the error +message is formatted for arguments (e.g., "bad argument #1"), you should not +use these functions for other stack values. + +============================================================================== +4.1 Functions and Types *luaref-auxFunctions* + +Here we list all functions and types from the auxiliary library in +alphabetical order. + +luaL_addchar *luaL_addchar()* +> + void luaL_addchar (luaL_Buffer *B, char c); +< + Adds the character `c` to the buffer `B` (see |luaref-luaL_Buffer|). + +luaL_addlstring *luaL_addlstring()* +> + void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); +< + Adds the string pointed to by `s` with length `l` to the buffer `B` + (see |luaref-luaL_Buffer|). The string may contain embedded zeros. + +luaL_addsize *luaL_addsize()* +> + void luaL_addsize (luaL_Buffer *B, size_t n); +< + Adds to the buffer `B` (see |luaref-luaL_Buffer|) a string of length + `n` previously copied to the buffer area (see + |luaref-luaL_prepbuffer|). + +luaL_addstring *luaL_addstring()* +> + void luaL_addstring (luaL_Buffer *B, const char *s); +< + Adds the zero-terminated string pointed to by `s` to the buffer `B` + (see |luaref-luaL_Buffer|). The string may not contain embedded zeros. + +luaL_addvalue *luaL_addvalue()* +> + void luaL_addvalue (luaL_Buffer *B); +< + Adds the value at the top of the stack to the buffer `B` (see + |luaref-luaL_Buffer|). Pops the value. + + This is the only function on string buffers that can (and must) be + called with an extra element on the stack, which is the value to be + added to the buffer. + +luaL_argcheck *luaL_argcheck()* +> + void luaL_argcheck (lua_State *L, + int cond, + int narg, + const char *extramsg); +< + Checks whether `cond` is true. If not, raises an error with the + following message, where `func` is retrieved from the call stack: +> + bad argument # to () +< + +luaL_argerror *luaL_argerror()* +> + int luaL_argerror (lua_State *L, int narg, const char *extramsg); +< + Raises an error with the following message, where `func` is retrieved + from the call stack: +> + bad argument # to () +< + This function never returns, but it is an idiom to use it in C + functions as `return luaL_argerror(` `args` `)`. + +luaL_Buffer *luaL_Buffer()* +> + typedef struct luaL_Buffer luaL_Buffer; +< + Type for a `string buffer`. + + A string buffer allows C code to build Lua strings piecemeal. Its + pattern of use is as follows: + + - First you declare a variable `b` of type `luaL_Buffer`. + - Then you initialize it with a call `luaL_buffinit(L, &b)` (see + |luaref-luaL_buffinit|). + - Then you add string pieces to the buffer calling any of the + `luaL_add*` functions. + - You finish by calling `luaL_pushresult(&b)` (see + |luaref-luaL_pushresult|). This call leaves the final string on the + top of the stack. + + During its normal operation, a string buffer uses a variable number of + stack slots. So, while using a buffer, you cannot assume that you know + where the top of the stack is. You can use the stack between + successive calls to buffer operations as long as that use is balanced; + that is, when you call a buffer operation, the stack is at the same + level it was immediately after the previous buffer operation. (The + only exception to this rule is `luaL_addvalue` + |luaref-luaL_addvalue|.) After calling `luaL_pushresult` the stack is + back to its level when the buffer was initialized, plus the final + string on its top. + +luaL_buffinit *luaL_buffinit()* +> + void luaL_buffinit (lua_State *L, luaL_Buffer *B); +< + Initializes a buffer `B`. This function does not allocate any space; + the buffer must be declared as a variable (see |luaref-luaL_Buffer|). + +luaL_callmeta *luaL_callmeta()* +> + int luaL_callmeta (lua_State *L, int obj, const char *e); +< + Calls a metamethod. + + If the object at index `obj` has a metatable and this metatable has a + field `e`, this function calls this field and passes the object as its + only argument. In this case this function returns 1 and pushes onto + the stack the value returned by the call. If there is no metatable or + no metamethod, this function returns + 0 (without pushing any value on the stack). + +luaL_checkany *luaL_checkany()* +> + void luaL_checkany (lua_State *L, int narg); +< + Checks whether the function has an argument of any type (including + `nil`) at position `narg`. + +luaL_checkint *luaL_checkint()* +> + int luaL_checkint (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a number and returns + this number cast to an `int`. + +luaL_checkinteger *luaL_checkinteger()* +> + lua_Integer luaL_checkinteger (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a number and returns + this number cast to a `lua_Integer` (see |luaref-lua_Integer|). + +luaL_checklong *luaL_checklong()* +> + long luaL_checklong (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a number and returns + this number cast to a `long`. + +luaL_checklstring *luaL_checklstring()* +> + const char *luaL_checklstring (lua_State *L, int narg, size_t *l); +< + Checks whether the function argument `narg` is a string and returns + this string; if `l` is not `NULL` fills `*l` with the string's length. + +luaL_checknumber *luaL_checknumber()* +> + lua_Number luaL_checknumber (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a number and returns + this number (see |luaref-lua_Number|). + +luaL_checkoption *luaL_checkoption()* +> + int luaL_checkoption (lua_State *L, + int narg, + const char *def, + const char *const lst[]); +< + Checks whether the function argument `narg` is a string and searches + for this string in the array `lst` (which must be NULL-terminated). + Returns the index in the array where the string was found. Raises an + error if the argument is not a string or if the string cannot be + found. + + If `def` is not `NULL`, the function uses `def` as a default value + when there is no argument `narg` or if this argument is `nil`. + + This is a useful function for mapping strings to C enums. (The usual + convention in Lua libraries is to use strings instead of numbers to + select options.) + +luaL_checkstack *luaL_checkstack()* +> + void luaL_checkstack (lua_State *L, int sz, const char *msg); +< + Grows the stack size to `top + sz` elements, raising an error if the + stack cannot grow to that size. `msg` is an additional text to go into + the error message. + +luaL_checkstring *luaL_checkstring()* +> + const char *luaL_checkstring (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a string and returns + this string. + +luaL_checktype *luaL_checktype()* +> + void luaL_checktype (lua_State *L, int narg, int t); +< + Checks whether the function argument `narg` has type `t` (see + |luaref-lua_type|). + +luaL_checkudata *luaL_checkudata()* +> + void *luaL_checkudata (lua_State *L, int narg, const char *tname); +< + Checks whether the function argument `narg` is a userdata of the type + `tname` (see |luaref-luaL_newmetatable|). + +luaL_dofile *luaL_dofile()* +> + int luaL_dofile (lua_State *L, const char *filename); +< + Loads and runs the given file. It is defined as the following macro: +> + (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) +< + It returns 0 if there are no errors or 1 in case of errors. + +luaL_dostring *luaL_dostring()* +> + int luaL_dostring (lua_State *L, const char *str); +< + Loads and runs the given string. It is defined as the following macro: +> + (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) +< + It returns 0 if there are no errors or 1 in case of errors. + +luaL_error *luaL_error()* +> + int luaL_error (lua_State *L, const char *fmt, ...); +< + Raises an error. The error message format is given by `fmt` plus any + extra arguments, following the same rules of `lua_pushfstring` (see + |luaref-lua_pushfstring|). It also adds at the beginning of the + message the file name and the line number where the error occurred, if + this information is available. + + This function never returns, but it is an idiom to use it in C + functions as `return luaL_error(` `args` `)`. + +luaL_getmetafield *luaL_getmetafield()* +> + int luaL_getmetafield (lua_State *L, int obj, const char *e); +< + Pushes onto the stack the field `e` from the metatable of the object + at index `obj`. If the object does not have a metatable, or if the + metatable does not have this field, returns 0 and pushes nothing. + +luaL_getmetatable *luaL_getmetatable()* +> + void luaL_getmetatable (lua_State *L, const char *tname); +< + Pushes onto the stack the metatable associated with name `tname` in + the registry (see |luaref-luaL_newmetatable|). + +luaL_gsub *luaL_gsub()* +> + const char *luaL_gsub (lua_State *L, + const char *s, + const char *p, + const char *r); +< + Creates a copy of string `s` by replacing any occurrence of the string + `p` with the string `r`. Pushes the resulting string on the stack and + returns it. + +luaL_loadbuffer *luaL_loadbuffer()* +> + int luaL_loadbuffer (lua_State *L, + const char *buff, + size_t sz, + const char *name); +< + Loads a buffer as a Lua chunk. This function uses `lua_load` (see + |luaref-lua_load|) to load the chunk in the buffer pointed to by + `buff` with size `sz`. + + This function returns the same results as `lua_load`. `name` is the + chunk name, used for debug information and error messages. + +luaL_loadfile *luaL_loadfile()* +> + int luaL_loadfile (lua_State *L, const char *filename); +< + Loads a file as a Lua chunk. This function uses `lua_load` (see + |luaref-lua_load|) to load the chunk in the file named `filename`. If + `filename` is `NULL`, then it loads from the standard input. The first + line in the file is ignored if it starts with a `#`. + + This function returns the same results as `lua_load`, but it has an + extra error code `LUA_ERRFILE` if it cannot open/read the file. + + As `lua_load`, this function only loads the chunk; it does not run it. + +luaL_loadstring *luaL_loadstring()* +> + int luaL_loadstring (lua_State *L, const char *s); +< + Loads a string as a Lua chunk. This function uses `lua_load` (see + |luaref-lua_load|) to load the chunk in the zero-terminated string + `s`. + + This function returns the same results as `lua_load`. + + Also as `lua_load`, this function only loads the chunk; it does not + run it. + +luaL_newmetatable *luaL_newmetatable()* +> + int luaL_newmetatable (lua_State *L, const char *tname); +< + If the registry already has the key `tname`, returns 0. Otherwise, + creates a new table to be used as a metatable for userdata, adds it to + the registry with key `tname`, and returns 1. + + In both cases pushes onto the stack the final value associated with + `tname` in the registry. + +luaL_newstate *luaL_newstate()* +> + lua_State *luaL_newstate (void); +< + Creates a new Lua state. It calls `lua_newstate` (see + |luaref-lua_newstate|) with an allocator based on the standard C + `realloc` function and then sets a panic function (see + |luaref-lua_atpanic|) that prints an error message to the standard + error output in case of fatal errors. + + Returns the new state, or `NULL` if there is a memory allocation + error. + +luaL_openlibs *luaL_openlibs()* +> + void luaL_openlibs (lua_State *L); +< + Opens all standard Lua libraries into the given state. See also + |luaref-openlibs| for details on how to open individual libraries. + +luaL_optint *luaL_optint()* +> + int luaL_optint (lua_State *L, int narg, int d); +< + If the function argument `narg` is a number, returns this number cast + to an `int`. If this argument is absent or is `nil`, returns `d`. + Otherwise, raises an error. + +luaL_optinteger *luaL_optinteger()* +> + lua_Integer luaL_optinteger (lua_State *L, + int narg, + lua_Integer d); +< + If the function argument `narg` is a number, returns this number cast + to a `lua_Integer` (see |luaref-lua_Integer|). If this argument is + absent or is `nil`, returns `d`. Otherwise, raises an error. + +luaL_optlong *luaL_optlong()* +> + long luaL_optlong (lua_State *L, int narg, long d); +< + If the function argument `narg` is a number, returns this number cast + to a `long`. If this argument is absent or is `nil`, returns `d`. + Otherwise, raises an error. + +luaL_optlstring *luaL_optlstring()* +> + const char *luaL_optlstring (lua_State *L, + int narg, + const char *d, + size_t *l); +< + If the function argument `narg` is a string, returns this string. If + this argument is absent or is `nil`, returns `d`. Otherwise, raises an + error. + + If `l` is not `NULL`, fills the position `*l` with the results' length. + +luaL_optnumber *luaL_optnumber()* +> + lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d); +< + If the function argument `narg` is a number, returns this number. If + this argument is absent or is `nil`, returns `d`. Otherwise, raises an + error. + +luaL_optstring *luaL_optstring()* +> + const char *luaL_optstring (lua_State *L, + int narg, + const char *d); +< + If the function argument `narg` is a string, returns this string. If + this argument is absent or is `nil`, returns `d`. Otherwise, raises an + error. + +luaL_prepbuffer *luaL_prepbuffer()* +> + char *luaL_prepbuffer (luaL_Buffer *B); +< + Returns an address to a space of size `LUAL_BUFFERSIZE` where you can + copy a string to be added to buffer `B` (see |luaref-luaL_Buffer|). + After copying the string into this space you must call `luaL_addsize` + (see |luaref-luaL_addsize|) with the size of the string to actually + add it to the buffer. + +luaL_pushresult *luaL_pushresult()* +> + void luaL_pushresult (luaL_Buffer *B); +< + Finishes the use of buffer `B` leaving the final string on the top of + the stack. + +luaL_ref *luaL_ref()* +> + int luaL_ref (lua_State *L, int t); +< + Creates and returns a `reference`, in the table at index `t`, for the + object at the top of the stack (and pops the object). + + A reference is a unique integer key. As long as you do not manually + add integer keys into table `t`, `luaL_ref` ensures the uniqueness of + the key it returns. You can retrieve an object referred by reference + `r` by calling `lua_rawgeti(L, t, r)` (see |luaref-lua_rawgeti|). + Function `luaL_unref` (see |luaref-luaL_unref|) frees a reference and + its associated object. + + If the object at the top of the stack is `nil`, `luaL_ref` returns the + constant `LUA_REFNIL`. The constant `LUA_NOREF` is guaranteed to be + different from any reference returned by `luaL_ref`. + +luaL_Reg *luaL_Reg()* +> + typedef struct luaL_Reg { + const char *name; + lua_CFunction func; + } luaL_Reg; +< + Type for arrays of functions to be registered by `luaL_register` (see + |luaref-luaL_register|). `name` is the function name and `func` is a + pointer to the function. Any array of `luaL_Reg` must end with a + sentinel entry in which both `name` and `func` are `NULL`. + +luaL_register *luaL_register()* +> + void luaL_register (lua_State *L, + const char *libname, + const luaL_Reg *l); +< + Opens a library. + + When called with `libname` equal to `NULL`, it simply registers all + functions in the list `l` (see |luaref-luaL_Reg|) into the table on + the top of the stack. + + When called with a non-null `libname`, `luaL_register` creates a new + table `t`, sets it as the value of the global variable `libname`, sets + it as the value of `package.loaded[libname]`, and registers on it all + functions in the list `l`. If there is a table in + `package.loaded[libname]` or in variable `libname`, reuses this table + instead of creating a new one. + + In any case the function leaves the table on the top of the stack. + +luaL_typename *luaL_typename()* +> + const char *luaL_typename (lua_State *L, int idx); +< + Returns the name of the type of the value at index `idx`. + +luaL_typerror *luaL_typerror()* +> + int luaL_typerror (lua_State *L, int narg, const char *tname); +< + Generates an error with a message like the following: + + `location` `: bad argument` `narg` `to` `'func'` `(` `tname` + `expected, got` `rt` `)` + + where `location` is produced by `luaL_where` (see + |luaref-luaL_where|), `func` is the name of the current function, and + `rt` is the type name of the actual argument. + +luaL_unref *luaL_unref()* +> + void luaL_unref (lua_State *L, int t, int ref); +< + Releases reference `ref` from the table at index `t` (see + |luaref-luaL_ref|). The entry is removed from the table, so that the + referred object can be collected. The reference `ref` is also freed to + be used again. + + If `ref` is `LUA_NOREF` or `LUA_REFNIL`, `luaL_unref` does nothing. + +luaL_where *luaL_where()* +> + void luaL_where (lua_State *L, int lvl); +< + Pushes onto the stack a string identifying the current position of the + control at level `lvl` in the call stack. Typically this string has + the following format: + + `chunkname:currentline:` + + Level 0 is the running function, level 1 is the function that called + the running function, etc. + + This function is used to build a prefix for error messages. + +============================================================================== +5 STANDARD LIBRARIES *luaref-Lib* +============================================================================== + +The standard libraries provide useful functions that are implemented directly +through the C API. Some of these functions provide essential services to the +language (e.g., `type` and `getmetatable`); others provide access to "outside" +services (e.g., I/O); and others could be implemented in Lua itself, but are +quite useful or have critical performance requirements that deserve an +implementation in C (e.g., `sort`). + +All libraries are implemented through the official C API and are provided as +separate C modules. Currently, Lua has the following standard libraries: + +- basic library; +- package library; +- string manipulation; +- table manipulation; +- mathematical functions (sin, log, etc.); +- input and output; +- operating system facilities; +- debug facilities. + +Except for the basic and package libraries, each library provides all its +functions as fields of a global table or as methods of its objects. + + *luaref-openlibs* +To have access to these libraries, the C host program should call the +`luaL_openlibs` function, which opens all standard libraries (see +|luaref-luaL_openlibs|). Alternatively, the host program can open the libraries +individually by calling `luaopen_base` (for the basic library), +`luaopen_package` (for the package library), `luaopen_string` (for the string +library), `luaopen_table` (for the table library), `luaopen_math` (for the +mathematical library), `luaopen_io` (for the I/O and the Operating System +libraries), and `luaopen_debug` (for the debug library). These functions are +declared in `lualib.h` and should not be called directly: you must call them +like any other Lua C function, e.g., by using `lua_call` (see |luaref-lua_call|). + +============================================================================== +5.1 Basic Functions *luaref-libBasic* + +The basic library provides some core functions to Lua. If you do not include +this library in your application, you should check carefully whether you need +to provide implementations for some of its facilities. + +assert({v} [, {message}]) *luaref-assert()* + Issues an error when the value of its argument `v` is false (i.e., `nil` or + `false`); otherwise, returns all its arguments. `message` is an error message; + when absent, it defaults to "assertion failed!" + +collectgarbage({opt} [, {arg}]) *luaref-collectgarbage()* + This function is a generic interface to the garbage collector. It + performs different functions according to its first argument, {opt}: + + `"stop"` stops the garbage collector. + `"restart"` restarts the garbage collector. + `"collect"` performs a full garbage-collection cycle. + `"count"` returns the total memory in use by Lua (in Kbytes). + `"step"` performs a garbage-collection step. The step "size" is + controlled by {arg} (larger values mean more steps) in a + non-specified way. If you want to control the step size + you must experimentally tune the value of {arg}. Returns + `true` if the step finished a collection cycle. + `"setpause"` sets {arg} /100 as the new value for the `pause` of + the collector (see |luaref-langGC|). + `"setstepmul"` sets {arg} /100 as the new value for the `step + multiplier` of the collector (see |luaref-langGC|). + +dofile({filename}) *luaref-dofile()* + Opens the named file and executes its contents as a Lua chunk. When + called without arguments, `dofile` executes the contents of the + standard input (`stdin`). Returns all values returned by the chunk. In + case of errors, `dofile` propagates the error to its caller (that is, + `dofile` does not run in protected mode). + +error({message} [, {level}]) *luaref-error()* + Terminates the last protected function called and returns `message` as + the error message. Function {error} never returns. + + Usually, {error} adds some information about the error position at the + beginning of the message. The {level} argument specifies how to get + the error position. With level 1 (the default), the error position is + where the {error} function was called. Level 2 points the error to + where the function that called {error} was called; and so on. Passing + a level 0 avoids the addition of error position information to the + message. + +_G *luaref-_G()* + A global variable (not a function) that holds the global environment + (that is, `_G._G = _G`). Lua itself does not use this variable; + changing its value does not affect any environment, nor vice-versa. + (Use `setfenv` to change environments.) + +getfenv({f}) *luaref-getfenv()* + Returns the current environment in use by the function. {f} can be a + Lua function or a number that specifies the function at that stack + level: Level 1 is the function calling `getfenv`. If the given + function is not a Lua function, or if {f} is 0, `getfenv` returns the + global environment. The default for {f} is 1. + +getmetatable({object}) *luaref-getmetatable()* + If {object} does not have a metatable, returns `nil`. Otherwise, if + the object's metatable has a `"__metatable"` field, returns the + associated value. Otherwise, returns the metatable of the given + object. + +ipairs({t}) *luaref-ipairs()* + Returns three values: an iterator function, the table {t}, and 0, so + that the construction + + `for i,v in ipairs(t) do` `body` `end` + + will iterate over the pairs (`1,t[1]`), (`2,t[2]`), ..., up to the + first integer key absent from the table. + +load({func} [, {chunkname}]) *luaref-load()* + Loads a chunk using function {func} to get its pieces. Each call to + {func} must return a string that concatenates with previous results. A + return of `nil` (or no value) signals the end of the chunk. + + If there are no errors, returns the compiled chunk as a function; + otherwise, returns `nil` plus the error message. The environment of + the returned function is the global environment. + + {chunkname} is used as the chunk name for error messages and debug + information. + +loadfile([{filename}]) *luaref-loadfile()* + Similar to `load` (see |luaref-load|), but gets the chunk from file + {filename} or from the standard input, if no file name is given. + +loadstring({string} [, {chunkname}]) *luaref-loadstring()* + Similar to `load` (see |luaref-load|), but gets the chunk from the + given {string}. + + To load and run a given string, use the idiom +> + assert(loadstring(s))() +< + +next({table} [, {index}]) *luaref-next()* + Allows a program to traverse all fields of a table. Its first argument + is a table and its second argument is an index in this table. `next` + returns the next index of the table and its associated value. When + called with `nil` as its second argument, `next` returns an initial + index and its associated value. When called with the last index, or + with `nil` in an empty table, `next` returns `nil`. If the second + argument is absent, then it is interpreted as `nil`. In particular, + you can use `next(t)` to check whether a table is empty. + + The order in which the indices are enumerated is not specified, `even + for` `numeric indices`. (To traverse a table in numeric order, use a + numerical `for` or the `ipairs` |luaref-ipairs| function.) + + The behavior of `next` is `undefined` if, during the traversal, you + assign any value to a non-existent field in the table. You may however + modify existing fields. In particular, you may clear existing fields. + +pairs({t}) *luaref-pairs()* + Returns three values: the `next` |luaref-next| function, the table + {t}, and `nil`, so that the construction + + `for k,v in pairs(t) do` `body` `end` + + will iterate over all key-value pairs of table {t}. + +pcall({f}, {arg1}, {...}) *luaref-pcall()* + Calls function {f} with the given arguments in `protected mode`. This + means that any error inside {f} is not propagated; instead, `pcall` + catches the error and returns a status code. Its first result is the + status code (a boolean), which is `true` if the call succeeds without + errors. In such case, `pcall` also returns all results from the call, + after this first result. In case of any error, `pcall` returns `false` + plus the error message. + +print({...}) *luaref-print()* + Receives any number of arguments, and prints their values to `stdout`, + using the `tostring` |luaref-tostring| function to convert them to + strings. `print` is not intended for formatted output, but only as a + quick way to show a value, typically for debugging. For formatted + output, use `string.format` (see |luaref-string.format|). + +rawequal({v1}, {v2}) *luaref-rawequal()* + Checks whether {v1} is equal to {v2}, without invoking any metamethod. + Returns a boolean. + +rawget({table}, {index}) *luaref-rawget()* + Gets the real value of `table[index]`, without invoking any + metamethod. {table} must be a table; {index} may be any value. + +rawset({table}, {index}, {value}) *luaref-rawset()* + Sets the real value of `table[index]` to {value}, without invoking any + metamethod. {table} must be a table, {index} any value different from + `nil`, and {value} any Lua value. + + This function returns {table}. + +select({index}, {...}) *luaref-select()* + If {index} is a number, returns all arguments after argument number + {index}. Otherwise, {index} must be the string `"#"`, and `select` + returns the total number of extra arguments it received. + +setfenv({f}, {table}) *luaref-setfenv()* + Sets the environment to be used by the given function. {f} can be a + Lua function or a number that specifies the function at that stack + level: Level 1 is the function calling `setfenv`. `setfenv` returns + the given function. + + As a special case, when {f} is 0 `setfenv` changes the environment of + the running thread. In this case, `setfenv` returns no values. + +setmetatable({table}, {metatable}) *luaref-setmetatable()* + Sets the metatable for the given table. (You cannot change the + metatable of other types from Lua, only from C.) If {metatable} is + `nil`, removes the metatable of the given table. If the original + metatable has a `"__metatable"` field, raises an error. + + This function returns {table}. + +tonumber({e} [, {base}]) *luaref-tonumber()* + Tries to convert its argument to a number. If the argument is already + a number or a string convertible to a number, then `tonumber` returns + this number; otherwise, it returns `nil`. + + An optional argument specifies the base to interpret the numeral. The + base may be any integer between 2 and 36, inclusive. In bases above + 10, the letter `A` (in either upper or lower case) represents 10, `B` + represents 11, and so forth, with `Z'` representing 35. In base 10 + (the default), the number may have a decimal part, as well as an + optional exponent part (see |luaref-langLexConv|). In other bases, + only unsigned integers are accepted. + +tostring({e}) *luaref-tostring()* + Receives an argument of any type and converts it to a string in a + reasonable format. For complete control of how numbers are converted, + use `string.format` (see |luaref-string.format|). + + *__tostring* + If the metatable of {e} has a `"__tostring"` field, `tostring` calls + the corresponding value with {e} as argument, and uses the result of + the call as its result. + +type({v}) *luaref-type()* + Returns the type of its only argument, coded as a string. The possible + results of this function are `"nil"` (a string, not the value `nil`), + `"number"`, `"string"`, `"boolean`, `"table"`, `"function"`, + `"thread"`, and `"userdata"`. + +unpack({list} [, {i} [, {j}]]) *luaref-unpack()* + Returns the elements from the given table. This function is equivalent + to +> + return list[i], list[i+1], ..., list[j] +< + except that the above code can be written only for a fixed number of + elements. By default, {i} is 1 and {j} is the length of the list, as + defined by the length operator(see |luaref-langLength|). + +_VERSION *luaref-_VERSION()* + A global variable (not a function) that holds a string containing the + current interpreter version. The current contents of this string is + `"Lua 5.1"` . + +xpcall({f}, {err}) *luaref-xpcall()* + This function is similar to `pcall` (see |luaref-pcall|), except that + you can set a new error handler. + + `xpcall` calls function {f} in protected mode, using {err} as the + error handler. Any error inside {f} is not propagated; instead, + `xpcall` catches the error, calls the {err} function with the original + error object, and returns a status code. Its first result is the + status code (a boolean), which is true if the call succeeds without + errors. In this case, `xpcall` also returns all results from the call, + after this first result. In case of any error, `xpcall` returns + `false` plus the result from {err}. + +============================================================================== +5.2 Coroutine Manipulation *luaref-libCoro* + +The operations related to coroutines comprise a sub-library of the basic +library and come inside the table `coroutine`. See |luaref-langCoro| for a +general description of coroutines. + +coroutine.create({f}) *coroutine.create()* + Creates a new coroutine, with body {f}. {f} must be a Lua function. + Returns this new coroutine, an object with type `"thread"`. + +coroutine.resume({co} [, {val1}, {...}]) *coroutine.resume()* + Starts or continues the execution of coroutine {co}. The first time + you resume a coroutine, it starts running its body. The values {val1}, + {...} are passed as arguments to the body function. If the coroutine has + yielded, `resume` restarts it; the values {val1}, {...} are passed as + the results from the yield. + + If the coroutine runs without any errors, `resume` returns `true` plus + any values passed to `yield` (if the coroutine yields) or any values + returned by the body function(if the coroutine terminates). If there + is any error, `resume` returns `false` plus the error message. + +coroutine.running() *coroutine.running()* + Returns the running coroutine, or `nil` when called by the main + thread. + +coroutine.status({co}) *coroutine.status()* + Returns the status of coroutine {co}, as a string: `"running"`, if the + coroutine is running (that is, it called `status`); `"suspended"`, if + the coroutine is suspended in a call to `yield`, or if it has not + started running yet; `"normal"` if the coroutine is active but not + running (that is, it has resumed another coroutine); and `"dead"` if + the coroutine has finished its body function, or if it has stopped + with an error. + +coroutine.wrap({f}) *coroutine.wrap()* + Creates a new coroutine, with body {f}. {f} must be a Lua function. + Returns a function that resumes the coroutine each time it is called. + Any arguments passed to the function behave as the extra arguments to + `resume`. Returns the same values returned by `resume`, except the + first boolean. In case of error, propagates the error. + +coroutine.yield({...}) *coroutine.yield()* + Suspends the execution of the calling coroutine. The coroutine cannot + be running a C function, a metamethod, or an iterator. Any arguments + to `yield` are passed as extra results to `resume`. + +============================================================================== +5.3 - Modules *luaref-libModule* + +The package library provides basic facilities for loading and building modules +in Lua. It exports two of its functions directly in the global environment: +`require` and `module` (see |luaref-require| and |luaref-module|). Everything else is +exported in a table `package`. + +module({name} [, {...}]) *luaref-module()* + Creates a module. If there is a table in `package.loaded[name]`, this + table is the module. Otherwise, if there is a global table `t` with + the given name, this table is the module. Otherwise creates a new + table `t` and sets it as the value of the global {name} and the value + of `package.loaded[name]`. This function also initializes `t._NAME` + with the given name, `t._M` with the module (`t` itself), and + `t._PACKAGE` with the package name (the full module name minus last + component; see below). Finally, `module` sets `t` as the new + environment of the current function and the new value of + `package.loaded[name]`, so that `require` (see |luaref-require|) + returns `t`. + + If {name} is a compound name (that is, one with components separated + by dots), `module` creates (or reuses, if they already exist) tables + for each component. For instance, if {name} is `a.b.c`, then `module` + stores the module table in field `c` of field `b` of global `a`. + + This function may receive optional `options` after the module name, + where each option is a function to be applied over the module. + +require({modname}) *luaref-require()* + Loads the given module. The function starts by looking into the + `package.loaded` table to determine whether {modname} is already + loaded. If it is, then `require` returns the value stored at + `package.loaded[modname]`. Otherwise, it tries to find a `loader` for + the module. + + To find a loader, first `require` queries `package.preload[modname]`. + If it has a value, this value (which should be a function) is the + loader. Otherwise `require` searches for a Lua loader using the path + stored in `package.path`. If that also fails, it searches for a C + loader using the path stored in `package.cpath`. If that also fails, + it tries an `all-in-one` loader (see below). + + When loading a C library, `require` first uses a dynamic link facility + to link the application with the library. Then it tries to find a C + function inside this library to be used as the loader. The name of + this C function is the string `"luaopen_"` concatenated with a copy of + the module name where each dot is replaced by an underscore. Moreover, + if the module name has a hyphen, its prefix up to (and including) the + first hyphen is removed. For instance, if the module name is + `a.v1-b.c`, the function name will be `luaopen_b_c`. + + If `require` finds neither a Lua library nor a C library for a module, + it calls the `all-in-one loader`. This loader searches the C path for + a library for the root name of the given module. For instance, when + requiring `a.b.c`, it will search for a C library for `a`. If found, + it looks into it for an open function for the submodule; in our + example, that would be `luaopen_a_b_c`. With this facility, a package + can pack several C submodules into one single library, with each + submodule keeping its original open function. + + Once a loader is found, `require` calls the loader with a single + argument, {modname}. If the loader returns any value, `require` + assigns the returned value to `package.loaded[modname]`. If the loader + returns no value and has not assigned any value to + `package.loaded[modname]`, then `require` assigns `true` to this + entry. In any case, `require` returns the final value of + `package.loaded[modname]`. + + If there is any error loading or running the module, or if it cannot + find any loader for the module, then `require` signals an error. + +package.cpath *package.cpath()* + The path used by `require` to search for a C loader. + + Lua initializes the C path `package.cpath` in the same way it + initializes the Lua path `package.path`, using the environment + variable `LUA_CPATH` (plus another default path defined in + `luaconf.h`). + +package.loaded *package.loaded()* + A table used by `require` to control which modules are already loaded. + When you require a module `modname` and `package.loaded[modname]` is + not false, `require` simply returns the value stored there. + +package.loadlib({libname}, {funcname}) *package.loadlib()* + Dynamically links the host program with the C library {libname}. + Inside this library, looks for a function {funcname} and returns this + function as a C function. (So, {funcname} must follow the protocol + (see |luaref-lua_CFunction|)). + + This is a low-level function. It completely bypasses the package and + module system. Unlike `require`, it does not perform any path + searching and does not automatically adds extensions. {libname} must + be the complete file name of the C library, including if necessary a + path and extension. {funcname} must be the exact name exported by the + C library (which may depend on the C compiler and linker used). + + This function is not supported by ANSI C. As such, it is only + available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, + plus other Unix systems that support the `dlfcn` standard). + +package.path *package.path()* + The path used by `require` to search for a Lua loader. + + At start-up, Lua initializes this variable with the value of the + environment variable `LUA_PATH` or with a default path defined in + `luaconf.h`, if the environment variable is not defined. Any `";;"` in + the value of the environment variable is replaced by the default path. + + A path is a sequence of `templates` separated by semicolons. For each + template, `require` will change each interrogation mark in the + template by `filename`, which is `modname` with each dot replaced by a + "directory separator" (such as `"/"` in Unix); then it will try to + load the resulting file name. So, for instance, if the Lua path is +> + "./?.lua;./?.lc;/usr/local/?/init.lua" +< + the search for a Lua loader for module `foo` will try to load the + files `./foo.lua`, `./foo.lc`, and `/usr/local/foo/init.lua`, in that + order. + +package.preload *package.preload()* + A table to store loaders for specific modules (see |luaref-require|). + +package.seeall({module}) *package.seeall()* + Sets a metatable for {module} with its `__index` field referring to + the global environment, so that this module inherits values from the + global environment. To be used as an option to function {module}. + +============================================================================== +5.4 - String Manipulation *luaref-libString* + +This library provides generic functions for string manipulation, such as +finding and extracting substrings, and pattern matching. When indexing a +string in Lua, the first character is at position 1 (not at 0, as in C). +Indices are allowed to be negative and are interpreted as indexing backwards, +from the end of the string. Thus, the last character is at position -1, and +so on. + +The string library provides all its functions inside the table `string`. +It also sets a metatable for strings where the `__index` field points to the +`string` table. Therefore, you can use the string functions in object-oriented +style. For instance, `string.byte(s, i)` can be written as `s:byte(i)`. + +string.byte({s} [, {i} [, {j}]]) *string.byte()* + Returns the internal numerical codes of the characters `s[i]`, + `s[i+1]`,..., `s[j]`. The default value for {i} is 1; the default + value for {j} is {i}. + + Note that numerical codes are not necessarily portable across + platforms. + +string.char({...}) *string.char()* + Receives zero or more integers. Returns a string with length equal to + the number of arguments, in which each character has the internal + numerical code equal to its correspondent argument. + + Note that numerical codes are not necessarily portable across + platforms. + +string.dump({function}) *string.dump()* + Returns a string containing a binary representation of the given + function, so that a later |luaref-loadstring| on this string returns a + copy of the function. {function} must be a Lua function without + upvalues. + +string.find({s}, {pattern} [, {init} [, {plain}]]) *string.find()* + Looks for the first match of {pattern} in the string {s}. If it finds + a match, then {find} returns the indices of {s} where this occurrence + starts and ends; otherwise, it returns `nil`. A third, optional + numerical argument {init} specifies where to start the search; its + default value is 1 and may be negative. A value of {true} as a fourth, + optional argument {plain} turns off the pattern matching facilities, + so the function does a plain "find substring" operation, with no + characters in {pattern} being considered "magic". Note that if {plain} + is given, then {init} must be given as well. + + If the pattern has captures, then in a successful match the captured + values are also returned, after the two indices. + +string.format({formatstring}, {...}) *string.format()* + Returns a formatted version of its variable number of arguments + following the description given in its first argument (which must be a + string). The format string follows the same rules as the `printf` + family of standard C functions. The only differences are that the + options/modifiers `*`, `l`, `L`, `n`, `p`, and `h` are not supported + and that there is an extra option, `q`. The `q` option formats a + string in a form suitable to be safely read back by the Lua + interpreter: the string is written between double quotes, and all + double quotes, newlines, embedded zeros, and backslashes in the string + are correctly escaped when written. For instance, the call +> + string.format('%q', 'a string with "quotes" and \n new line') +< + will produce the string: +> + "a string with \"quotes\" and \ + new line" +< + The options `c`, `d`, `E`, `e`, `f`, `g`, `G`, `i`, `o`, `u`, `X`, and + `x` all expect a number as argument, whereas `q` and `s` expect a + string. + + This function does not accept string values containing embedded zeros. + +string.gmatch({s}, {pattern}) *string.gmatch()* + Returns an iterator function that, each time it is called, returns the + next captures from {pattern} over string {s}. + + If {pattern} specifies no captures, then the whole match is produced + in each call. + + As an example, the following loop +> + s = "hello world from Lua" + for w in string.gmatch(s, "%a+") do + print(w) + end +< + will iterate over all the words from string {s}, printing one per + line. The next example collects all pairs `key=value` from the given + string into a table: +> + t = {} + s = "from=world, to=Lua" + for k, v in string.gmatch(s, "(%w+)=(%w+)") do + t[k] = v + end +< + +string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsu{b}()* + Returns a copy of {s} in which all occurrences of the {pattern} have + been replaced by a replacement string specified by {repl}, which may + be a string, a table, or a function. `gsub` also returns, as its + second value, the total number of substitutions made. + + If {repl} is a string, then its value is used for replacement. The + character `%` works as an escape character: any sequence in {repl} of + the form `%n`, with {n} between 1 and 9, stands for the value of the + {n} -th captured substring (see below). The sequence `%0` stands for + the whole match. The sequence `%%` stands for a single `%`. + + If {repl} is a table, then the table is queried for every match, using + the first capture as the key; if the pattern specifies no captures, + then the whole match is used as the key. + + If {repl} is a function, then this function is called every time a + match occurs, with all captured substrings passed as arguments, in + order; if the pattern specifies no captures, then the whole match is + passed as a sole argument. + + If the value returned by the table query or by the function call is a + string or a number, then it is used as the replacement string; + otherwise, if it is `false` or `nil`, then there is no replacement + (that is, the original match is kept in the string). + + The optional last parameter {n} limits the maximum number of + substitutions to occur. For instance, when {n} is 1 only the first + occurrence of `pattern` is replaced. + + Here are some examples: +> + x = string.gsub("hello world", "(%w+)", "%1 %1") + --> x="hello hello world world" + + x = string.gsub("hello world", "%w+", "%0 %0", 1) + --> x="hello hello world" + + x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") + --> x="world hello Lua from" + + x = string.gsub("home = `HOME, user = ` USER", "%$(%w+)", os.getenv) + --> x="home = /home/roberto, user = roberto" + + x = string.gsub("4+5 = `return 4+5` ", "% `(.-)%` ", function (s) + return loadstring(s)() + end) + --> x="4+5 = 9" + + local t = {name="lua", version="5.1"} + x = string.gsub(" `name%-` version.tar.gz", "%$(%w+)", t) + --> x="lua-5.1.tar.gz" +< + +string.len({s}) *string.len()* + Receives a string and returns its length. The empty string `""` has + length 0. Embedded zeros are counted, so `"a\000b\000c"` has length 5. + +string.lower({s}) *string.lower()* + Receives a string and returns a copy of this string with all uppercase + letters changed to lowercase. All other characters are left unchanged. + The definition of what an uppercase letter is depends on the current + locale. + +string.match({s}, {pattern} [, {init}]) *string.match()* + Looks for the first `match` of {pattern} in the string {s}. If it + finds one, then `match` returns the captures from the pattern; + otherwise it returns `nil`. If {pattern} specifies no captures, then + the whole match is returned. A third, optional numerical argument + {init} specifies where to start the search; its default value is 1 and + may be negative. + +string.rep({s}, {n}) *string.rep()* + Returns a string that is the concatenation of {n} copies of the string + {s}. + +string.reverse({s}) *string.reverse()* + Returns a string that is the string {s} reversed. + +string.sub({s}, {i} [, {j}]) *string.sub()* + Returns the substring of {s} that starts at {i} and continues until + {j}; {i} and {j} may be negative. If {j} is absent, then it is assumed + to be equal to `-1` (which is the same as the string length). In + particular, the call `string.sub(s,1,j)` returns a prefix of {s} with + length {j}, and `string.sub(s,-i)` returns a suffix of {s} with length + {i}. + +string.upper({s}) *string.upper()* + Receives a string and returns a copy of that string with all lowercase + letters changed to uppercase. All other characters are left unchanged. + The definition of what a lowercase letter is depends on the current + locale. + +------------------------------------------------------------------------------ +5.4.1 Patterns *luaref-patterns* *luaref-libStringPat* + +A character class is used to represent a set of characters. The following +combinations are allowed in describing a character class: + + - `x` (where `x` is not one of the magic characters `^$()%.[]*+-?`) + represents the character `x` itself. + - `.` (a dot) represents all characters. + - `%a` represents all letters. + - `%c` represents all control characters. + - `%d` represents all digits. + - `%l` represents all lowercase letters. + - `%p` represents all punctuation characters. + - `%s` represents all space characters. + - `%u` represents all uppercase letters. + - `%w` represents all alphanumeric characters. + - `%x` represents all hexadecimal digits. + - `%z` represents the character with representation `0`. + - `%x` (where `x` is any non-alphanumeric character) represents the + character `x`. This is the standard way to escape the magic + characters. Any punctuation character (even the non-magic) can be + preceded by a `%` when used to represent itself in a pattern. + + - `[set]` represents the class which is the union of all characters in + `set`. A range of characters may be specified by separating the end + characters of the range with a `-`. All classes `%x` described + above may also be used as components in `set`. All other characters + in `set` represent themselves. For example, `[%w_]` (or `[_%w]`) + represents all alphanumeric characters plus the underscore, `[0-7]` + represents the octal digits, and `[0-7%l%-]` represents the octal + digits plus the lowercase letters plus the `-` character. + + The interaction between ranges and classes is not defined. Therefore, + patterns like `[%a-z]` or `[a-%%]` have no meaning. + + - `[^set]` represents the complement of `set`, where `set` is interpreted + as above. + +For all classes represented by single letters (`%a`, `%c`, etc.), the +corresponding uppercase letter represents the complement of the class. For +instance, `%S` represents all non-space characters. + +The definitions of letter, space, and other character groups depend on the +current locale. In particular, the class `[a-z]` may not be equivalent to `%l`. + + *luaref-patternitem* +Pattern Item:~ +------------- +A pattern item may be + + - a single character class, which matches any single character in the + class; + - a single character class followed by `*`, which matches 0 or more + repetitions of characters in the class. These repetition items will + always match the longest possible sequence; + - a single character class followed by `+`, which matches 1 or more + repetitions of characters in the class. These repetition items will + always match the longest possible sequence; + - a single character class followed by `-`, which also matches 0 or + more repetitions of characters in the class. Unlike `*`, these + repetition items will always match the shortest possible sequence; + - a single character class followed by `?`, which matches 0 or 1 + occurrences of a character in the class; + - `%n`, for `n` between 1 and 9; such item matches a substring equal to the + `n` -th captured string (see below); + - `%bxy`, where `x` and `y` are two distinct characters; such item matches + strings that start with `x`, end with `y`, and where the `x` and `y` + are balanced. This means that, if one reads the string from left to + right, counting `+1` for an `x` and `-1` for a `y`, the ending `y` is the first + `y` where the count reaches 0. For instance, the item `%b()` matches + expressions with balanced parentheses. + + *luaref-pattern* +Pattern:~ +-------- +A pattern is a sequence of pattern items. A `^` at the beginning of a pattern +anchors the match at the beginning of the subject string. A `$` at the end of +a pattern anchors the match at the end of the subject string. At other +positions, `^` and `$` have no special meaning and represent themselves. + + *luaref-capture* +Captures:~ +--------- +A pattern may contain sub-patterns enclosed in parentheses; they describe +captures. When a match succeeds, the substrings of the subject string that +match captures are stored (captured) for future use. Captures are numbered +according to their left parentheses. For instance, in the pattern +`"(a*(.)%w(%s*))"`, the part of the string matching `"a*(.)%w(%s*)"` is stored +as the first capture (and therefore has number 1); the character matching `.` +is captured with number 2, and the part matching `%s*` has number 3. + +As a special case, the empty capture `()` captures the current string position +(a number). For instance, if we apply the pattern `"()aa()"` on the +string `"flaaap"`, there will be two captures: 3 and 5. + +A pattern cannot contain embedded zeros. Use `%z` instead. + +============================================================================== +5.5 Table Manipulation *luaref-libTable* + +This library provides generic functions for table manipulation. It provides +all its functions inside the table `table`. + +Most functions in the table library assume that the table represents an array +or a list. For those functions, when we talk about the "length" of a table we +mean the result of the length operator. + +table.concat({table} [, {sep} [, {i} [, {j}]]]) *table.concat()* + Given an array where all elements are strings or numbers, returns + `table[i]..sep..table[i+1] ... sep..table[j]`. The default value for + {sep} is the empty string, the default for {i} is 1, and the default + for {j} is the length of the table. If {i} is greater than {j}, + returns the empty string. + +table.foreach({table}, {f}) *table.foreach()* + Executes the given {f} over all elements of {table}. For each element, + {f} is called with the index and respective value as arguments. If {f} + returns a non-`nil` value, then the loop is broken, and this value is + returned as the final value of `table.foreach`. + + See |luaref-next| for extra information about table traversals. + +table.foreachi({table}, {f}) *table.foreachi()* + Executes the given {f} over the numerical indices of {table}. For each + index, {f} is called with the index and respective value as arguments. + Indices are visited in sequential order, from 1 to `n`, where `n` is + the length of the table. If {f} returns a non-`nil` value, then the + loop is broken and this value is returned as the result of + `table.foreachi`. + +table.insert({table}, [{pos},] {value}) *table.insert()* + Inserts element {value} at position {pos} in {table}, shifting up + other elements to open space, if necessary. The default value for + {pos} is `n+1`, where `n` is the length of the table (see + |luaref-langLength|), so that a call `table.insert(t,x)` inserts `x` + at the end of table `t`. + +table.maxn({table}) *table.maxn()* + Returns the largest positive numerical index of the given table, or + zero if the table has no positive numerical indices. (To do its job + this function does a linear traversal of the whole table.) + +table.remove({table} [, {pos}]) *table.remove()* + Removes from {table} the element at position {pos}, shifting down + other elements to close the space, if necessary. Returns the value of + the removed element. The default value for {pos} is `n`, where `n` is + the length of the table (see |luaref-langLength|), so that a call + `table.remove(t)` removes the last element of table `t`. + +table.sort({table} [, {comp}]) *table.sort()* + Sorts table elements in a given order, `in-place`, from `table[1]` to + `table[n]`, where `n` is the length of the table (see + |luaref-langLength|). If {comp} is given, then it must be a function + that receives two table elements, and returns true when the first is + less than the second (so that `not comp(a[i+1],a[i])` will be true + after the sort). If {comp} is not given, then the standard Lua + operator `<` is used instead. + +The sort algorithm is `not` stable, that is, elements considered equal by the +given order may have their relative positions changed by the sort. + +============================================================================== +5.6 Mathematical Functions *luaref-libMath* + +This library is an interface to most of the functions of the standard C math +library. It provides all its functions inside the table `math`. + +math.abs({x}) *math.abs()* + Returns the absolute value of {x}. + +math.acos({x}) *math.acos()* + Returns the arc cosine of {x} (in radians). + +math.asin({x}) *math.asin()* + Returns the arc sine of {x} (in radians). + +math.atan({x}) *math.atan()* + Returns the arc tangent of {x} (in radians). + +math.atan2({x}, {y}) *math.atan2()* + Returns the arc tangent of `x/y` (in radians), but uses the signs of + both parameters to find the quadrant of the result. (It also handles + correctly the case of {y} being zero.) + +math.ceil({x}) *math.ceil()* + Returns the smallest integer larger than or equal to {x}. + +math.cos({x}) *math.cos()* + Returns the cosine of {x} (assumed to be in radians). + +math.cosh({x}) *math.cosh()* + Returns the hyperbolic cosine of {x}. + +math.deg({x}) *math.deg()* + Returns the angle {x} (given in radians) in degrees. + +math.exp({x}) *math.exp()* + Returns the value `e^x`. + +math.floor({x}) *math.floor()* + Returns the largest integer smaller than or equal to {x}. + +math.fmod({x}, {y}) *math.fmod()* + Returns the remainder of the division of {x} by {y}. + +math.frexp({x}) *math.frexp()* + Returns `m` and `e` such that `x = m * 2^e`, `e` is an integer and the + absolute value of `m` is in the range `[0.5, 1)` (or zero when {x} is + zero). + +math.huge *math.huge()* + The value `HUGE_VAL`, a value larger than or equal to any other + numerical value. + +math.ldexp({m}, {e}) *math.ldexp()* + Returns `m * 2^e` (`e` should be an integer). + +math.log({x}) *math.log()* + Returns the natural logarithm of {x}. + +math.log10({x}) *math.log10()* + Returns the base-10 logarithm of {x}. + +math.max({x}, {...}) *math.max()* + Returns the maximum value among its arguments. + +math.min({x}, {...}) *math.min()* + Returns the minimum value among its arguments. + +math.modf({x}) *math.modf()* + Returns two numbers, the integral part of {x} and the fractional part + of {x}. + +math.pi *math.pi()* + The value of `pi`. + +math.pow({x}, {y}) *math.pow()* + Returns `x^y`. (You can also use the expression `x^y` to compute this + value.) + +math.rad({x}) *math.rad()* + Returns the angle {x} (given in degrees) in radians. + +math.random([{m} [, {n}]]) *math.random()* + This function is an interface to the simple pseudo-random generator + function `rand` provided by ANSI C. (No guarantees can be given for + its statistical properties.) + + When called without arguments, returns a pseudo-random real number in + the range `[0,1)`. When called with a number {m}, `math.random` + returns a pseudo-random integer in the range `[1, m]`. When called + with two numbers {m} and {n}, `math.random` returns a pseudo-random + integer in the range `[m, n]`. + +math.randomseed({x}) *math.randomseed()* + Sets {x} as the "seed" for the pseudo-random generator: equal seeds + produce equal sequences of numbers. + +math.sin({x}) *math.sin()* + Returns the sine of {x} (assumed to be in radians). + +math.sinh({x}) *math.sinh()* + Returns the hyperbolic sine of {x}. + +math.sqrt({x}) *math.sqrt()* + Returns the square root of {x}. (You can also use the expression + `x^0.5` to compute this value.) + +math.tan({x}) *math.tan()* + Returns the tangent of {x} (assumed to be in radians). + +math.tanh({x}) *math.tanh()* + Returns the hyperbolic tangent of {x}. + +============================================================================== +5.6 Input and Output Facilities *luaref-libIO* + +The I/O library provides two different styles for file manipulation. The first +one uses implicit file descriptors; that is, there are operations to set a +default input file and a default output file, and all input/output operations +are over these default files. The second style uses explicit file +descriptors. + +When using implicit file descriptors, all operations are supplied by +table `io`. When using explicit file descriptors, the operation `io.open` returns +a file descriptor and then all operations are supplied as methods of the file +descriptor. + +The table `io` also provides three predefined file descriptors with their usual +meanings from C: `io.stdin`, `io.stdout`, and `io.stderr`. + +Unless otherwise stated, all I/O functions return `nil` on failure (plus an +error message as a second result) and some value different from `nil` on +success. + +io.close([{file}]) *io.close()* + Equivalent to `file:close`. Without a {file}, closes the default + output file. + +io.flush() *io.flush()* + Equivalent to `file:flush` over the default output file. + +io.input([{file}]) *io.input()* + When called with a file name, it opens the named file (in text mode), + and sets its handle as the default input file. When called with a file + handle, it simply sets this file handle as the default input file. + When called without parameters, it returns the current default input + file. + + In case of errors this function raises the error, instead of returning + an error code. + +io.lines([{filename}]) *io.lines()* + Opens the given file name in read mode and returns an iterator + function that, each time it is called, returns a new line from the + file. Therefore, the construction + + `for line in io.lines(filename) do` `body` `end` + + will iterate over all lines of the file. When the iterator function + detects the end of file, it returns `nil` (to finish the loop) and + automatically closes the file. + + The call `io.lines()` (without a file name) is equivalent to + `io.input():lines()`; that is, it iterates over the lines of the + default input file. In this case it does not close the file when the + loop ends. + +io.open({filename} [, {mode}]) *io.open()* + This function opens a file, in the mode specified in the string + {mode}. It returns a new file handle, or, in case of errors, `nil` + plus an error message. + + The {mode} string can be any of the following: + + - `"r"` read mode (the default); + - `"w"` write mode; + - `"a"` append mode; + - `"r+"` update mode, all previous data is preserved; + - `"w+"` update mode, all previous data is erased; + - `"a+"` append update mode, previous data is preserved, writing is + only allowed at the end of file. + + The {mode} string may also have a `b` at the end, which is needed in + some systems to open the file in binary mode. This string is exactly + what is used in the standard C function `fopen`. + +io.output([{file}]) *io.output()* + Similar to `io.input`, but operates over the default output file. + +io.popen({prog} [, {mode}]) *io.popen()* + Starts program {prog} in a separated process and returns a file handle + that you can use to read data from this program (if {mode} is `"r"`, + the default) or to write data to this program (if {mode} is `"w"`). + + This function is system dependent and is not available on all + platforms. + +io.read({...}) *io.read()* + Equivalent to `io.input():read`. + +io.tmpfile() *io.tmpfile()* + Returns a handle for a temporary file. This file is opened in update + mode and it is automatically removed when the program ends. + +io.type({obj}) *io.type()* + Checks whether {obj} is a valid file handle. Returns the string + `"file"` if {obj} is an open file handle, `"closed file"` if {obj} is + a closed file handle, or `nil` if {obj} is not a file handle. + +io.write({...}) *io.write()* + Equivalent to `io.output():write`. + +file:close() *luaref-file:close()* + Closes `file`. Note that files are automatically closed when their + handles are garbage collected, but that takes an unpredictable amount + of time to happen. + +file:flush() *luaref-file:flush()* + Saves any written data to `file`. + +file:lines() *luaref-file:lines()* + Returns an iterator function that, each time it is called, returns a + new line from the file. Therefore, the construction + + `for line in file:lines() do` `body` `end` + + will iterate over all lines of the file. (Unlike `io.lines`, this + function does not close the file when the loop ends.) + +file:read({...}) *luaref-file:read()* + Reads the file `file`, according to the given formats, which specify + what to read. For each format, the function returns a string (or a + number) with the characters read, or `nil` if it cannot read data with + the specified format. When called without formats, it uses a default + format that reads the entire next line (see below). + + The available formats are + + `"*n"` reads a number; this is the only format that returns a + number instead of a string. + `"*a"` reads the whole file, starting at the current position. On + end of file, it returns the empty string. + `"*l"` reads the next line (skipping the end of line), returning + `nil` on end of file. This is the default format. + `number` reads a string with up to that number of characters, + returning `nil` on end of file. If number is zero, it reads + nothing and returns an empty string, or `nil` on end of file. + +file:seek([{whence}] [, {offset}]) *luaref-file:seek()* + Sets and gets the file position, measured from the beginning of the + file, to the position given by {offset} plus a base specified by the + string {whence}, as follows: + + - `"set"`: base is position 0 (beginning of the file); + - `"cur"`: base is current position; + - `"end"`: base is end of file; + + In case of success, function `seek` returns the final file position, + measured in bytes from the beginning of the file. If this function + fails, it returns `nil`, plus a string describing the error. + + The default value for {whence} is `"cur"`, and for {offset} is 0. + Therefore, the call `file:seek()` returns the current file position, + without changing it; the call `file:seek("set")` sets the position to + the beginning of the file (and returns 0); and the call + `file:seek("end")` sets the position to the end of the file, and + returns its size. + +file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()* + Sets the buffering mode for an output file. There are three available + modes: + + `"no"` no buffering; the result of any output operation appears + immediately. + `"full"` full buffering; output operation is performed only when + the buffer is full (or when you explicitly `flush` the file + (see |luaref-io.flush|). + `"line"` line buffering; output is buffered until a newline is + output or there is any input from some special files (such as + a terminal device). + + For the last two cases, {size} specifies the size of the buffer, in + bytes. The default is an appropriate size. + +file:write({...}) *luaref-file:write()* + Writes the value of each of its arguments to `file`. The arguments + must be strings or numbers. To write other values, use `tostring` + |luaref-tostring| or `string.format` |luaref-string.format| before + `write`. + +============================================================================== +5.8 Operating System Facilities *luaref-libOS* + +This library is implemented through table `os`. + +os.clock() *os.clock()* + Returns an approximation of the amount in seconds of CPU time used by + the program. + +os.date([{format} [, {time}]]) *os.date()* + Returns a string or a table containing date and time, formatted + according to the given string {format}. + + If the {time} argument is present, this is the time to be formatted + (see the `os.time` function |luaref-os.time| for a description of this + value). Otherwise, `date` formats the current time. + + If {format} starts with `!`, then the date is formatted in + Coordinated Universal Time. After this optional character, if {format} + is the string `"*t"`, then `date` returns a table with the following + fields: `year` (four digits), `month` (1-12), `day` (1-31), `hour` + (0-23), `min` (0-59), `sec` (0-61), `wday` (weekday, Sunday is 1), + `yday` (day of the year), and `isdst` (daylight saving flag, a + boolean). + + If {format} is not `"*t"`, then `date` returns the date as a string, + formatted according to the same rules as the C function `strftime`. + + When called without arguments, `date` returns a reasonable date and + time representation that depends on the host system and on the current + locale (that is, `os.date()` is equivalent to `os.date("%c")`). + +os.difftime({t2}, {t1}) *os.difftime()* + Returns the number of seconds from time {t1} to time {t2}. In POSIX, + Windows, and some other systems, this value is exactly `t2 - t1` . + +os.execute([{command}]) *os.execute()* + This function is equivalent to the C function `system`. It passes + {command} to be executed by an operating system shell. It returns a + status code, which is system-dependent. If {command} is absent, then + it returns nonzero if a shell is available and zero otherwise. + +os.exit([{code}]) *os.exit()* + Calls the C function `exit`, with an optional {code}, to terminate the + host program. The default value for {code} is the success code. + +os.getenv({varname}) *os.getenv()* + Returns the value of the process environment variable {varname}, or + `nil` if the variable is not defined. + +os.remove({filename}) *os.remove()* + Deletes the file with the given name. Directories must be empty to be + removed. If this function fails, it returns `nil`, plus a string + describing the error. + +os.rename({oldname}, {newname}) *os.rename()* + Renames file named {oldname} to {newname}. If this function fails, it + returns `nil`, plus a string describing the error. + +os.setlocale({locale} [, {category}]) *os.setlocale()* + Sets the current locale of the program. {locale} is a string + specifying a locale; {category} is an optional string describing which + category to change: `"all"`, `"collate"`, `"ctype"`, `"monetary"`, + `"numeric"`, or `"time"`; the default category is `"all"`. The + function returns the name of the new locale, or `nil` if the request + cannot be honored. + +os.time([{table}]) *os.time()* + Returns the current time when called without arguments, or a time + representing the date and time specified by the given table. This + table must have fields `year`, `month`, and `day`, and may have fields + `hour`, `min`, `sec`, and `isdst` (for a description of these fields, + see the `os.date` function |luaref-os.date|). + + The returned value is a number, whose meaning depends on your system. + In POSIX, Windows, and some other systems, this number counts the + number of seconds since some given start time (the "epoch"). In other + systems, the meaning is not specified, and the number returned by + `time` can be used only as an argument to `date` and `difftime`. + +os.tmpname() *os.tmpname()* + Returns a string with a file name that can be used for a temporary + file. The file must be explicitly opened before its use and explicitly + removed when no longer needed. + +============================================================================== +5.9 The Debug Library *luaref-libDebug* + +This library provides the functionality of the debug interface to Lua +programs. You should exert care when using this library. The functions +provided here should be used exclusively for debugging and similar tasks, such +as profiling. Please resist the temptation to use them as a usual programming +tool: they can be very slow. Moreover, several of its functions violate some +assumptions about Lua code (e.g., that variables local to a function cannot be +accessed from outside or that userdata metatables cannot be changed by Lua +code) and therefore can compromise otherwise secure code. + +All functions in this library are provided inside the `debug` table. All +functions that operate over a thread have an optional first argument which is +the thread to operate over. The default is always the current thread. + +debug.debug() *debug.debug()* + Enters an interactive mode with the user, running each string that the + user enters. Using simple commands and other debug facilities, the + user can inspect global and local variables, change their values, + evaluate expressions, and so on. A line containing only the word + `cont` finishes this function, so that the caller continues its + execution. + + Note that commands for `debug.debug` are not lexically nested within + any function, and so have no direct access to local variables. + +debug.getfenv(o) *debug.getfenv()* + Returns the environment of object {o}. + +debug.gethook([{thread}]) *debug.gethook()* + Returns the current hook settings of the thread, as three values: the + current hook function, the current hook mask, and the current hook + count (as set by the `debug.sethook` function). + +debug.getinfo([{thread},] {function} [, {what}]) *debug.getinfo()* + Returns a table with information about a function. You can give the + function directly, or you can give a number as the value of + {function}, which means the function running at level {function} of + the call stack of the given thread: level 0 is the current function + (`getinfo` itself); level 1 is the function that called `getinfo`; and + so on. If {function} is a number larger than the number of active + functions, then `getinfo` returns `nil`. + + The returned table may contain all the fields returned by + `lua_getinfo` (see |luaref-lua_getinfo|), with the string {what} + describing which fields to fill in. The default for {what} is to get + all information available, except the table of valid lines. If + present, the option `f` adds a field named `func` with the function + itself. If present, the option `L` adds a field named `activelines` + with the table of valid lines. + + For instance, the expression `debug.getinfo(1,"n").name` returns the + name of the current function, if a reasonable name can be found, and + `debug.getinfo(print)` returns a table with all available information + about the `print` function. + +debug.getlocal([{thread},] {level}, {local}) *debug.getlocal()* + This function returns the name and the value of the local variable + with index {local} of the function at level {level} of the stack. (The + first parameter or local variable has index 1, and so on, until the + last active local variable.) The function returns `nil` if there is no + local variable with the given index, and raises an error when called + with a {level} out of range. (You can call `debug.getinfo` + |luaref-debug.getinfo| to check whether the level is valid.) + + Variable names starting with `(` (open parentheses) represent + internal variables (loop control variables, temporaries, and C + function locals). + +debug.getmetatable({object}) *debug.getmetatable()* + Returns the metatable of the given {object} or `nil` if it does not + have a metatable. + +debug.getregistry() *debug.getregistry()* + Returns the registry table (see |luaref-apiRegistry|). + +debug.getupvalue({func}, {up}) *debug.getupvalue()* + This function returns the name and the value of the upvalue with index + {up} of the function {func}. The function returns `nil` if there is no + upvalue with the given index. + +debug.setfenv({object}, {table}) *debug.setfenv()* + Sets the environment of the given {object} to the given {table}. + Returns {object}. + +debug.sethook([{thread},] {hook}, {mask} [, {count}]) *debug.sethook()* + Sets the given function as a hook. The string {mask} and the number + {count} describe when the hook will be called. The string mask may + have the following characters, with the given meaning: + + - `"c"` : The hook is called every time Lua calls a function; + - `"r"` : The hook is called every time Lua returns from a function; + - `"l"` : The hook is called every time Lua enters a new line of + code. + + With a {count} different from zero, the hook is called after every + {count} instructions. + + When called without arguments, the `debug.sethook` turns off the hook. + + When the hook is called, its first parameter is a string describing + the event that triggered its call: `"call"`, `"return"` (or `"tail + return"`), `"line"`, and `"count"`. For line events, the hook also + gets the new line number as its second parameter. Inside a hook, you + can call `getinfo` with level 2 to get more information about the + running function (level 0 is the `getinfo` function, and level 1 is + the hook function), unless the event is `"tail return"`. In this case, + Lua is only simulating the return, and a call to `getinfo` will return + invalid data. + +debug.setlocal([{thread},] {level}, {local}, {value}) *debug.setlocal()* + This function assigns the value {value} to the local variable with + index {local} of the function at level {level} of the stack. The + function returns `nil` if there is no local variable with the given + index, and raises an error when called with a {level} out of range. + (You can call `getinfo` to check whether the level is valid.) + Otherwise, it returns the name of the local variable. + +debug.setmetatable({object}, {table}) *debug.setmetatable()* + Sets the metatable for the given {object} to the given {table} (which + can be `nil`). + +debug.setupvalue({func}, {up}, {value}) *debug.setupvalue()* + This function assigns the value {value} to the upvalue with index {up} + of the function {func}. The function returns `nil` if there is no + upvalue with the given index. Otherwise, it returns the name of the + upvalue. + +debug.traceback([{thread},] [{message}] [,{level}]) *debug.traceback()* + Returns a string with a traceback of the call stack. An optional + {message} string is appended at the beginning of the traceback. An + optional {level} number tells at which level to start the traceback + (default is 1, the function calling `traceback`). + +============================================================================== +A BIBLIOGRAPHY *luaref-bibliography* +============================================================================== + +This help file is a minor adaptation from this main reference: + + - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., + "Lua: 5.1 reference manual", http://www.lua.org/manual/5.1/manual.html + +Lua is discussed in these references: + + - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., + "Lua --- an extensible extension language". + "Software: Practice & Experience" 26, 6 (1996) 635-652. + + - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes., + "The design and implementation of a language for extending applications". + "Proc. of XXI Brazilian Seminar on Software and Hardware" (1994) 273-283. + + - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes., + "Lua: an extensible embedded language". + "Dr. Dobb's Journal" 21, 12 (Dec 1996) 26-33. + + - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., + "The evolution of an extension language: a history of Lua". + "Proc. of V Brazilian Symposium on Programming Languages" (2001) B-14-B-28. + +============================================================================== +B COPYRIGHT & LICENSES *luaref-copyright* +============================================================================== + +This help file has the same copyright and license as Lua 5.1 and the Lua 5.1 + manual: + +Copyright (c) 1994-2006 Lua.org, PUC-Rio. + +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. + +============================================================================== +C LUAREF DOC *luarefvim* *luarefvimdoc* *luaref-help* *luaref-doc* +============================================================================== + +This is a Vim help file containing a reference for Lua 5.1, and it is -- with +a few exceptions and adaptations -- a copy of the Lua 5.1 Reference Manual +(see |luaref-bibliography|). For usage information, refer to +|luaref-docUsage|. For copyright information, see |luaref-copyright|. + +The main ideas and concepts on how to implement this reference were taken from +Christian Habermann's CRefVim project +(http://www.vim.org/scripts/script.php?script_id=614). + +Adapted for bundled Nvim documentation; the original plugin can be found at +http://www.vim.org/scripts/script.php?script_id=1291 + +------------------------------------------------------------------------------ + vi:tw=78:ts=4:ft=help:norl:et diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index d6c3e25b3b..e1b4ed4ea9 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -526,7 +526,7 @@ function vim.trim(s) return s:match('^%s*(.*%S)') or '' end ---- Escapes magic chars in a Lua pattern. +--- Escapes magic chars in |lua-patterns|. --- ---@see https://github.com/rxi/lume ---@param s string String to escape -- cgit From a5e846b9969b1dfbd7e92f437f3ac7905039b84f Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 9 Aug 2022 10:43:28 +0200 Subject: vim-patch:partial: 48c3f4e0bff7 (#19684) vim-patch:partial:48c3f4e0bff7 Update runtime files https://github.com/vim/vim/commit/48c3f4e0bff7efd289a7001b68c777b6f89a7057 partially skip `options.txt` (needs 9.0.0138) --- runtime/autoload/dist/ft.vim | 11 +- runtime/autoload/python.vim | 71 ++++++----- runtime/doc/help.txt | 1 + runtime/doc/options.txt | 7 +- runtime/doc/usr_41.txt | 6 +- runtime/ftplugin/abaqus.vim | 48 +++---- runtime/ftplugin/php.vim | 151 ++++++++++++++++------ runtime/ftplugin/vim.vim | 4 +- runtime/indent/lisp.vim | 4 +- runtime/indent/systemverilog.vim | 176 ++++++++++++++++---------- runtime/indent/testdir/python.in | 68 ++++++++++ runtime/indent/testdir/python.ok | 68 ++++++++++ runtime/lua/vim/filetype/detect.lua | 15 ++- runtime/pack/dist/opt/matchit/doc/matchit.txt | 3 - runtime/syntax/abaqus.vim | 7 +- 15 files changed, 457 insertions(+), 183 deletions(-) create mode 100644 runtime/indent/testdir/python.in create mode 100644 runtime/indent/testdir/python.ok diff --git a/runtime/autoload/dist/ft.vim b/runtime/autoload/dist/ft.vim index a2f485dd67..77140d62b1 100644 --- a/runtime/autoload/dist/ft.vim +++ b/runtime/autoload/dist/ft.vim @@ -348,7 +348,7 @@ func dist#ft#FTidl() setf idl endfunc -" Distinguish between "default" and Cproto prototype file. */ +" Distinguish between "default", Prolog and Cproto prototype file. */ func dist#ft#ProtoCheck(default) " Cproto files have a comment in the first line and a function prototype in " the second line, it always ends in ";". Indent files may also have @@ -358,7 +358,14 @@ func dist#ft#ProtoCheck(default) if getline(2) =~ '.;$' setf cpp else - exe 'setf ' . a:default + " recognize Prolog by specific text in the first non-empty line + " require a blank after the '%' because Perl uses "%list" and "%translate" + let l = getline(nextnonblank(1)) + if l =~ '\' || l =~ '^\s*\(%\+\(\s\|$\)\|/\*\)' || l =~ ':-' + setf prolog + else + exe 'setf ' .. a:default + endif endif endfunc diff --git a/runtime/autoload/python.vim b/runtime/autoload/python.vim index 7e7bca6fb6..4b220708cf 100644 --- a/runtime/autoload/python.vim +++ b/runtime/autoload/python.vim @@ -3,13 +3,28 @@ let s:keepcpo= &cpo set cpo&vim +" searchpair() can be slow, limit the time to 150 msec or what is put in +" g:pyindent_searchpair_timeout +let s:searchpair_timeout = get(g:, 'pyindent_searchpair_timeout', 150) + +" Identing inside parentheses can be very slow, regardless of the searchpair() +" timeout, so let the user disable this feature if he doesn't need it +let s:disable_parentheses_indenting = get(g:, 'pyindent_disable_parentheses_indenting', v:false) + +let s:maxoff = 50 " maximum number of lines to look backwards for () + +function s:SearchBracket(fromlnum, flags) + return searchpairpos('[[({]', '', '[])}]', a:flags, + \ {-> synID('.', col('.'), v:true)->synIDattr('name') + \ =~ '\%(Comment\|Todo\|String\)$'}, + \ [0, a:fromlnum - s:maxoff]->max(), s:searchpair_timeout) +endfunction + " See if the specified line is already user-dedented from the expected value. function s:Dedented(lnum, expected) return indent(a:lnum) <= a:expected - shiftwidth() endfunction -let s:maxoff = 50 " maximum number of lines to look backwards for () - " Some other filetypes which embed Python have slightly different indent " rules (e.g. bitbake). Those filetypes can pass an extra funcref to this " function which is evaluated below. @@ -39,30 +54,30 @@ function python#GetIndent(lnum, ...) return 0 endif - call cursor(plnum, 1) - - " Identing inside parentheses can be very slow, regardless of the searchpair() - " timeout, so let the user disable this feature if he doesn't need it - let disable_parentheses_indenting = get(g:, "pyindent_disable_parentheses_indenting", 0) - - if disable_parentheses_indenting == 1 + if s:disable_parentheses_indenting == 1 let plindent = indent(plnum) let plnumstart = plnum else - " searchpair() can be slow sometimes, limit the time to 150 msec or what is - " put in g:pyindent_searchpair_timeout - let searchpair_stopline = 0 - let searchpair_timeout = get(g:, 'pyindent_searchpair_timeout', 150) + " Indent inside parens. + " Align with the open paren unless it is at the end of the line. + " E.g. + " open_paren_not_at_EOL(100, + " (200, + " 300), + " 400) + " open_paren_at_EOL( + " 100, 200, 300, 400) + call cursor(a:lnum, 1) + let [parlnum, parcol] = s:SearchBracket(a:lnum, 'nbW') + if parlnum > 0 && parcol != col([parlnum, '$']) - 1 + return parcol + endif + + call cursor(plnum, 1) " If the previous line is inside parenthesis, use the indent of the starting " line. - " Trick: use the non-existing "dummy" variable to break out of the loop when - " going too far back. - let parlnum = searchpair('(\|{\|\[', '', ')\|}\|\]', 'nbW', - \ "line('.') < " . (plnum - s:maxoff) . " ? dummy :" - \ . " synIDattr(synID(line('.'), col('.'), 1), 'name')" - \ . " =~ '\\(Comment\\|Todo\\|String\\)$'", - \ searchpair_stopline, searchpair_timeout) + let [parlnum, _] = s:SearchBracket(plnum, 'nbW') if parlnum > 0 if a:0 > 0 && ExtraFunc(parlnum) " We may have found the opening brace of a bitbake Python task, e.g. 'python do_task {' @@ -85,11 +100,7 @@ function python#GetIndent(lnum, ...) " + b " + c) call cursor(a:lnum, 1) - let p = searchpair('(\|{\|\[', '', ')\|}\|\]', 'bW', - \ "line('.') < " . (a:lnum - s:maxoff) . " ? dummy :" - \ . " synIDattr(synID(line('.'), col('.'), 1), 'name')" - \ . " =~ '\\(Comment\\|Todo\\|String\\)$'", - \ searchpair_stopline, searchpair_timeout) + let [p, _] = s:SearchBracket(a:lnum, 'bW') if p > 0 if a:0 > 0 && ExtraFunc(p) " Currently only used by bitbake @@ -109,11 +120,7 @@ function python#GetIndent(lnum, ...) else if p == plnum " When the start is inside parenthesis, only indent one 'shiftwidth'. - let pp = searchpair('(\|{\|\[', '', ')\|}\|\]', 'bW', - \ "line('.') < " . (a:lnum - s:maxoff) . " ? dummy :" - \ . " synIDattr(synID(line('.'), col('.'), 1), 'name')" - \ . " =~ '\\(Comment\\|Todo\\|String\\)$'", - \ searchpair_stopline, searchpair_timeout) + let [pp, _] = s:SearchBracket(a:lnum, 'bW') if pp > 0 return indent(plnum) + (exists("g:pyindent_nested_paren") ? eval(g:pyindent_nested_paren) : shiftwidth()) endif @@ -136,12 +143,12 @@ function python#GetIndent(lnum, ...) " If the last character in the line is a comment, do a binary search for " the start of the comment. synID() is slow, a linear search would take " too long on a long line. - if synIDattr(synID(plnum, pline_len, 1), "name") =~ "\\(Comment\\|Todo\\)$" + if synIDattr(synID(plnum, pline_len, 1), "name") =~ "\\(Comment\\|Todo\\)" let min = 1 let max = pline_len while min < max let col = (min + max) / 2 - if synIDattr(synID(plnum, col, 1), "name") =~ "\\(Comment\\|Todo\\)$" + if synIDattr(synID(plnum, col, 1), "name") =~ "\\(Comment\\|Todo\\)" let max = col else let min = col + 1 diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt index 2a7125a044..e9fd2888ac 100644 --- a/runtime/doc/help.txt +++ b/runtime/doc/help.txt @@ -25,6 +25,7 @@ Get specific help: It is possible to go directly to whatever you want help Option ' :help 'textwidth' Regular expression / :help /[ See |help-summary| for more contexts and an explanation. + See |notation| for an explanation of the help syntax. Search for help: Type ":help word", then hit CTRL-D to see matching help entries for "word". diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index f0977c91de..f8e60f0d0d 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -1325,7 +1325,8 @@ A jump table for the options with a short description can be found at |Q_op|. page can have a different value. When 'cmdheight' is zero, there is no command-line unless it is being - used. Any messages will cause the |hit-enter| prompt. + used. Some informative messages will not be displayed, any other + messages will cause the |hit-enter| prompt. *'cmdwinheight'* *'cwh'* 'cmdwinheight' 'cwh' number (default 7) @@ -3735,8 +3736,8 @@ A jump table for the options with a short description can be found at |Q_op|. *'lispwords'* *'lw'* 'lispwords' 'lw' string (default is very long) global or local to buffer |global-local| - Comma-separated list of words that influence the Lisp indenting. - |'lisp'| + Comma-separated list of words that influence the Lisp indenting when + enabled with the |'lisp'| option. *'list'* *'nolist'* 'list' boolean (default off) diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index bc2f7f077b..af5ef0ab2d 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -202,9 +202,9 @@ message when it doesn't, append !: > :unlet! s:count -When a script finishes, the local variables used there will not be -automatically freed. The next time the script executes, it can still use the -old value. Example: > +When a script has been processed to the end, the local variables declared +there will not be deleted. Functions defined in the script can use them. +Example: :if !exists("s:call_count") : let s:call_count = 0 diff --git a/runtime/ftplugin/abaqus.vim b/runtime/ftplugin/abaqus.vim index 5ce565ef3f..3faeff621a 100644 --- a/runtime/ftplugin/abaqus.vim +++ b/runtime/ftplugin/abaqus.vim @@ -1,7 +1,7 @@ " Vim filetype plugin file " Language: Abaqus finite element input file (www.abaqus.com) -" Maintainer: Carl Osterwisch -" Last Change: 2022 May 09 +" Maintainer: Carl Osterwisch +" Last Change: 2022 Aug 03 " Only do this when not done yet for this buffer if exists("b:did_ftplugin") | finish | endif @@ -46,7 +46,7 @@ if has("folding") endif " Set the file browse filter (currently only supported under Win32 gui) -if has("gui_win32") && !exists("b:browsefilter") +if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter") let b:browsefilter = "Abaqus Input Files (*.inp *.inc)\t*.inp;*.inc\n" . \ "Abaqus Results (*.dat)\t*.dat\n" . \ "Abaqus Messages (*.pre *.msg *.sta)\t*.pre;*.msg;*.sta\n" . @@ -57,7 +57,7 @@ endif " Define patterns for the matchit plugin if exists("loaded_matchit") && !exists("b:match_words") let b:match_ignorecase = 1 - let b:match_words = + let b:match_words = \ '\*part:\*end\s*part,' . \ '\*assembly:\*end\s*assembly,' . \ '\*instance:\*end\s*instance,' . @@ -65,25 +65,27 @@ if exists("loaded_matchit") && !exists("b:match_words") let b:undo_ftplugin .= "|unlet! b:match_ignorecase b:match_words" endif -" Define keys used to move [count] keywords backward or forward. -noremap [[ ?^\*\a:nohlsearch -noremap ]] /^\*\a:nohlsearch - -" Define key to toggle commenting of the current line or range -noremap - \ :call Abaqus_ToggleComment()j -function! Abaqus_ToggleComment() range - if strpart(getline(a:firstline), 0, 2) == "**" - " Un-comment all lines in range - silent execute a:firstline . ',' . a:lastline . 's/^\*\*//' - else - " Comment all lines in range - silent execute a:firstline . ',' . a:lastline . 's/^/**/' - endif -endfunction - -let b:undo_ftplugin .= "|unmap [[|unmap ]]" - \ . "|unmap " +if !exists("no_plugin_maps") && !exists("no_abaqus_maps") + " Define keys used to move [count] keywords backward or forward. + noremap [[ ?^\*\a:nohlsearch + noremap ]] /^\*\a:nohlsearch + + " Define key to toggle commenting of the current line or range + noremap + \ :call Abaqus_ToggleComment()j + function! Abaqus_ToggleComment() range + if strpart(getline(a:firstline), 0, 2) == "**" + " Un-comment all lines in range + silent execute a:firstline . ',' . a:lastline . 's/^\*\*//' + else + " Comment all lines in range + silent execute a:firstline . ',' . a:lastline . 's/^/**/' + endif + endfunction + + let b:undo_ftplugin .= "|unmap [[|unmap ]]" + \ . "|unmap " +endif " Undo must be done in nocompatible mode for . let b:undo_ftplugin = "let b:cpo_save = &cpoptions|" diff --git a/runtime/ftplugin/php.vim b/runtime/ftplugin/php.vim index 2824a5853b..540653e030 100644 --- a/runtime/ftplugin/php.vim +++ b/runtime/ftplugin/php.vim @@ -1,12 +1,12 @@ " Vim filetype plugin file -" Language: php -" -" This runtime file is looking for a new maintainer. -" -" Former maintainer: Dan Sharp -" Last Changed: 20 Jan 2009 +" Language: PHP +" Maintainer: Doug Kearns +" Previous Maintainer: Dan Sharp +" Last Changed: 2022 Jul 20 -if exists("b:did_ftplugin") | finish | endif +if exists("b:did_ftplugin") + finish +endif " Make sure the continuation lines below do not cause problems in " compatibility mode. @@ -15,8 +15,8 @@ set cpo&vim " Define some defaults in case the included ftplugins don't set them. let s:undo_ftplugin = "" -let s:browsefilter = "HTML Files (*.html, *.htm)\t*.html;*.htm\n" . - \ "All Files (*.*)\t*.*\n" +let s:browsefilter = "HTML Files (*.html, *.htm)\t*.html;*.htm\n" .. + \ "All Files (*.*)\t*.*\n" let s:match_words = "" runtime! ftplugin/html.vim ftplugin/html_*.vim ftplugin/html/*.vim @@ -24,63 +24,130 @@ let b:did_ftplugin = 1 " Override our defaults if these were set by an included ftplugin. if exists("b:undo_ftplugin") - let s:undo_ftplugin = b:undo_ftplugin +" let b:undo_ftplugin = "setlocal comments< commentstring< formatoptions< omnifunc<" + let s:undo_ftplugin = b:undo_ftplugin endif if exists("b:browsefilter") - let s:browsefilter = b:browsefilter +" let b:undo_ftplugin ..= " | unlet! b:browsefilter b:html_set_browsefilter" + let s:browsefilter = b:browsefilter endif if exists("b:match_words") - let s:match_words = b:match_words +" let b:undo_ftplugin ..= " | unlet! b:match_ignorecase b:match_words b:html_set_match_words" + let s:match_words = b:match_words endif if exists("b:match_skip") - unlet b:match_skip + unlet b:match_skip endif -" Change the :browse e filter to primarily show PHP-related files. -if has("gui_win32") - let b:browsefilter="PHP Files (*.php)\t*.php\n" . s:browsefilter +setlocal comments=s1:/*,mb:*,ex:*/,://,:# +setlocal commentstring=/*%s*/ +setlocal formatoptions+=l formatoptions-=t + +if get(g:, "php_autocomment", 1) + setlocal formatoptions+=croq + " NOTE: set g:PHP_autoformatcomment = 0 to prevent the indent plugin from + " overriding this 'comments' value + setlocal comments-=:# + " space after # comments to exclude attributes + setlocal comments+=b:# endif +if exists('&omnifunc') + setlocal omnifunc=phpcomplete#CompletePHP +endif + +setlocal suffixesadd=.php + " ### " Provided by Mikolaj Machowski setlocal include=\\\(require\\\|include\\\)\\\(_once\\\)\\\? " Disabled changing 'iskeyword', it breaks a command such as "*" " setlocal iskeyword+=$ -if exists("loaded_matchit") - let b:match_words = ',\:\,' . - \ '\:\:\:\,' . - \ '\:\,' . - \ '\:\,' . - \ '\:\,' . - \ '\:\,' . - \ '(:),[:],{:},' . - \ s:match_words +let b:undo_ftplugin = "setlocal include< suffixesadd<" + +if exists("loaded_matchit") && exists("b:html_set_match_words") + let b:match_ignorecase = 1 + let b:match_words = 'PhpMatchWords()' + + if !exists("*PhpMatchWords") + function! PhpMatchWords() + " The PHP syntax file uses the Delimiter syntax group for the phpRegion + " matchgroups, without a "php" prefix, so use the stack to test for the + " outer phpRegion group. This also means the closing ?> tag which is + " outside of the matched region just uses the Delimiter group for the + " end match. + let stack = synstack(line('.'), col('.')) + let php_region = !empty(stack) && synIDattr(stack[0], "name") =~# '\' + let b:match_skip = "PhpMatchSkip('html')" + return ',' .. + \ '\:\:\:\,' .. + \ '\:\:\:\:\,' .. + \ '\.\{-})\s*\::\:\:\,' .. + \ '\:\:\:\,' .. + \ '\:\:\:\,' .. + \ '\:\:\:\,' .. + \ '\%(<<<\s*\)\@<=''\=\(\h\w*\)''\=:^\s*\1\>' + + " TODO: these probably aren't worth adding and really need syntax support + " '<\_s*script\_s*language\_s*=\_s*[''"]\=\_s*php\_s*[''"]\=\_s*>:<\_s*\_s*/\_s*script\_s*>,' .. + " '<%:%>,' .. + else + let b:match_skip = "PhpMatchSkip('php')" + return s:match_words + endif + endfunction + endif + if !exists("*PhpMatchSkip") + function! PhpMatchSkip(skip) + let name = synIDattr(synID(line('.'), col('.'), 1), 'name') + if a:skip == "html" + " ?> in line comments will also be correctly matched as Delimiter + return name =~? 'comment\|string' || name !~? 'php\|delimiter' + else " php + return name =~? 'comment\|string\|php' + endif + endfunction + endif + let b:undo_ftplugin ..= " | unlet! b:match_skip" endif " ### -if exists('&omnifunc') - setlocal omnifunc=phpcomplete#CompletePHP +" Change the :browse e filter to primarily show PHP-related files. +if (has("gui_win32") || has("gui_gtk")) && exists("b:html_set_browsefilter") + let b:browsefilter = "PHP Files (*.php)\t*.php\n" .. + \ "PHP Test Files (*.phpt)\t*.phpt\n" .. + \ s:browsefilter endif -" Section jumping: [[ and ]] provided by Antony Scriven -let s:function = '\(abstract\s\+\|final\s\+\|private\s\+\|protected\s\+\|public\s\+\|static\s\+\)*function' -let s:class = '\(abstract\s\+\|final\s\+\)*class' -let s:interface = 'interface' -let s:section = '\(.*\%#\)\@!\_^\s*\zs\('.s:function.'\|'.s:class.'\|'.s:interface.'\)' -exe 'nno [[ ?' . escape(s:section, '|') . '?:nohls' -exe 'nno ]] /' . escape(s:section, '|') . '/:nohls' -exe 'ono [[ ?' . escape(s:section, '|') . '?:nohls' -exe 'ono ]] /' . escape(s:section, '|') . '/:nohls' +if !exists("no_plugin_maps") && !exists("no_php_maps") + " Section jumping: [[ and ]] provided by Antony Scriven + let s:function = '\%(abstract\s\+\|final\s\+\|private\s\+\|protected\s\+\|public\s\+\|static\s\+\)*function' + let s:class = '\%(abstract\s\+\|final\s\+\)*class' + let s:section = escape('^\s*\zs\%(' .. s:function .. '\|' .. s:class .. '\|interface\|trait\|enum\)\>', "|") -setlocal suffixesadd=.php -setlocal commentstring=/*%s*/ + function! s:Jump(pattern, count, flags) + normal! m' + for i in range(a:count) + if !search(a:pattern, a:flags) + break + endif + endfor + endfunction -" Undo the stuff we changed. -let b:undo_ftplugin = "setlocal suffixesadd< commentstring< include< omnifunc<" . - \ " | unlet! b:browsefilter b:match_words | " . - \ s:undo_ftplugin + for mode in ["n", "o", "x"] + exe mode .. "noremap ]] call Jump('" .. s:section .. "', v:count1, 'W')" + exe mode .. "noremap [[ call Jump('" .. s:section .. "', v:count1, 'bW')" + let b:undo_ftplugin ..= " | sil! exe '" .. mode .. "unmap ]]'" .. + \ " | sil! exe '" .. mode .. "unmap [['" + endfor +endif + +let b:undo_ftplugin ..= " | " .. s:undo_ftplugin " Restore the saved compatibility options. let &cpo = s:keepcpo unlet s:keepcpo + +" vim: nowrap sw=2 sts=2 ts=8 noet: diff --git a/runtime/ftplugin/vim.vim b/runtime/ftplugin/vim.vim index 64b64b45e3..772899cb42 100644 --- a/runtime/ftplugin/vim.vim +++ b/runtime/ftplugin/vim.vim @@ -1,7 +1,7 @@ " Vim filetype plugin " Language: Vim " Maintainer: Bram Moolenaar -" Last Change: 2021 Apr 11 +" Last Change: 2022 Aug 4 " Only do this when not done yet for this buffer if exists("b:did_ftplugin") @@ -109,7 +109,7 @@ if exists("loaded_matchit") " - set spl=de,en " - au! FileType javascript syntax region foldBraces start=/{/ end=/}/ … let b:match_skip = 'synIDattr(synID(line("."),col("."),1),"name") - \ =~? "comment\\|string\\|vimSynReg\\|vimSet"' + \ =~? "comment\\|string\\|vimLetHereDoc\\|vimSynReg\\|vimSet"' endif let &cpo = s:cpo_save diff --git a/runtime/indent/lisp.vim b/runtime/indent/lisp.vim index b0c4eed1bd..1bce39510c 100644 --- a/runtime/indent/lisp.vim +++ b/runtime/indent/lisp.vim @@ -1,7 +1,7 @@ " Vim indent file " Language: Lisp -" Maintainer: Sergey Khorev -" URL: http://sites.google.com/site/khorser/opensource/vim +" Maintainer: Sergey Khorev +" URL: http://sites.google.com/site/khorser/opensource/vim " Last Change: 2012 Jan 10 " Only load this indent file when no other was loaded. diff --git a/runtime/indent/systemverilog.vim b/runtime/indent/systemverilog.vim index f6114dc1fd..a5f4d5b90d 100644 --- a/runtime/indent/systemverilog.vim +++ b/runtime/indent/systemverilog.vim @@ -2,7 +2,7 @@ " Language: SystemVerilog " Maintainer: kocha " Last Change: 05-Feb-2017 by Bilal Wasim -" 2022 April: b:undo_indent added by Doug Kearns +" 03-Aug-2022 Improved indent " Only load this indent file when no other was loaded. if exists("b:did_indent") @@ -15,7 +15,7 @@ setlocal indentkeys=!^F,o,O,0),0},=begin,=end,=join,=endcase,=join_any,=join_non setlocal indentkeys+==endmodule,=endfunction,=endtask,=endspecify setlocal indentkeys+==endclass,=endpackage,=endsequence,=endclocking setlocal indentkeys+==endinterface,=endgroup,=endprogram,=endproperty,=endchecker -setlocal indentkeys+==`else,=`endif +setlocal indentkeys+==`else,=`elsif,=`endif let b:undo_indent = "setl inde< indk<" @@ -27,6 +27,9 @@ endif let s:cpo_save = &cpo set cpo&vim +let s:multiple_comment = 0 +let s:open_statement = 0 + function SystemVerilogIndent() if exists('b:systemverilog_indent_width') @@ -40,6 +43,12 @@ function SystemVerilogIndent() let indent_modules = 0 endif + if exists('b:systemverilog_indent_ifdef_off') + let indent_ifdef = 0 + else + let indent_ifdef = 1 + endif + " Find a non-blank line above the current line. let lnum = prevnonblank(v:lnum - 1) @@ -54,48 +63,55 @@ function SystemVerilogIndent() let last_line2 = getline(lnum2) let ind = indent(lnum) let ind2 = indent(lnum - 1) - let offset_comment1 = 1 " Define the condition of an open statement " Exclude the match of //, /* or */ let sv_openstat = '\(\\|\([*/]\)\@<+-/%^&|!=?:]\([*/]\)\@!\)' " Define the condition when the statement ends with a one-line comment let sv_comment = '\(//.*\|/\*.*\*/\s*\)' - if exists('b:verilog_indent_verbose') - let vverb_str = 'INDENT VERBOSE:' + if exists('b:systemverilog_indent_verbose') + let vverb_str = 'INDENT VERBOSE: '. v:lnum .":" let vverb = 1 else let vverb = 0 endif - " Indent according to last line - " End of multiple-line comment - if last_line =~ '\*/\s*$' && last_line !~ '/\*.\{-}\*/' - let ind = ind - offset_comment1 - if vverb - echo vverb_str "De-indent after a multiple-line comment." - endif + " Multiple-line comment count + if curr_line =~ '^\s*/\*' && curr_line !~ '/\*.\{-}\*/' + let s:multiple_comment += 1 + if vverb | echom vverb_str "Start of multiple-line commnt" | endif + elseif curr_line =~ '\*/\s*$' && curr_line !~ '/\*.\{-}\*/' + let s:multiple_comment -= 1 + if vverb | echom vverb_str "End of multiple-line commnt" | endif + return ind + endif + " Maintain indentation during commenting. + if s:multiple_comment > 0 + return ind + endif " Indent after if/else/for/case/always/initial/specify/fork blocks - elseif last_line =~ '`\@' || - \ last_line =~ '^\s*\<\(for\|case\%[[zx]]\|do\|foreach\|forever\|randcase\)\>' || + if last_line =~ '^\s*\(end\)\=\s*`\@' || + \ last_line =~ '^\s*\<\(for\|while\|repeat\|case\%[[zx]]\|do\|foreach\|forever\|randcase\)\>' || \ last_line =~ '^\s*\<\(always\|always_comb\|always_ff\|always_latch\)\>' || \ last_line =~ '^\s*\<\(initial\|specify\|fork\|final\)\>' - if last_line !~ '\(;\|\\)\s*' . sv_comment . '*$' || + if last_line !~ '\(;\|\\|\*/\)\s*' . sv_comment . '*$' || \ last_line =~ '\(//\|/\*\).*\(;\|\\)\s*' . sv_comment . '*$' let ind = ind + offset - if vverb | echo vverb_str "Indent after a block statement." | endif + if vverb | echom vverb_str "Indent after a block statement." | endif endif " Indent after function/task/class/package/sequence/clocking/ " interface/covergroup/property/checkerprogram blocks elseif last_line =~ '^\s*\<\(function\|task\|class\|package\)\>' || \ last_line =~ '^\s*\<\(sequence\|clocking\|interface\)\>' || \ last_line =~ '^\s*\(\w\+\s*:\)\=\s*\' || - \ last_line =~ '^\s*\<\(property\|checker\|program\)\>' + \ last_line =~ '^\s*\<\(property\|checker\|program\)\>' || + \ ( last_line =~ '^\s*\' && last_line =~ '\<\(function\|task\|class\|interface\)\>' ) || + \ ( last_line =~ '^\s*\' && last_line =~ '\' && last_line =~ '\<\(function\|task\)\>' ) if last_line !~ '\\s*' . sv_comment . '*$' || \ last_line =~ '\(//\|/\*\).*\(;\|\\)\s*' . sv_comment . '*$' let ind = ind + offset if vverb - echo vverb_str "Indent after function/task/class block statement." + echom vverb_str "Indent after function/task/class block statement." endif endif @@ -103,13 +119,13 @@ function SystemVerilogIndent() elseif last_line =~ '^\s*\(\\s*\)\=\' let ind = ind + indent_modules if vverb && indent_modules - echo vverb_str "Indent after module statement." + echom vverb_str "Indent after module statement." endif if last_line =~ '[(,]\s*' . sv_comment . '*$' && \ last_line !~ '\(//\|/\*\).*[(,]\s*' . sv_comment . '*$' let ind = ind + offset if vverb - echo vverb_str "Indent after a multiple-line module statement." + echom vverb_str "Indent after a multiple-line module statement." endif endif @@ -119,7 +135,7 @@ function SystemVerilogIndent() \ ( last_line2 !~ sv_openstat . '\s*' . sv_comment . '*$' || \ last_line2 =~ '^\s*[^=!]\+\s*:\s*' . sv_comment . '*$' ) let ind = ind + offset - if vverb | echo vverb_str "Indent after begin statement." | endif + if vverb | echom vverb_str "Indent after begin statement." | endif " Indent after a '{' or a '(' elseif last_line =~ '[{(]' . sv_comment . '*$' && @@ -127,7 +143,21 @@ function SystemVerilogIndent() \ ( last_line2 !~ sv_openstat . '\s*' . sv_comment . '*$' || \ last_line2 =~ '^\s*[^=!]\+\s*:\s*' . sv_comment . '*$' ) let ind = ind + offset - if vverb | echo vverb_str "Indent after begin statement." | endif + if vverb | echom vverb_str "Indent after begin statement." | endif + + " Ignore de-indent for the end of one-line block + elseif ( last_line !~ '\' || + \ last_line =~ '\(//\|/\*\).*\' ) && + \ last_line2 =~ '\<\(`\@.*' . + \ sv_comment . '*$' && + \ last_line2 !~ '\(//\|/\*\).*\<\(`\@' && + \ last_line2 !~ sv_openstat . '\s*' . sv_comment . '*$' && + \ ( last_line2 !~ '\' || + \ last_line2 =~ '\(//\|/\*\).*\' ) && + \ last_line2 =~ ')*\s*;\s*' . sv_comment . '*$' + if vverb + echom vverb_str "Ignore de-indent after the end of one-line statement." + endif " De-indent for the end of one-line block elseif ( last_line !~ '\' || @@ -136,39 +166,29 @@ function SystemVerilogIndent() \ sv_comment . '*$' && \ last_line2 !~ '\(//\|/\*\).*\<\(`\@' && \ last_line2 !~ sv_openstat . '\s*' . sv_comment . '*$' && + \ last_line2 !~ '\(;\|\\|\*/\)\s*' . sv_comment . '*$' && \ ( last_line2 !~ '\' || \ last_line2 =~ '\(//\|/\*\).*\' ) let ind = ind - offset if vverb - echo vverb_str "De-indent after the end of one-line statement." + echom vverb_str "De-indent after the end of one-line statement." endif - " Multiple-line statement (including case statement) - " Open statement - " Ident the first open line - elseif last_line =~ sv_openstat . '\s*' . sv_comment . '*$' && - \ last_line !~ '\(//\|/\*\).*' . sv_openstat . '\s*$' && - \ last_line2 !~ sv_openstat . '\s*' . sv_comment . '*$' - let ind = ind + offset - if vverb | echo vverb_str "Indent after an open statement." | endif - - " Close statement - " De-indent for an optional close parenthesis and a semicolon, and only - " if there exists precedent non-whitespace char - elseif last_line =~ ')*\s*;\s*' . sv_comment . '*$' && - \ last_line !~ '^\s*)*\s*;\s*' . sv_comment . '*$' && - \ last_line !~ '\(//\|/\*\).*\S)*\s*;\s*' . sv_comment . '*$' && - \ ( last_line2 =~ sv_openstat . '\s*' . sv_comment . '*$' && - \ last_line2 !~ ';\s*//.*$') && - \ last_line2 !~ '^\s*' . sv_comment . '$' - let ind = ind - offset - if vverb | echo vverb_str "De-indent after a close statement." | endif + " Multiple-line statement (including case statement) + " Open statement + " Ident the first open line + elseif last_line =~ sv_openstat . '\s*' . sv_comment . '*$' && + \ last_line !~ '\(//\|/\*\).*' . sv_openstat . '\s*$' && + \ last_line2 !~ sv_openstat . '\s*' . sv_comment . '*$' + let ind = ind + offset + let s:open_statement = 1 + if vverb | echom vverb_str "Indent after an open statement." | endif - " `ifdef and `else - elseif last_line =~ '^\s*`\<\(ifdef\|else\)\>' + " `ifdef or `ifndef or `elsif or `else + elseif last_line =~ '^\s*`\<\(ifn\?def\|elsif\|else\)\>' && indent_ifdef let ind = ind + offset if vverb - echo vverb_str "Indent after a `ifdef or `else statement." + echom vverb_str "Indent after a `ifdef or `ifndef or `elsif or `else statement." endif endif @@ -177,17 +197,21 @@ function SystemVerilogIndent() " De-indent on the end of the block " join/end/endcase/endfunction/endtask/endspecify - if curr_line =~ '^\s*\<\(join\|join_any\|join_none\|\|end\|endcase\|while\)\>' || + if curr_line =~ '^\s*\<\(join\|join_any\|join_none\|\|end\|endcase\)\>' || \ curr_line =~ '^\s*\<\(endfunction\|endtask\|endspecify\|endclass\)\>' || \ curr_line =~ '^\s*\<\(endpackage\|endsequence\|endclocking\|endinterface\)\>' || - \ curr_line =~ '^\s*\<\(endgroup\|endproperty\|endchecker\|endprogram\)\>' || - \ curr_line =~ '^\s*}' + \ curr_line =~ '^\s*\<\(endgroup\|endproperty\|endchecker\|endprogram\)\>' let ind = ind - offset - if vverb | echo vverb_str "De-indent the end of a block." | endif + if vverb | echom vverb_str "De-indent the end of a block." | endif + if s:open_statement == 1 + let ind = ind - offset + let s:open_statement = 0 + if vverb | echom vverb_str "De-indent the close statement." | endif + endif elseif curr_line =~ '^\s*\' let ind = ind - indent_modules if vverb && indent_modules - echo vverb_str "De-indent the end of a module." + echom vverb_str "De-indent the end of a module." endif " De-indent on a stand-alone 'begin' @@ -202,25 +226,46 @@ function SystemVerilogIndent() \ last_line =~ sv_openstat . '\s*' . sv_comment . '*$' ) let ind = ind - offset if vverb - echo vverb_str "De-indent a stand alone begin statement." + echom vverb_str "De-indent a stand alone begin statement." + endif + if s:open_statement == 1 + let ind = ind - offset + let s:open_statement = 0 + if vverb | echom vverb_str "De-indent the close statement." | endif endif endif - " De-indent after the end of multiple-line statement - elseif curr_line =~ '^\s*)' && - \ ( last_line =~ sv_openstat . '\s*' . sv_comment . '*$' || - \ last_line !~ sv_openstat . '\s*' . sv_comment . '*$' && - \ last_line2 =~ sv_openstat . '\s*' . sv_comment . '*$' ) - let ind = ind - offset - if vverb - echo vverb_str "De-indent the end of a multiple statement." - endif + " " Close statement + " " De-indent for an optional close parenthesis and a semicolon, and only + " " if there exists precedent non-whitespace char + " elseif last_line =~ ')*\s*;\s*' . sv_comment . '*$' && + " \ last_line !~ '^\s*)*\s*;\s*' . sv_comment . '*$' && + " \ last_line !~ '\(//\|/\*\).*\S)*\s*;\s*' . sv_comment . '*$' && + " \ ( last_line2 =~ sv_openstat . '\s*' . sv_comment . '*$' && + " \ last_line2 !~ ';\s*//.*$') && + " \ last_line2 !~ '^\s*' . sv_comment . '$' + " let ind = ind - offset + " if vverb | echom vverb_str "De-indent after a close statement." | endif - " De-indent `else and `endif - elseif curr_line =~ '^\s*`\<\(else\|endif\)\>' - let ind = ind - offset - if vverb | echo vverb_str "De-indent `else and `endif statement." | endif + " " De-indent after the end of multiple-line statement + " elseif curr_line =~ '^\s*)' && + " \ ( last_line =~ sv_openstat . '\s*' . sv_comment . '*$' || + " \ last_line !~ sv_openstat . '\s*' . sv_comment . '*$' && + " \ last_line2 =~ sv_openstat . '\s*' . sv_comment . '*$' ) + " let ind = ind - offset + " if vverb + " echom vverb_str "De-indent the end of a multiple statement." + " endif + " De-indent `elsif or `else or `endif + elseif curr_line =~ '^\s*`\<\(elsif\|else\|endif\)\>' && indent_ifdef + let ind = ind - offset + if vverb | echom vverb_str "De-indent `elsif or `else or `endif statement." | endif + if b:systemverilog_open_statement == 1 + let ind = ind - offset + let b:systemverilog_open_statement = 0 + if vverb | echom vverb_str "De-indent the open statement." | endif + endif endif " Return the indentation @@ -231,3 +276,4 @@ let &cpo = s:cpo_save unlet s:cpo_save " vim:sw=2 + diff --git a/runtime/indent/testdir/python.in b/runtime/indent/testdir/python.in new file mode 100644 index 0000000000..868a63622b --- /dev/null +++ b/runtime/indent/testdir/python.in @@ -0,0 +1,68 @@ +" vim: set ft=python sw=4 et: + +" START_INDENT +open_paren_not_at_EOL(100, +(200, +300), +400) + +open_paren_at_EOL( +100, 200, 300, 400) + +open_paren_not_at_EOL(100, +(200, +300), +400) + +open_paren_at_EOL( +100, 200, 300, 400) + +open_paren_not_at_EOL(100, +(200, +300), +400) + +open_paren_at_EOL( +100, 200, 300, 400) + +open_paren_not_at_EOL(100, +(200, +300), +400) + +open_paren_at_EOL( +100, 200, 300, 400) + +open_paren_not_at_EOL(100, +(200, +300), +400) + +open_paren_at_EOL( +100, 200, 300, 400) + +open_paren_not_at_EOL(100, +(200, +300), +400) + +open_paren_at_EOL( +100, 200, 300, 400) + +open_paren_not_at_EOL(100, +(200, +300), +400) + +open_paren_at_EOL( +100, 200, 300, 400) + +open_paren_not_at_EOL(100, +(200, +300), +400) + +open_paren_at_EOL( +100, 200, 300, 400) + +" END_INDENT diff --git a/runtime/indent/testdir/python.ok b/runtime/indent/testdir/python.ok new file mode 100644 index 0000000000..c0c08af4b9 --- /dev/null +++ b/runtime/indent/testdir/python.ok @@ -0,0 +1,68 @@ +" vim: set ft=python sw=4 et: + +" START_INDENT +open_paren_not_at_EOL(100, + (200, + 300), + 400) + +open_paren_at_EOL( + 100, 200, 300, 400) + +open_paren_not_at_EOL(100, + (200, + 300), + 400) + +open_paren_at_EOL( + 100, 200, 300, 400) + +open_paren_not_at_EOL(100, + (200, + 300), + 400) + +open_paren_at_EOL( + 100, 200, 300, 400) + +open_paren_not_at_EOL(100, + (200, + 300), + 400) + +open_paren_at_EOL( + 100, 200, 300, 400) + +open_paren_not_at_EOL(100, + (200, + 300), + 400) + +open_paren_at_EOL( + 100, 200, 300, 400) + +open_paren_not_at_EOL(100, + (200, + 300), + 400) + +open_paren_at_EOL( + 100, 200, 300, 400) + +open_paren_not_at_EOL(100, + (200, + 300), + 400) + +open_paren_at_EOL( + 100, 200, 300, 400) + +open_paren_not_at_EOL(100, + (200, + 300), + 400) + +open_paren_at_EOL( + 100, 200, 300, 400) + +" END_INDENT diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index 14f076717f..2be9dcff88 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -930,7 +930,7 @@ function M.progress_pascal(bufnr) return 'progress' end --- Distinguish between "default" and Cproto prototype file. +-- Distinguish between "default", Prolog and Cproto prototype file. function M.proto(bufnr, default) -- Cproto files have a comment in the first line and a function prototype in -- the second line, it always ends in ";". Indent files may also have @@ -940,7 +940,18 @@ function M.proto(bufnr, default) if getlines(bufnr, 2):find('.;$') then return 'cpp' else - return default + -- Recognize Prolog by specific text in the first non-empty line; + -- require a blank after the '%' because Perl uses "%list" and "%translate" + local line = nextnonblank(bufnr, 1) + if + line and line:find(':%-') + or matchregex(line, [[\c\]]) + or findany(line, { '^%s*%%+%s', '^%s*%%+$', '^%s*/%*' }) + then + return 'prolog' + else + return default + end end end diff --git a/runtime/pack/dist/opt/matchit/doc/matchit.txt b/runtime/pack/dist/opt/matchit/doc/matchit.txt index 553359ffaf..45033ce3f1 100644 --- a/runtime/pack/dist/opt/matchit/doc/matchit.txt +++ b/runtime/pack/dist/opt/matchit/doc/matchit.txt @@ -243,9 +243,6 @@ Examples: comment character) you can > :let b:match_skip = 'r:\(^\|[^\\]\)\(\\\\\)*%' < - See the $VIMRUNTIME/ftplugin/vim.vim for an example that uses both - syntax and a regular expression. - ============================================================================== 4. Supporting a New Language *matchit-newlang* *b:match_words* diff --git a/runtime/syntax/abaqus.vim b/runtime/syntax/abaqus.vim index db2717f818..e6f025d8f4 100644 --- a/runtime/syntax/abaqus.vim +++ b/runtime/syntax/abaqus.vim @@ -1,6 +1,6 @@ " Vim syntax file " Language: Abaqus finite element input file (www.hks.com) -" Maintainer: Carl Osterwisch +" Maintainer: Carl Osterwisch " Last Change: 2002 Feb 24 " Remark: Huge improvement in folding performance--see filetype plugin @@ -28,8 +28,7 @@ syn match abaqusBadLine "^\s\+\*.*" display hi def link abaqusComment Comment hi def link abaqusKeyword Statement hi def link abaqusParameter Identifier -hi def link abaqusValue Constant -hi def link abaqusBadLine Error - +hi def link abaqusValue Constant +hi def link abaqusBadLine Error let b:current_syntax = "abaqus" -- cgit From cd14efd281c260c92936f05bf5f91780f8912f81 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Tue, 9 Aug 2022 17:13:44 +0800 Subject: vim-patch:8.1.1823: command line history code is spread out (#19688) Problem: Command line history code is spread out. Solution: Put the code in a new file. (Yegappan Lakshmanan, closes vim/vim#4779) Also graduate the +cmdline_hist feature. https://github.com/vim/vim/commit/d7663c22c6c1ff0f86b81371586fbc851d3a3e9e --- src/nvim/cmdhist.c | 743 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/nvim/cmdhist.h | 33 +++ src/nvim/eval.c | 1 + src/nvim/eval/funcs.c | 82 +----- src/nvim/ex_cmds.c | 2 + src/nvim/ex_docmd.c | 4 +- src/nvim/ex_getln.c | 709 ++--------------------------------------------- src/nvim/ex_getln.h | 24 -- src/nvim/memory.c | 1 + src/nvim/normal.c | 3 + src/nvim/search.c | 1 + src/nvim/shada.c | 24 +- 12 files changed, 835 insertions(+), 792 deletions(-) create mode 100644 src/nvim/cmdhist.c create mode 100644 src/nvim/cmdhist.h diff --git a/src/nvim/cmdhist.c b/src/nvim/cmdhist.c new file mode 100644 index 0000000000..625bd514ad --- /dev/null +++ b/src/nvim/cmdhist.c @@ -0,0 +1,743 @@ +// This is an open source non-commercial project. Dear PVS-Studio, please check +// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + +// cmdhist.c: Functions for the history of the command-line. + +#include "nvim/ascii.h" +#include "nvim/charset.h" +#include "nvim/cmdhist.h" +#include "nvim/ex_getln.h" +#include "nvim/regexp.h" +#include "nvim/strings.h" +#include "nvim/ui.h" +#include "nvim/vim.h" + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "cmdhist.c.generated.h" +#endif + +static histentry_T *(history[HIST_COUNT]) = { NULL, NULL, NULL, NULL, NULL }; +static int hisidx[HIST_COUNT] = { -1, -1, -1, -1, -1 }; ///< lastused entry +/// identifying (unique) number of newest history entry +static int hisnum[HIST_COUNT] = { 0, 0, 0, 0, 0 }; +static int hislen = 0; ///< actual length of history tables + +/// Return the length of the history tables +int get_hislen(void) +{ + return hislen; +} + +/// Return a pointer to a specified history table +histentry_T *get_histentry(int hist_type) +{ + return history[hist_type]; +} + +void set_histentry(int hist_type, histentry_T *entry) +{ + history[hist_type] = entry; +} + +int *get_hisidx(int hist_type) +{ + return &hisidx[hist_type]; +} + +int *get_hisnum(int hist_type) +{ + return &hisnum[hist_type]; +} + +/// Translate a history character to the associated type number +HistoryType hist_char2type(const int c) + FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT +{ + switch (c) { + case ':': + return HIST_CMD; + case '=': + return HIST_EXPR; + case '@': + return HIST_INPUT; + case '>': + return HIST_DEBUG; + case NUL: + case '/': + case '?': + return HIST_SEARCH; + default: + return HIST_INVALID; + } + // Silence -Wreturn-type + return 0; +} + +/// Table of history names. +/// These names are used in :history and various hist...() functions. +/// It is sufficient to give the significant prefix of a history name. +static char *(history_names[]) = { + "cmd", + "search", + "expr", + "input", + "debug", + NULL +}; + +/// Function given to ExpandGeneric() to obtain the possible first +/// arguments of the ":history command. +char *get_history_arg(expand_T *xp, int idx) +{ + static char_u compl[2] = { NUL, NUL }; + char *short_names = ":=@>?/"; + int short_names_count = (int)STRLEN(short_names); + int history_name_count = ARRAY_SIZE(history_names) - 1; + + if (idx < short_names_count) { + compl[0] = (char_u)short_names[idx]; + return (char *)compl; + } + if (idx < short_names_count + history_name_count) { + return history_names[idx - short_names_count]; + } + if (idx == short_names_count + history_name_count) { + return "all"; + } + return NULL; +} + +/// Initialize command line history. +/// Also used to re-allocate history tables when size changes. +void init_history(void) +{ + assert(p_hi >= 0 && p_hi <= INT_MAX); + int newlen = (int)p_hi; + int oldlen = hislen; + + // If history tables size changed, reallocate them. + // Tables are circular arrays (current position marked by hisidx[type]). + // On copying them to the new arrays, we take the chance to reorder them. + if (newlen != oldlen) { + for (int type = 0; type < HIST_COUNT; type++) { + histentry_T *temp = (newlen + ? xmalloc((size_t)newlen * sizeof(*temp)) + : NULL); + + int j = hisidx[type]; + if (j >= 0) { + // old array gets partitioned this way: + // [0 , i1 ) --> newest entries to be deleted + // [i1 , i1 + l1) --> newest entries to be copied + // [i1 + l1 , i2 ) --> oldest entries to be deleted + // [i2 , i2 + l2) --> oldest entries to be copied + int l1 = MIN(j + 1, newlen); // how many newest to copy + int l2 = MIN(newlen, oldlen) - l1; // how many oldest to copy + int i1 = j + 1 - l1; // copy newest from here + int i2 = MAX(l1, oldlen - newlen + l1); // copy oldest from here + + // copy as much entries as they fit to new table, reordering them + if (newlen) { + // copy oldest entries + memcpy(&temp[0], &history[type][i2], (size_t)l2 * sizeof(*temp)); + // copy newest entries + memcpy(&temp[l2], &history[type][i1], (size_t)l1 * sizeof(*temp)); + } + + // delete entries that don't fit in newlen, if any + for (int i = 0; i < i1; i++) { + hist_free_entry(history[type] + i); + } + for (int i = i1 + l1; i < i2; i++) { + hist_free_entry(history[type] + i); + } + } + + // clear remaining space, if any + int l3 = j < 0 ? 0 : MIN(newlen, oldlen); // number of copied entries + if (newlen) { + memset(temp + l3, 0, (size_t)(newlen - l3) * sizeof(*temp)); + } + + hisidx[type] = l3 - 1; + xfree(history[type]); + history[type] = temp; + } + hislen = newlen; + } +} + +static inline void hist_free_entry(histentry_T *hisptr) + FUNC_ATTR_NONNULL_ALL +{ + xfree(hisptr->hisstr); + tv_list_unref(hisptr->additional_elements); + clear_hist_entry(hisptr); +} + +static inline void clear_hist_entry(histentry_T *hisptr) + FUNC_ATTR_NONNULL_ALL +{ + memset(hisptr, 0, sizeof(*hisptr)); +} + +/// Check if command line 'str' is already in history. +/// If 'move_to_front' is true, matching entry is moved to end of history. +/// +/// @param move_to_front Move the entry to the front if it exists +static int in_history(int type, char_u *str, int move_to_front, int sep) +{ + int last_i = -1; + + if (hisidx[type] < 0) { + return false; + } + int i = hisidx[type]; + do { + if (history[type][i].hisstr == NULL) { + return false; + } + + // For search history, check that the separator character matches as + // well. + char_u *p = history[type][i].hisstr; + if (STRCMP(str, p) == 0 + && (type != HIST_SEARCH || sep == p[STRLEN(p) + 1])) { + if (!move_to_front) { + return true; + } + last_i = i; + break; + } + if (--i < 0) { + i = hislen - 1; + } + } while (i != hisidx[type]); + + if (last_i >= 0) { + list_T *const list = history[type][i].additional_elements; + str = history[type][i].hisstr; + while (i != hisidx[type]) { + if (++i >= hislen) { + i = 0; + } + history[type][last_i] = history[type][i]; + last_i = i; + } + tv_list_unref(list); + history[type][i].hisnum = ++hisnum[type]; + history[type][i].hisstr = str; + history[type][i].timestamp = os_time(); + history[type][i].additional_elements = NULL; + return true; + } + return false; +} + +/// Convert history name to its HIST_ equivalent +/// +/// Names are taken from the table above. When `name` is empty returns currently +/// active history or HIST_DEFAULT, depending on `return_default` argument. +/// +/// @param[in] name Converted name. +/// @param[in] len Name length. +/// @param[in] return_default Determines whether HIST_DEFAULT should be +/// returned or value based on `ccline.cmdfirstc`. +/// +/// @return Any value from HistoryType enum, including HIST_INVALID. May not +/// return HIST_DEFAULT unless return_default is true. +static HistoryType get_histtype(const char *const name, const size_t len, const bool return_default) + FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT +{ + // No argument: use current history. + if (len == 0) { + return return_default ? HIST_DEFAULT : hist_char2type(get_cmdline_firstc()); + } + + for (HistoryType i = 0; history_names[i] != NULL; i++) { + if (STRNICMP(name, history_names[i], len) == 0) { + return i; + } + } + + if (vim_strchr(":=@>?/", name[0]) != NULL && len == 1) { + return hist_char2type(name[0]); + } + + return HIST_INVALID; +} + +static int last_maptick = -1; // last seen maptick + +/// Add the given string to the given history. If the string is already in the +/// history then it is moved to the front. +/// +/// @param histype may be one of the HIST_ values. +/// @param in_map consider maptick when inside a mapping +/// @param sep separator character used (search hist) +void add_to_history(int histype, char_u *new_entry, int in_map, int sep) +{ + histentry_T *hisptr; + + if (hislen == 0 || histype == HIST_INVALID) { // no history + return; + } + assert(histype != HIST_DEFAULT); + + if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) && histype == HIST_SEARCH) { + return; + } + + // Searches inside the same mapping overwrite each other, so that only + // the last line is kept. Be careful not to remove a line that was moved + // down, only lines that were added. + if (histype == HIST_SEARCH && in_map) { + if (maptick == last_maptick && hisidx[HIST_SEARCH] >= 0) { + // Current line is from the same mapping, remove it + hisptr = &history[HIST_SEARCH][hisidx[HIST_SEARCH]]; + hist_free_entry(hisptr); + hisnum[histype]--; + if (--hisidx[HIST_SEARCH] < 0) { + hisidx[HIST_SEARCH] = hislen - 1; + } + } + last_maptick = -1; + } + if (!in_history(histype, new_entry, true, sep)) { + if (++hisidx[histype] == hislen) { + hisidx[histype] = 0; + } + hisptr = &history[histype][hisidx[histype]]; + hist_free_entry(hisptr); + + // Store the separator after the NUL of the string. + size_t len = STRLEN(new_entry); + hisptr->hisstr = vim_strnsave(new_entry, len + 2); + hisptr->timestamp = os_time(); + hisptr->additional_elements = NULL; + hisptr->hisstr[len + 1] = (char_u)sep; + + hisptr->hisnum = ++hisnum[histype]; + if (histype == HIST_SEARCH && in_map) { + last_maptick = maptick; + } + } +} + +/// Get identifier of newest history entry. +/// +/// @param histype may be one of the HIST_ values. +static int get_history_idx(int histype) +{ + if (hislen == 0 || histype < 0 || histype >= HIST_COUNT + || hisidx[histype] < 0) { + return -1; + } + + return history[histype][hisidx[histype]].hisnum; +} + +/// Calculate history index from a number: +/// +/// @param num > 0: seen as identifying number of a history entry +/// < 0: relative position in history wrt newest entry +/// @param histype may be one of the HIST_ values. +static int calc_hist_idx(int histype, int num) +{ + int i; + int wrapped = false; + + if (hislen == 0 || histype < 0 || histype >= HIST_COUNT + || (i = hisidx[histype]) < 0 || num == 0) { + return -1; + } + + histentry_T *hist = history[histype]; + if (num > 0) { + while (hist[i].hisnum > num) { + if (--i < 0) { + if (wrapped) { + break; + } + i += hislen; + wrapped = true; + } + } + if (i >= 0 && hist[i].hisnum == num && hist[i].hisstr != NULL) { + return i; + } + } else if (-num <= hislen) { + i += num + 1; + if (i < 0) { + i += hislen; + } + if (hist[i].hisstr != NULL) { + return i; + } + } + return -1; +} + +/// Get a history entry by its index. +/// +/// @param histype may be one of the HIST_ values. +static char_u *get_history_entry(int histype, int idx) +{ + idx = calc_hist_idx(histype, idx); + if (idx >= 0) { + return history[histype][idx].hisstr; + } else { + return (char_u *)""; + } +} + +/// Clear all entries in a history +/// +/// @param[in] histype One of the HIST_ values. +/// +/// @return OK if there was something to clean and histype was one of HIST_ +/// values, FAIL otherwise. +int clr_history(const int histype) +{ + if (hislen != 0 && histype >= 0 && histype < HIST_COUNT) { + histentry_T *hisptr = history[histype]; + for (int i = hislen; i--; hisptr++) { + hist_free_entry(hisptr); + } + hisidx[histype] = -1; // mark history as cleared + hisnum[histype] = 0; // reset identifier counter + return OK; + } + return FAIL; +} + +/// Remove all entries matching {str} from a history. +/// +/// @param histype may be one of the HIST_ values. +static int del_history_entry(int histype, char_u *str) +{ + regmatch_T regmatch; + histentry_T *hisptr; + int idx; + int i; + int last; + bool found = false; + + regmatch.regprog = NULL; + regmatch.rm_ic = false; // always match case + if (hislen != 0 + && histype >= 0 + && histype < HIST_COUNT + && *str != NUL + && (idx = hisidx[histype]) >= 0 + && (regmatch.regprog = vim_regcomp((char *)str, RE_MAGIC + RE_STRING)) != NULL) { + i = last = idx; + do { + hisptr = &history[histype][i]; + if (hisptr->hisstr == NULL) { + break; + } + if (vim_regexec(®match, (char *)hisptr->hisstr, (colnr_T)0)) { + found = true; + hist_free_entry(hisptr); + } else { + if (i != last) { + history[histype][last] = *hisptr; + clear_hist_entry(hisptr); + } + if (--last < 0) { + last += hislen; + } + } + if (--i < 0) { + i += hislen; + } + } while (i != idx); + if (history[histype][idx].hisstr == NULL) { + hisidx[histype] = -1; + } + } + vim_regfree(regmatch.regprog); + return found; +} + +/// Remove an indexed entry from a history. +/// +/// @param histype may be one of the HIST_ values. +static int del_history_idx(int histype, int idx) +{ + int i = calc_hist_idx(histype, idx); + if (i < 0) { + return false; + } + idx = hisidx[histype]; + hist_free_entry(&history[histype][i]); + + // When deleting the last added search string in a mapping, reset + // last_maptick, so that the last added search string isn't deleted again. + if (histype == HIST_SEARCH && maptick == last_maptick && i == idx) { + last_maptick = -1; + } + + while (i != idx) { + int j = (i + 1) % hislen; + history[histype][i] = history[histype][j]; + i = j; + } + clear_hist_entry(&history[histype][idx]); + if (--i < 0) { + i += hislen; + } + hisidx[histype] = i; + return true; +} + +/// "histadd()" function +void f_histadd(typval_T *argvars, typval_T *rettv, FunPtr fptr) +{ + HistoryType histype; + + rettv->vval.v_number = false; + if (check_secure()) { + return; + } + const char *str = tv_get_string_chk(&argvars[0]); // NULL on type error + histype = str != NULL ? get_histtype(str, strlen(str), false) : HIST_INVALID; + if (histype != HIST_INVALID) { + char buf[NUMBUFLEN]; + str = tv_get_string_buf(&argvars[1], buf); + if (*str != NUL) { + init_history(); + add_to_history(histype, (char_u *)str, false, NUL); + rettv->vval.v_number = true; + return; + } + } +} + +/// "histdel()" function +void f_histdel(typval_T *argvars, typval_T *rettv, FunPtr fptr) +{ + int n; + const char *const str = tv_get_string_chk(&argvars[0]); // NULL on type error + if (str == NULL) { + n = 0; + } else if (argvars[1].v_type == VAR_UNKNOWN) { + // only one argument: clear entire history + n = clr_history(get_histtype(str, strlen(str), false)); + } else if (argvars[1].v_type == VAR_NUMBER) { + // index given: remove that entry + n = del_history_idx(get_histtype(str, strlen(str), false), + (int)tv_get_number(&argvars[1])); + } else { + // string given: remove all matching entries + char buf[NUMBUFLEN]; + n = del_history_entry(get_histtype(str, strlen(str), false), + (char_u *)tv_get_string_buf(&argvars[1], buf)); + } + rettv->vval.v_number = n; +} + +/// "histget()" function +void f_histget(typval_T *argvars, typval_T *rettv, FunPtr fptr) +{ + HistoryType type; + int idx; + + const char *const str = tv_get_string_chk(&argvars[0]); // NULL on type error + if (str == NULL) { + rettv->vval.v_string = NULL; + } else { + type = get_histtype(str, strlen(str), false); + if (argvars[1].v_type == VAR_UNKNOWN) { + idx = get_history_idx(type); + } else { + idx = (int)tv_get_number_chk(&argvars[1], NULL); + } + // -1 on type error + rettv->vval.v_string = (char *)vim_strsave(get_history_entry(type, idx)); + } + rettv->v_type = VAR_STRING; +} + +/// "histnr()" function +void f_histnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) +{ + const char *const histname = tv_get_string_chk(&argvars[0]); + HistoryType i = histname == NULL + ? HIST_INVALID + : get_histtype(histname, strlen(histname), false); + if (i != HIST_INVALID) { + i = get_history_idx(i); + } + rettv->vval.v_number = i; +} + +/// :history command - print a history +void ex_history(exarg_T *eap) +{ + histentry_T *hist; + int histype1 = HIST_CMD; + int histype2 = HIST_CMD; + int hisidx1 = 1; + int hisidx2 = -1; + int idx; + int i, j, k; + char_u *end; + char_u *arg = (char_u *)eap->arg; + + if (hislen == 0) { + msg(_("'history' option is zero")); + return; + } + + if (!(ascii_isdigit(*arg) || *arg == '-' || *arg == ',')) { + end = arg; + while (ASCII_ISALPHA(*end) + || vim_strchr(":=@>/?", *end) != NULL) { + end++; + } + histype1 = get_histtype((const char *)arg, (size_t)(end - arg), false); + if (histype1 == HIST_INVALID) { + if (STRNICMP(arg, "all", end - arg) == 0) { + histype1 = 0; + histype2 = HIST_COUNT - 1; + } else { + semsg(_(e_trailing_arg), arg); + return; + } + } else { + histype2 = histype1; + } + } else { + end = arg; + } + if (!get_list_range(&end, &hisidx1, &hisidx2) || *end != NUL) { + semsg(_(e_trailing_arg), end); + return; + } + + for (; !got_int && histype1 <= histype2; histype1++) { + STRCPY(IObuff, "\n # "); + assert(history_names[histype1] != NULL); + STRCAT(STRCAT(IObuff, history_names[histype1]), " history"); + msg_puts_title((char *)IObuff); + idx = hisidx[histype1]; + hist = history[histype1]; + j = hisidx1; + k = hisidx2; + if (j < 0) { + j = (-j > hislen) ? 0 : hist[(hislen + j + idx + 1) % hislen].hisnum; + } + if (k < 0) { + k = (-k > hislen) ? 0 : hist[(hislen + k + idx + 1) % hislen].hisnum; + } + if (idx >= 0 && j <= k) { + for (i = idx + 1; !got_int; i++) { + if (i == hislen) { + i = 0; + } + if (hist[i].hisstr != NULL + && hist[i].hisnum >= j && hist[i].hisnum <= k) { + msg_putchar('\n'); + snprintf((char *)IObuff, IOSIZE, "%c%6d ", i == idx ? '>' : ' ', + hist[i].hisnum); + if (vim_strsize((char *)hist[i].hisstr) > Columns - 10) { + trunc_string((char *)hist[i].hisstr, (char *)IObuff + STRLEN(IObuff), + Columns - 10, IOSIZE - (int)STRLEN(IObuff)); + } else { + STRCAT(IObuff, hist[i].hisstr); + } + msg_outtrans((char *)IObuff); + ui_flush(); + } + if (i == idx) { + break; + } + } + } + } +} + +/// Iterate over history items +/// +/// @warning No history-editing functions must be run while iteration is in +/// progress. +/// +/// @param[in] iter Pointer to the last history entry. +/// @param[in] history_type Type of the history (HIST_*). Ignored if iter +/// parameter is not NULL. +/// @param[in] zero If true then zero (but not free) returned items. +/// +/// @warning When using this parameter user is +/// responsible for calling clr_history() +/// itself after iteration is over. If +/// clr_history() is not called behaviour is +/// undefined. No functions that work with +/// history must be called during iteration +/// in this case. +/// @param[out] hist Next history entry. +/// +/// @return Pointer used in next iteration or NULL to indicate that iteration +/// was finished. +const void *hist_iter(const void *const iter, const uint8_t history_type, const bool zero, + histentry_T *const hist) + FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(4) +{ + *hist = (histentry_T) { + .hisstr = NULL + }; + if (hisidx[history_type] == -1) { + return NULL; + } + histentry_T *const hstart = &(history[history_type][0]); + histentry_T *const hlast = &(history[history_type][hisidx[history_type]]); + const histentry_T *const hend = &(history[history_type][hislen - 1]); + histentry_T *hiter; + if (iter == NULL) { + histentry_T *hfirst = hlast; + do { + hfirst++; + if (hfirst > hend) { + hfirst = hstart; + } + if (hfirst->hisstr != NULL) { + break; + } + } while (hfirst != hlast); + hiter = hfirst; + } else { + hiter = (histentry_T *)iter; + } + if (hiter == NULL) { + return NULL; + } + *hist = *hiter; + if (zero) { + memset(hiter, 0, sizeof(*hiter)); + } + if (hiter == hlast) { + return NULL; + } + hiter++; + return (const void *)((hiter > hend) ? hstart : hiter); +} + +/// Get array of history items +/// +/// @param[in] history_type Type of the history to get array for. +/// @param[out] new_hisidx Location where last index in the new array should +/// be saved. +/// @param[out] new_hisnum Location where last history number in the new +/// history should be saved. +/// +/// @return Pointer to the array or NULL. +histentry_T *hist_get_array(const uint8_t history_type, int **const new_hisidx, + int **const new_hisnum) + FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL +{ + init_history(); + *new_hisidx = &(hisidx[history_type]); + *new_hisnum = &(hisnum[history_type]); + return history[history_type]; +} diff --git a/src/nvim/cmdhist.h b/src/nvim/cmdhist.h new file mode 100644 index 0000000000..797b79a5f0 --- /dev/null +++ b/src/nvim/cmdhist.h @@ -0,0 +1,33 @@ +#ifndef NVIM_CMDHIST_H +#define NVIM_CMDHIST_H + +#include "nvim/eval/typval.h" +#include "nvim/ex_cmds_defs.h" +#include "nvim/os/time.h" + +/// Present history tables +typedef enum { + HIST_DEFAULT = -2, ///< Default (current) history. + HIST_INVALID = -1, ///< Unknown history. + HIST_CMD = 0, ///< Colon commands. + HIST_SEARCH, ///< Search commands. + HIST_EXPR, ///< Expressions (e.g. from entering = register). + HIST_INPUT, ///< input() lines. + HIST_DEBUG, ///< Debug commands. +} HistoryType; + +/// Number of history tables +#define HIST_COUNT (HIST_DEBUG + 1) + +/// History entry definition +typedef struct hist_entry { + int hisnum; ///< Entry identifier number. + char_u *hisstr; ///< Actual entry, separator char after the NUL. + Timestamp timestamp; ///< Time when entry was added. + list_T *additional_elements; ///< Additional entries from ShaDa file. +} histentry_T; + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "cmdhist.h.generated.h" +#endif +#endif // NVIM_CMDHIST_H diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 5911a93099..b0a207e5ba 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -19,6 +19,7 @@ #include "nvim/change.h" #include "nvim/channel.h" #include "nvim/charset.h" +#include "nvim/cmdhist.h" #include "nvim/cursor.h" #include "nvim/edit.h" #include "nvim/eval.h" diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 060dc50f52..52386a67f6 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -13,6 +13,7 @@ #include "nvim/change.h" #include "nvim/channel.h" #include "nvim/charset.h" +#include "nvim/cmdhist.h" #include "nvim/context.h" #include "nvim/cursor.h" #include "nvim/diff.h" @@ -4303,87 +4304,6 @@ static void f_haslocaldir(typval_T *argvars, typval_T *rettv, FunPtr fptr) } } -/// "histadd()" function -static void f_histadd(typval_T *argvars, typval_T *rettv, FunPtr fptr) -{ - HistoryType histype; - - rettv->vval.v_number = false; - if (check_secure()) { - return; - } - const char *str = tv_get_string_chk(&argvars[0]); // NULL on type error - histype = str != NULL ? get_histtype(str, strlen(str), false) : HIST_INVALID; - if (histype != HIST_INVALID) { - char buf[NUMBUFLEN]; - str = tv_get_string_buf(&argvars[1], buf); - if (*str != NUL) { - init_history(); - add_to_history(histype, (char_u *)str, false, NUL); - rettv->vval.v_number = true; - return; - } - } -} - -/// "histdel()" function -static void f_histdel(typval_T *argvars, typval_T *rettv, FunPtr fptr) -{ - int n; - const char *const str = tv_get_string_chk(&argvars[0]); // NULL on type error - if (str == NULL) { - n = 0; - } else if (argvars[1].v_type == VAR_UNKNOWN) { - // only one argument: clear entire history - n = clr_history(get_histtype(str, strlen(str), false)); - } else if (argvars[1].v_type == VAR_NUMBER) { - // index given: remove that entry - n = del_history_idx(get_histtype(str, strlen(str), false), - (int)tv_get_number(&argvars[1])); - } else { - // string given: remove all matching entries - char buf[NUMBUFLEN]; - n = del_history_entry(get_histtype(str, strlen(str), false), - (char_u *)tv_get_string_buf(&argvars[1], buf)); - } - rettv->vval.v_number = n; -} - -/// "histget()" function -static void f_histget(typval_T *argvars, typval_T *rettv, FunPtr fptr) -{ - HistoryType type; - int idx; - - const char *const str = tv_get_string_chk(&argvars[0]); // NULL on type error - if (str == NULL) { - rettv->vval.v_string = NULL; - } else { - type = get_histtype(str, strlen(str), false); - if (argvars[1].v_type == VAR_UNKNOWN) { - idx = get_history_idx(type); - } else { - idx = (int)tv_get_number_chk(&argvars[1], NULL); - } - // -1 on type error - rettv->vval.v_string = (char *)vim_strsave(get_history_entry(type, idx)); - } - rettv->v_type = VAR_STRING; -} - -/// "histnr()" function -static void f_histnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) -{ - const char *const history = tv_get_string_chk(&argvars[0]); - HistoryType i = history == NULL - ? HIST_INVALID - : get_histtype(history, strlen(history), false); - if (i != HIST_INVALID) { - i = get_history_idx(i); - } - rettv->vval.v_number = i; -} - /// "highlightID(name)" function static void f_hlID(typval_T *argvars, typval_T *rettv, FunPtr fptr) { diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 9d1ac185d4..9ad65500e9 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -20,6 +20,7 @@ #include "nvim/buffer_updates.h" #include "nvim/change.h" #include "nvim/charset.h" +#include "nvim/cmdhist.h" #include "nvim/cursor.h" #include "nvim/decoration.h" #include "nvim/diff.h" @@ -3343,6 +3344,7 @@ static bool sub_joining_lines(exarg_T *eap, char *pat, char *sub, char *cmd, boo if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) { save_re_pat(RE_SUBST, (char_u *)pat, p_magic); } + // put pattern in history add_to_history(HIST_SEARCH, (char_u *)pat, true, NUL); } diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 4ac9847e53..86c5489cf2 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -13,6 +13,7 @@ #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" +#include "nvim/cmdhist.h" #include "nvim/cursor.h" #include "nvim/debugger.h" #include "nvim/diff.h" @@ -601,10 +602,9 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) if (next_cmdline == NULL) { XFREE_CLEAR(cmdline_copy); - // + // If the command was typed, remember it for the ':' register. // Do this AFTER executing the command to make :@: work. - // if (getline_equal(fgetline, cookie, getexline) && new_last_cmdline != NULL) { xfree(last_cmdline); diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 07a0e68884..841345d625 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -19,6 +19,7 @@ #include "nvim/assert.h" #include "nvim/buffer.h" #include "nvim/charset.h" +#include "nvim/cmdhist.h" #include "nvim/cursor.h" #include "nvim/cursor_shape.h" #include "nvim/digraph.h" @@ -214,12 +215,6 @@ static Array cmdline_block = ARRAY_DICT_INIT; */ typedef void *(*user_expand_func_T)(const char_u *, int, typval_T *); -static histentry_T *(history[HIST_COUNT]) = { NULL, NULL, NULL, NULL, NULL }; -static int hisidx[HIST_COUNT] = { -1, -1, -1, -1, -1 }; // lastused entry -static int hisnum[HIST_COUNT] = { 0, 0, 0, 0, 0 }; -// identifying (unique) number of newest history entry -static int hislen = 0; // actual length of history tables - /// Flag for command_line_handle_key to ignore /// /// Used if it was received while processing highlight function in order for @@ -869,7 +864,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init may_trigger_modechanged(); init_history(); - s->hiscnt = hislen; // set hiscnt to impossible history value + s->hiscnt = get_hislen(); // set hiscnt to impossible history value s->histype = hist_char2type(s->firstc); do_digraph(-1); // init digraph typeahead @@ -1682,12 +1677,12 @@ static void command_line_next_histidx(CommandLineState *s, bool next_match) for (;;) { // one step backwards if (!next_match) { - if (s->hiscnt == hislen) { + if (s->hiscnt == get_hislen()) { // first time - s->hiscnt = hisidx[s->histype]; - } else if (s->hiscnt == 0 && hisidx[s->histype] != hislen - 1) { - s->hiscnt = hislen - 1; - } else if (s->hiscnt != hisidx[s->histype] + 1) { + s->hiscnt = *get_hisidx(s->histype); + } else if (s->hiscnt == 0 && *get_hisidx(s->histype) != get_hislen() - 1) { + s->hiscnt = get_hislen() - 1; + } else if (s->hiscnt != *get_hisidx(s->histype) + 1) { s->hiscnt--; } else { // at top of list @@ -1696,17 +1691,17 @@ static void command_line_next_histidx(CommandLineState *s, bool next_match) } } else { // one step forwards // on last entry, clear the line - if (s->hiscnt == hisidx[s->histype]) { - s->hiscnt = hislen; + if (s->hiscnt == *get_hisidx(s->histype)) { + s->hiscnt = get_hislen(); break; } // not on a history line, nothing to do - if (s->hiscnt == hislen) { + if (s->hiscnt == get_hislen()) { break; } - if (s->hiscnt == hislen - 1) { + if (s->hiscnt == get_hislen() - 1) { // wrap around s->hiscnt = 0; } else { @@ -1714,14 +1709,14 @@ static void command_line_next_histidx(CommandLineState *s, bool next_match) } } - if (s->hiscnt < 0 || history[s->histype][s->hiscnt].hisstr == NULL) { + if (s->hiscnt < 0 || get_histentry(s->histype)[s->hiscnt].hisstr == NULL) { s->hiscnt = s->save_hiscnt; break; } if ((s->c != K_UP && s->c != K_DOWN) || s->hiscnt == s->save_hiscnt - || STRNCMP(history[s->histype][s->hiscnt].hisstr, + || STRNCMP(get_histentry(s->histype)[s->hiscnt].hisstr, s->lookfor, (size_t)j) == 0) { break; } @@ -2103,7 +2098,7 @@ static int command_line_handle_key(CommandLineState *s) case K_KPAGEUP: case K_PAGEDOWN: case K_KPAGEDOWN: - if (s->histype == HIST_INVALID || hislen == 0 || s->firstc == NUL) { + if (s->histype == HIST_INVALID || get_hislen() == 0 || s->firstc == NUL) { // no history return command_line_not_changed(s); } @@ -2128,10 +2123,10 @@ static int command_line_handle_key(CommandLineState *s) XFREE_CLEAR(ccline.cmdbuff); s->xpc.xp_context = EXPAND_NOTHING; - if (s->hiscnt == hislen) { + if (s->hiscnt == get_hislen()) { p = s->lookfor; // back to the old one } else { - p = history[s->histype][s->hiscnt].hisstr; + p = get_histentry(s->histype)[s->hiscnt].hisstr; } if (s->histype == HIST_SEARCH @@ -5868,309 +5863,6 @@ void globpath(char_u *path, char_u *file, garray_T *ga, int expand_options) xfree(buf); } -/********************************* -* Command line history stuff * -*********************************/ - -/// Translate a history character to the associated type number -static HistoryType hist_char2type(const int c) - FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT -{ - switch (c) { - case ':': - return HIST_CMD; - case '=': - return HIST_EXPR; - case '@': - return HIST_INPUT; - case '>': - return HIST_DEBUG; - case NUL: - case '/': - case '?': - return HIST_SEARCH; - default: - return HIST_INVALID; - } - // Silence -Wreturn-type - return 0; -} - -/* - * Table of history names. - * These names are used in :history and various hist...() functions. - * It is sufficient to give the significant prefix of a history name. - */ - -static char *(history_names[]) = -{ - "cmd", - "search", - "expr", - "input", - "debug", - NULL -}; - -/* - * Function given to ExpandGeneric() to obtain the possible first - * arguments of the ":history command. - */ -static char *get_history_arg(expand_T *xp, int idx) -{ - static char_u compl[2] = { NUL, NUL }; - char *short_names = ":=@>?/"; - int short_names_count = (int)STRLEN(short_names); - int history_name_count = ARRAY_SIZE(history_names) - 1; - - if (idx < short_names_count) { - compl[0] = (char_u)short_names[idx]; - return (char *)compl; - } - if (idx < short_names_count + history_name_count) { - return history_names[idx - short_names_count]; - } - if (idx == short_names_count + history_name_count) { - return "all"; - } - return NULL; -} - -/// Initialize command line history. -/// Also used to re-allocate history tables when size changes. -void init_history(void) -{ - assert(p_hi >= 0 && p_hi <= INT_MAX); - int newlen = (int)p_hi; - int oldlen = hislen; - - // If history tables size changed, reallocate them. - // Tables are circular arrays (current position marked by hisidx[type]). - // On copying them to the new arrays, we take the chance to reorder them. - if (newlen != oldlen) { - for (int type = 0; type < HIST_COUNT; type++) { - histentry_T *temp = (newlen - ? xmalloc((size_t)newlen * sizeof(*temp)) - : NULL); - - int j = hisidx[type]; - if (j >= 0) { - // old array gets partitioned this way: - // [0 , i1 ) --> newest entries to be deleted - // [i1 , i1 + l1) --> newest entries to be copied - // [i1 + l1 , i2 ) --> oldest entries to be deleted - // [i2 , i2 + l2) --> oldest entries to be copied - int l1 = MIN(j + 1, newlen); // how many newest to copy - int l2 = MIN(newlen, oldlen) - l1; // how many oldest to copy - int i1 = j + 1 - l1; // copy newest from here - int i2 = MAX(l1, oldlen - newlen + l1); // copy oldest from here - - // copy as much entries as they fit to new table, reordering them - if (newlen) { - // copy oldest entries - memcpy(&temp[0], &history[type][i2], (size_t)l2 * sizeof(*temp)); - // copy newest entries - memcpy(&temp[l2], &history[type][i1], (size_t)l1 * sizeof(*temp)); - } - - // delete entries that don't fit in newlen, if any - for (int i = 0; i < i1; i++) { - hist_free_entry(history[type] + i); - } - for (int i = i1 + l1; i < i2; i++) { - hist_free_entry(history[type] + i); - } - } - - // clear remaining space, if any - int l3 = j < 0 ? 0 : MIN(newlen, oldlen); // number of copied entries - if (newlen) { - memset(temp + l3, 0, (size_t)(newlen - l3) * sizeof(*temp)); - } - - hisidx[type] = l3 - 1; - xfree(history[type]); - history[type] = temp; - } - hislen = newlen; - } -} - -static inline void hist_free_entry(histentry_T *hisptr) - FUNC_ATTR_NONNULL_ALL -{ - xfree(hisptr->hisstr); - tv_list_unref(hisptr->additional_elements); - clear_hist_entry(hisptr); -} - -static inline void clear_hist_entry(histentry_T *hisptr) - FUNC_ATTR_NONNULL_ALL -{ - memset(hisptr, 0, sizeof(*hisptr)); -} - -/// Check if command line 'str' is already in history. -/// If 'move_to_front' is TRUE, matching entry is moved to end of history. -/// -/// @param move_to_front Move the entry to the front if it exists -static int in_history(int type, char_u *str, int move_to_front, int sep) -{ - int i; - int last_i = -1; - char_u *p; - - if (hisidx[type] < 0) { - return FALSE; - } - i = hisidx[type]; - do { - if (history[type][i].hisstr == NULL) { - return FALSE; - } - - /* For search history, check that the separator character matches as - * well. */ - p = history[type][i].hisstr; - if (STRCMP(str, p) == 0 - && (type != HIST_SEARCH || sep == p[STRLEN(p) + 1])) { - if (!move_to_front) { - return TRUE; - } - last_i = i; - break; - } - if (--i < 0) { - i = hislen - 1; - } - } while (i != hisidx[type]); - - if (last_i >= 0) { - list_T *const list = history[type][i].additional_elements; - str = history[type][i].hisstr; - while (i != hisidx[type]) { - if (++i >= hislen) { - i = 0; - } - history[type][last_i] = history[type][i]; - last_i = i; - } - tv_list_unref(list); - history[type][i].hisnum = ++hisnum[type]; - history[type][i].hisstr = str; - history[type][i].timestamp = os_time(); - history[type][i].additional_elements = NULL; - return true; - } - return false; -} - -/// Convert history name to its HIST_ equivalent -/// -/// Names are taken from the table above. When `name` is empty returns currently -/// active history or HIST_DEFAULT, depending on `return_default` argument. -/// -/// @param[in] name Converted name. -/// @param[in] len Name length. -/// @param[in] return_default Determines whether HIST_DEFAULT should be -/// returned or value based on `ccline.cmdfirstc`. -/// -/// @return Any value from HistoryType enum, including HIST_INVALID. May not -/// return HIST_DEFAULT unless return_default is true. -HistoryType get_histtype(const char *const name, const size_t len, const bool return_default) - FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT -{ - // No argument: use current history. - if (len == 0) { - return return_default ? HIST_DEFAULT : hist_char2type(ccline.cmdfirstc); - } - - for (HistoryType i = 0; history_names[i] != NULL; i++) { - if (STRNICMP(name, history_names[i], len) == 0) { - return i; - } - } - - if (vim_strchr(":=@>?/", name[0]) != NULL && len == 1) { - return hist_char2type(name[0]); - } - - return HIST_INVALID; -} - -static int last_maptick = -1; // last seen maptick - -/// Add the given string to the given history. If the string is already in the -/// history then it is moved to the front. "histype" may be one of the HIST_ -/// values. -/// -/// @parma in_map consider maptick when inside a mapping -/// @param sep separator character used (search hist) -void add_to_history(int histype, char_u *new_entry, int in_map, int sep) -{ - histentry_T *hisptr; - - if (hislen == 0 || histype == HIST_INVALID) { // no history - return; - } - assert(histype != HIST_DEFAULT); - - if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) && histype == HIST_SEARCH) { - return; - } - - /* - * Searches inside the same mapping overwrite each other, so that only - * the last line is kept. Be careful not to remove a line that was moved - * down, only lines that were added. - */ - if (histype == HIST_SEARCH && in_map) { - if (maptick == last_maptick && hisidx[HIST_SEARCH] >= 0) { - // Current line is from the same mapping, remove it - hisptr = &history[HIST_SEARCH][hisidx[HIST_SEARCH]]; - hist_free_entry(hisptr); - --hisnum[histype]; - if (--hisidx[HIST_SEARCH] < 0) { - hisidx[HIST_SEARCH] = hislen - 1; - } - } - last_maptick = -1; - } - if (!in_history(histype, new_entry, true, sep)) { - if (++hisidx[histype] == hislen) { - hisidx[histype] = 0; - } - hisptr = &history[histype][hisidx[histype]]; - hist_free_entry(hisptr); - - // Store the separator after the NUL of the string. - size_t len = STRLEN(new_entry); - hisptr->hisstr = vim_strnsave(new_entry, len + 2); - hisptr->timestamp = os_time(); - hisptr->additional_elements = NULL; - hisptr->hisstr[len + 1] = (char_u)sep; - - hisptr->hisnum = ++hisnum[histype]; - if (histype == HIST_SEARCH && in_map) { - last_maptick = maptick; - } - } -} - -/* - * Get identifier of newest history entry. - * "histype" may be one of the HIST_ values. - */ -int get_history_idx(int histype) -{ - if (hislen == 0 || histype < 0 || histype >= HIST_COUNT - || hisidx[histype] < 0) { - return -1; - } - - return history[histype][hisidx[histype]].hisnum; -} - /// Get pointer to the command line info to use. save_cmdline() may clear /// ccline and put the previous value in ccline.prev_ccline. static struct cmdline_info *get_ccline_ptr(void) @@ -6292,168 +5984,10 @@ int get_cmdline_type(void) return p->cmdfirstc; } -/* - * Calculate history index from a number: - * num > 0: seen as identifying number of a history entry - * num < 0: relative position in history wrt newest entry - * "histype" may be one of the HIST_ values. - */ -static int calc_hist_idx(int histype, int num) -{ - int i; - histentry_T *hist; - int wrapped = FALSE; - - if (hislen == 0 || histype < 0 || histype >= HIST_COUNT - || (i = hisidx[histype]) < 0 || num == 0) { - return -1; - } - - hist = history[histype]; - if (num > 0) { - while (hist[i].hisnum > num) { - if (--i < 0) { - if (wrapped) { - break; - } - i += hislen; - wrapped = TRUE; - } - } - if (i >= 0 && hist[i].hisnum == num && hist[i].hisstr != NULL) { - return i; - } - } else if (-num <= hislen) { - i += num + 1; - if (i < 0) { - i += hislen; - } - if (hist[i].hisstr != NULL) { - return i; - } - } - return -1; -} - -/* - * Get a history entry by its index. - * "histype" may be one of the HIST_ values. - */ -char_u *get_history_entry(int histype, int idx) +/// Return the first character of the current command line. +int get_cmdline_firstc(void) { - idx = calc_hist_idx(histype, idx); - if (idx >= 0) { - return history[histype][idx].hisstr; - } else { - return (char_u *)""; - } -} - -/// Clear all entries in a history -/// -/// @param[in] histype One of the HIST_ values. -/// -/// @return OK if there was something to clean and histype was one of HIST_ -/// values, FAIL otherwise. -int clr_history(const int histype) -{ - if (hislen != 0 && histype >= 0 && histype < HIST_COUNT) { - histentry_T *hisptr = history[histype]; - for (int i = hislen; i--; hisptr++) { - hist_free_entry(hisptr); - } - hisidx[histype] = -1; // mark history as cleared - hisnum[histype] = 0; // reset identifier counter - return OK; - } - return FAIL; -} - -/* - * Remove all entries matching {str} from a history. - * "histype" may be one of the HIST_ values. - */ -int del_history_entry(int histype, char_u *str) -{ - regmatch_T regmatch; - histentry_T *hisptr; - int idx; - int i; - int last; - bool found = false; - - regmatch.regprog = NULL; - regmatch.rm_ic = FALSE; // always match case - if (hislen != 0 - && histype >= 0 - && histype < HIST_COUNT - && *str != NUL - && (idx = hisidx[histype]) >= 0 - && (regmatch.regprog = vim_regcomp((char *)str, RE_MAGIC + RE_STRING)) - != NULL) { - i = last = idx; - do { - hisptr = &history[histype][i]; - if (hisptr->hisstr == NULL) { - break; - } - if (vim_regexec(®match, (char *)hisptr->hisstr, (colnr_T)0)) { - found = true; - hist_free_entry(hisptr); - } else { - if (i != last) { - history[histype][last] = *hisptr; - clear_hist_entry(hisptr); - } - if (--last < 0) { - last += hislen; - } - } - if (--i < 0) { - i += hislen; - } - } while (i != idx); - if (history[histype][idx].hisstr == NULL) { - hisidx[histype] = -1; - } - } - vim_regfree(regmatch.regprog); - return found; -} - -/* - * Remove an indexed entry from a history. - * "histype" may be one of the HIST_ values. - */ -int del_history_idx(int histype, int idx) -{ - int i, j; - - i = calc_hist_idx(histype, idx); - if (i < 0) { - return FALSE; - } - idx = hisidx[histype]; - hist_free_entry(&history[histype][i]); - - /* When deleting the last added search string in a mapping, reset - * last_maptick, so that the last added search string isn't deleted again. - */ - if (histype == HIST_SEARCH && maptick == last_maptick && i == idx) { - last_maptick = -1; - } - - while (i != idx) { - j = (i + 1) % hislen; - history[histype][i] = history[histype][j]; - i = j; - } - clear_hist_entry(&history[histype][idx]); - if (--i < 0) { - i += hislen; - } - hisidx[histype] = i; - return TRUE; + return ccline.cmdfirstc; } /// Get indices that specify a range within a list (not a range of text lines @@ -6493,115 +6027,6 @@ int get_list_range(char_u **str, int *num1, int *num2) return OK; } -/* - * :history command - print a history - */ -void ex_history(exarg_T *eap) -{ - histentry_T *hist; - int histype1 = HIST_CMD; - int histype2 = HIST_CMD; - int hisidx1 = 1; - int hisidx2 = -1; - int idx; - int i, j, k; - char_u *end; - char_u *arg = (char_u *)eap->arg; - - if (hislen == 0) { - msg(_("'history' option is zero")); - return; - } - - if (!(ascii_isdigit(*arg) || *arg == '-' || *arg == ',')) { - end = arg; - while (ASCII_ISALPHA(*end) - || vim_strchr(":=@>/?", *end) != NULL) { - end++; - } - histype1 = get_histtype((const char *)arg, (size_t)(end - arg), false); - if (histype1 == HIST_INVALID) { - if (STRNICMP(arg, "all", end - arg) == 0) { - histype1 = 0; - histype2 = HIST_COUNT - 1; - } else { - semsg(_(e_trailing_arg), arg); - return; - } - } else { - histype2 = histype1; - } - } else { - end = arg; - } - if (!get_list_range(&end, &hisidx1, &hisidx2) || *end != NUL) { - semsg(_(e_trailing_arg), end); - return; - } - - for (; !got_int && histype1 <= histype2; ++histype1) { - STRCPY(IObuff, "\n # "); - assert(history_names[histype1] != NULL); - STRCAT(STRCAT(IObuff, history_names[histype1]), " history"); - msg_puts_title((char *)IObuff); - idx = hisidx[histype1]; - hist = history[histype1]; - j = hisidx1; - k = hisidx2; - if (j < 0) { - j = (-j > hislen) ? 0 : hist[(hislen + j + idx + 1) % hislen].hisnum; - } - if (k < 0) { - k = (-k > hislen) ? 0 : hist[(hislen + k + idx + 1) % hislen].hisnum; - } - if (idx >= 0 && j <= k) { - for (i = idx + 1; !got_int; ++i) { - if (i == hislen) { - i = 0; - } - if (hist[i].hisstr != NULL - && hist[i].hisnum >= j && hist[i].hisnum <= k) { - msg_putchar('\n'); - snprintf((char *)IObuff, IOSIZE, "%c%6d ", i == idx ? '>' : ' ', - hist[i].hisnum); - if (vim_strsize((char *)hist[i].hisstr) > Columns - 10) { - trunc_string((char *)hist[i].hisstr, (char *)IObuff + STRLEN(IObuff), - Columns - 10, IOSIZE - (int)STRLEN(IObuff)); - } else { - STRCAT(IObuff, hist[i].hisstr); - } - msg_outtrans((char *)IObuff); - ui_flush(); - } - if (i == idx) { - break; - } - } - } - } -} - -/// Translate a history type number to the associated character -int hist_type2char(int type) - FUNC_ATTR_CONST -{ - switch (type) { - case HIST_CMD: - return ':'; - case HIST_SEARCH: - return '/'; - case HIST_EXPR: - return '='; - case HIST_INPUT: - return '@'; - case HIST_DEBUG: - return '>'; - default: - abort(); - } - return NUL; -} - void cmdline_init(void) { memset(&ccline, 0, sizeof(struct cmdline_info)); @@ -6688,18 +6113,18 @@ static int open_cmdwin(void) // Fill the buffer with the history. init_history(); - if (hislen > 0 && histtype != HIST_INVALID) { - i = hisidx[histtype]; + if (get_hislen() > 0 && histtype != HIST_INVALID) { + i = *get_hisidx(histtype); if (i >= 0) { lnum = 0; do { - if (++i == hislen) { + if (++i == get_hislen()) { i = 0; } - if (history[histtype][i].hisstr != NULL) { - ml_append(lnum++, (char *)history[histtype][i].hisstr, (colnr_T)0, false); + if (get_histentry(histtype)[i].hisstr != NULL) { + ml_append(lnum++, (char *)get_histentry(histtype)[i].hisstr, (colnr_T)0, false); } - } while (i != hisidx[histtype]); + } while (i != *get_hisidx(histtype)); } } @@ -6904,90 +6329,6 @@ char *script_get(exarg_T *const eap, size_t *const lenp) return (char *)ga.ga_data; } -/// Iterate over history items -/// -/// @warning No history-editing functions must be run while iteration is in -/// progress. -/// -/// @param[in] iter Pointer to the last history entry. -/// @param[in] history_type Type of the history (HIST_*). Ignored if iter -/// parameter is not NULL. -/// @param[in] zero If true then zero (but not free) returned items. -/// -/// @warning When using this parameter user is -/// responsible for calling clr_history() -/// itself after iteration is over. If -/// clr_history() is not called behaviour is -/// undefined. No functions that work with -/// history must be called during iteration -/// in this case. -/// @param[out] hist Next history entry. -/// -/// @return Pointer used in next iteration or NULL to indicate that iteration -/// was finished. -const void *hist_iter(const void *const iter, const uint8_t history_type, const bool zero, - histentry_T *const hist) - FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(4) -{ - *hist = (histentry_T) { - .hisstr = NULL - }; - if (hisidx[history_type] == -1) { - return NULL; - } - histentry_T *const hstart = &(history[history_type][0]); - histentry_T *const hlast = ( - &(history[history_type][hisidx[history_type]])); - const histentry_T *const hend = &(history[history_type][hislen - 1]); - histentry_T *hiter; - if (iter == NULL) { - histentry_T *hfirst = hlast; - do { - hfirst++; - if (hfirst > hend) { - hfirst = hstart; - } - if (hfirst->hisstr != NULL) { - break; - } - } while (hfirst != hlast); - hiter = hfirst; - } else { - hiter = (histentry_T *)iter; - } - if (hiter == NULL) { - return NULL; - } - *hist = *hiter; - if (zero) { - memset(hiter, 0, sizeof(*hiter)); - } - if (hiter == hlast) { - return NULL; - } - hiter++; - return (const void *)((hiter > hend) ? hstart : hiter); -} - -/// Get array of history items -/// -/// @param[in] history_type Type of the history to get array for. -/// @param[out] new_hisidx Location where last index in the new array should -/// be saved. -/// @param[out] new_hisnum Location where last history number in the new -/// history should be saved. -/// -/// @return Pointer to the array or NULL. -histentry_T *hist_get_array(const uint8_t history_type, int **const new_hisidx, - int **const new_hisnum) - FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL -{ - init_history(); - *new_hisidx = &(hisidx[history_type]); - *new_hisnum = &(hisnum[history_type]); - return history[history_type]; -} - static void set_search_match(pos_T *t) { // First move cursor to end of match, then to the start. This diff --git a/src/nvim/ex_getln.h b/src/nvim/ex_getln.h index 1cc6faf87c..2f6929924d 100644 --- a/src/nvim/ex_getln.h +++ b/src/nvim/ex_getln.h @@ -3,8 +3,6 @@ #include "nvim/eval/typval.h" #include "nvim/ex_cmds.h" -#include "nvim/ex_cmds_defs.h" -#include "nvim/os/time.h" #include "nvim/regexp_defs.h" // Values for nextwild() and ExpandOne(). See ExpandOne() for meaning. @@ -39,30 +37,8 @@ #define VSE_SHELL 1 ///< escape for a shell command #define VSE_BUFFER 2 ///< escape for a ":buffer" command -/// Present history tables -typedef enum { - HIST_DEFAULT = -2, ///< Default (current) history. - HIST_INVALID = -1, ///< Unknown history. - HIST_CMD = 0, ///< Colon commands. - HIST_SEARCH, ///< Search commands. - HIST_EXPR, ///< Expressions (e.g. from entering = register). - HIST_INPUT, ///< input() lines. - HIST_DEBUG, ///< Debug commands. -} HistoryType; - -/// Number of history tables -#define HIST_COUNT (HIST_DEBUG + 1) - typedef char *(*CompleteListItemGetter)(expand_T *, int); -/// History entry definition -typedef struct hist_entry { - int hisnum; ///< Entry identifier number. - char_u *hisstr; ///< Actual entry, separator char after the NUL. - Timestamp timestamp; ///< Time when entry was added. - list_T *additional_elements; ///< Additional entries from ShaDa file. -} histentry_T; - #ifdef INCLUDE_GENERATED_DECLARATIONS # include "ex_getln.h.generated.h" #endif diff --git a/src/nvim/memory.c b/src/nvim/memory.c index 5ae7f7bbe3..4d00c0212e 100644 --- a/src/nvim/memory.c +++ b/src/nvim/memory.c @@ -619,6 +619,7 @@ char *arena_memdupz(Arena *arena, const char *buf, size_t size) # include "nvim/buffer.h" # include "nvim/charset.h" +# include "nvim/cmdhist.h" # include "nvim/diff.h" # include "nvim/edit.h" # include "nvim/eval/typval.h" diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 2d752eade7..064b73a56f 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -18,6 +18,7 @@ #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" +#include "nvim/cmdhist.h" #include "nvim/cursor.h" #include "nvim/diff.h" #include "nvim/digraph.h" @@ -4379,9 +4380,11 @@ static void nv_ident(cmdarg_T *cap) && vim_iswordp(mb_prevptr(get_cursor_line_ptr(), ptr))) { STRCAT(buf, "\\>"); } + // put pattern in search history init_history(); add_to_history(HIST_SEARCH, (char_u *)buf, true, NUL); + (void)normal_search(cap, cmdchar == '*' ? '/' : '?', (char_u *)buf, 0, NULL); } else { diff --git a/src/nvim/search.c b/src/nvim/search.c index 403e2f3aa4..b9aac59e1e 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -15,6 +15,7 @@ #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" +#include "nvim/cmdhist.h" #include "nvim/cursor.h" #include "nvim/edit.h" #include "nvim/eval.h" diff --git a/src/nvim/shada.c b/src/nvim/shada.c index 6e80b550d8..ee5322752f 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -16,11 +16,12 @@ #include "nvim/ascii.h" #include "nvim/buffer.h" #include "nvim/buffer_defs.h" +#include "nvim/cmdhist.h" #include "nvim/eval/decode.h" #include "nvim/eval/encode.h" #include "nvim/eval/typval.h" +#include "nvim/ex_cmds.h" #include "nvim/ex_docmd.h" -#include "nvim/ex_getln.h" #include "nvim/fileio.h" #include "nvim/garray.h" #include "nvim/globals.h" @@ -2451,6 +2452,27 @@ static inline void find_removable_bufs(khash_t(bufset) *removable_bufs) } } +/// Translate a history type number to the associated character +static int hist_type2char(const int type) + FUNC_ATTR_CONST +{ + switch (type) { + case HIST_CMD: + return ':'; + case HIST_SEARCH: + return '/'; + case HIST_EXPR: + return '='; + case HIST_INPUT: + return '@'; + case HIST_DEBUG: + return '>'; + default: + abort(); + } + return NUL; +} + /// Write ShaDa file /// /// @param[in] sd_writer Structure containing file writer definition. -- cgit From 33ddca6fa0534df2605699070fdd1e5c6e4a7bcf Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 9 Aug 2022 13:21:50 +0200 Subject: docs(lua): add luv (`vim.loop`) reference manual (#19679) Upstreamed from https://github.com/nanotee/luv-vimdocs with kind permission from @nanotee. --- runtime/doc/help.txt | 1 + runtime/doc/lua.txt | 4 +- runtime/doc/luvref.txt | 3898 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 3901 insertions(+), 2 deletions(-) create mode 100644 runtime/doc/luvref.txt diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt index e9fd2888ac..04e31e0680 100644 --- a/runtime/doc/help.txt +++ b/runtime/doc/help.txt @@ -187,6 +187,7 @@ Other ~ |dev_style.txt| Nvim style guide |job_control.txt| Spawn and control multiple processes |luaref.txt| Lua reference manual +|luvref.txt| Luv (|vim.loop|) reference manual *standard-plugin-list* Standard plugins ~ diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 52d25d82e6..5f6a1e4d73 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -516,8 +516,8 @@ management. Try this command to see available functions: > :lua print(vim.inspect(vim.loop)) < -Reference: https://github.com/luvit/luv/blob/master/docs.md -Examples: https://github.com/luvit/luv/tree/master/examples +Internally, `vim.loop` wraps the "luv" Lua bindings for the LibUV library; +see |luv-intro| for a full reference manual. *E5560* *lua-loop-callbacks* It is an error to directly invoke `vim.api` functions (except |api-fast|) in diff --git a/runtime/doc/luvref.txt b/runtime/doc/luvref.txt new file mode 100644 index 0000000000..ee45444b42 --- /dev/null +++ b/runtime/doc/luvref.txt @@ -0,0 +1,3898 @@ +*luvref.txt* Nvim + + + LUV REFERENCE MANUAL + + +This file documents the Lua bindings for the LibUV library which is used for +Nvim's event-loop and is accessible from Lua via |vim.loop| (e.g., |uv.version()| +is exposed as `vim.loop.version()`). + +For information about this manual, see |luv-credits|. + +For further examples, see https://github.com/luvit/luv/tree/master/examples. + +============================================================================== +INTRODUCTION *luv* *luv-intro* *uv* + +The luv (https://github.com/luvit/luv) project provides access to the +multi-platform support library libuv (https://github.com/libuv/libuv) in Lua +code. It was primarily developed for the luvit +(https://github.com/luvit/luvit) project as the built-in `uv` module, but can +be used in other Lua environments. + +More information about the core libuv library can be found at the original +libuv documentation page (https://docs.libuv.org/). + +TCP Echo Server Example~ + +Here is a small example showing a TCP echo server: + + > + local uv = vim.loop + + local server = uv.new_tcp() + server:bind("127.0.0.1", 1337) + server:listen(128, function (err) + assert(not err, err) + local client = uv.new_tcp() + server:accept(client) + client:read_start(function (err, chunk) + assert(not err, err) + if chunk then + client:write(chunk) + else + client:shutdown() + client:close() + end + end) + end) + print("TCP server listening at 127.0.0.1 port 1337") + uv.run() -- an explicit run call is necessary outside of luvit +< + +Module Layout~ + +The luv library contains a single Lua module referred to hereafter as `uv` for +simplicity. This module consists mostly of functions with names corresponding +to their original libuv versions. For example, the libuv function +`uv_tcp_bind` has a luv version at |uv.tcp_bind()|. Currently, only one +non-function field exists: `uv.constants`, which is a table. + +Functions vs Methods~ + +In addition to having simple functions, luv provides an optional method-style +API. For example, `uv.tcp_bind(server, host, port)` can alternatively be +called as `server:bind(host, port)` . Note that the first argument `server` +becomes the object and `tcp_` is removed from the function name. Method forms +are documented below where they exist. + +Synchronous vs Asynchronous Functions~ + +Functions that accept a callback are asynchronous. These functions may +immediately return results to the caller to indicate their initial status, but +their final execution is deferred until at least the next libuv loop +iteration. After completion, their callbacks are executed with any results +passed to it. + +Functions that do not accept a callback are synchronous. These functions +immediately return their results to the caller. + +Some (generally FS and DNS) functions can behave either synchronously or +asynchronously. If a callback is provided to these functions, they behave +asynchronously; if no callback is provided, they behave synchronously. + +Pseudo-Types~ + +Some unique types are defined. These are not actual types in Lua, but they are +used here to facilitate documenting consistent behavior: +- `fail`: an assertable `nil, string, string` tuple (see |luv-error-handling|) +- `callable`: a `function`; or a `table` or `userdata` with a `__call` + metamethod +- `buffer`: a `string` or a sequential `table` of `string`s +- `threadargs`: variable arguments (`...`) of type `nil`, `boolean`, `number`, + `string`, or `userdata` + +============================================================================== +CONTENTS *luv-contents* + +This documentation is mostly a retelling of the libuv API documentation +(http://docs.libuv.org/en/v1.x/api.html) within the context of luv's Lua API. +Low-level implementation details and unexposed C functions and types are not +documented here except for when they are relevant to behavior seen in the Lua +module. + +- |luv-error-handling| — Error handling +- |luv-version-checking| — Version checking +- |uv_loop_t| — Event loop +- |uv_req_t| — Base request +- |uv_handle_t| — Base handle + - |uv_timer_t| — Timer handle + - |uv_prepare_t| — Prepare handle + - |uv_check_t| — Check handle + - |uv_idle_t| — Idle handle + - |uv_async_t| — Async handle + - |uv_poll_t| — Poll handle + - |uv_signal_t| — Signal handle + - |uv_process_t| — Process handle + - |uv_stream_t| — Stream handle + - |uv_tcp_t| — TCP handle + - |uv_pipe_t| — Pipe handle + - |uv_tty_t| — TTY handle + - |uv_udp_t| — UDP handle + - |uv_fs_event_t| — FS Event handle + - |uv_fs_poll_t| — FS Poll handle +- |luv-file-system-operations| — File system operations +- |luv-thread-pool-work-scheduling| — Thread pool work scheduling +- |luv-dns-utility-functions| — DNS utility functions +- |luv-threading-and-synchronization-utilities| — Threading and + synchronization utilities +- |luv-miscellaneous-utilities| — Miscellaneous utilities +- |luv-metrics-operations| — Metrics operations + +============================================================================== +ERROR HANDLING *luv-error-handling* + +In libuv, errors are negative numbered constants; however, these errors and +the functions used to handle them are not exposed to luv users. Instead, if an +internal error is encountered, the luv function will return to the caller an +assertable `nil, err, name` tuple. + +- `nil` idiomatically indicates failure +- `err` is a string with the format `{name}: {message}` + - `{name}` is the error name provided internally by `uv_err_name` + - `{message}` is a human-readable message provided internally by + `uv_strerror` +- `name` is the same string used to construct `err` + +This tuple is referred to below as the `fail` pseudo-type. + +When a function is called successfully, it will return either a value that is +relevant to the operation of the function, or the integer `0` to indicate +success, or sometimes nothing at all. These cases are documented below. + +============================================================================== +VERSION CHECKING *luv-version-checking* + +uv.version() *uv.version()* + + Returns the libuv version packed into a single integer. 8 bits + are used for each component, with the patch number stored in + the 8 least significant bits. For example, this would be + 0x010203 in libuv 1.2.3. + + Returns: `integer` + +uv.version_string() *uv.version_string()* + + Returns the libuv version number as a string. For example, + this would be "1.2.3" in libuv 1.2.3. For non-release + versions, the version suffix is included. + + Returns: `string` + +============================================================================== +`uv_loop_t` — Event loop *luv-event-loop* *uv_loop_t* + +The event loop is the central part of libuv's functionality. It takes care of +polling for I/O and scheduling callbacks to be run based on different sources +of events. + +In luv, there is an implicit uv loop for every Lua state that loads the +library. You can use this library in an multi-threaded environment as long as +each thread has it's own Lua state with its corresponding own uv loop. This +loop is not directly exposed to users in the Lua module. + +uv.loop_close() *uv.loop_close()* + + Closes all internal loop resources. In normal execution, the + loop will automatically be closed when it is garbage collected + by Lua, so it is not necessary to explicitly call + `loop_close()`. Call this function only after the loop has + finished executing and all open handles and requests have been + closed, or it will return `EBUSY`. + + Returns: `0` or `fail` + +uv.run([{mode}]) *uv.run()* + + Parameters: + - `mode`: `string` or `nil` (default: `"default"`) + + This function runs the event loop. It will act differently + depending on the specified mode: + + - `"default"`: Runs the event loop until there are no more + active and referenced handles or requests. Returns `true` + if |uv.stop()| was called and there are still active + handles or requests. Returns `false` in all other cases. + + - `"once"`: Poll for I/O once. Note that this function + blocks if there are no pending callbacks. Returns `false` + when done (no active handles or requests left), or `true` + if more callbacks are expected (meaning you should run the + event loop again sometime in the future). + + - `"nowait"`: Poll for I/O once but don't block if there are + no pending callbacks. Returns `false` if done (no active + handles or requests left), or `true` if more callbacks are + expected (meaning you should run the event loop again + sometime in the future). + + Returns: `boolean` or `fail` + + Note: Luvit will implicitly call `uv.run()` after loading user + code, but if you use the luv bindings directly, you need to + call this after registering your initial set of event + callbacks to start the event loop. + +uv.loop_configure({option}, {...}) *uv.loop_configure()* + + Parameters: + - `option`: `string` + - `...`: depends on `option`, see below + + Set additional loop options. You should normally call this + before the first call to uv_run() unless mentioned otherwise. + + Supported options: + + - `"block_signal"`: Block a signal when polling for new + events. The second argument to loop_configure() is the + signal name (as a lowercase string) or the signal number. + This operation is currently only implemented for + `"sigprof"` signals, to suppress unnecessary wakeups when + using a sampling profiler. Requesting other signals will + fail with `EINVAL`. + - `"metrics_idle_time"`: Accumulate the amount of idle time + the event loop spends in the event provider. This option + is necessary to use `metrics_idle_time()`. + + An example of a valid call to this function is: + + > + uv.loop_configure("block_signal", "sigprof") +< + + Returns: `0` or `fail` + + Note: Be prepared to handle the `ENOSYS` error; it means the + loop option is not supported by the platform. + +uv.loop_mode() *uv.loop_mode()* + + If the loop is running, returns a string indicating the mode + in use. If the loop is not running, `nil` is returned instead. + + Returns: `string` or `nil` + +uv.loop_alive() *uv.loop_alive()* + + Returns `true` if there are referenced active handles, active + requests, or closing handles in the loop; otherwise, `false`. + + Returns: `boolean` or `fail` + +uv.stop() *uv.stop()* + + Stop the event loop, causing |uv.run()| to end as soon as + possible. This will happen not sooner than the next loop + iteration. If this function was called before blocking for + I/O, the loop won't block for I/O on this iteration. + + Returns: Nothing. + +uv.backend_fd() *uv.backend_fd()* + + Get backend file descriptor. Only kqueue, epoll, and event + ports are supported. + + This can be used in conjunction with `uv.run("nowait")` to + poll in one thread and run the event loop's callbacks in + another + + Returns: `integer` or `nil` + + Note: Embedding a kqueue fd in another kqueue pollset doesn't + work on all platforms. It's not an error to add the fd but it + never generates events. + +uv.backend_timeout() *uv.backend_timeout()* + + Get the poll timeout. The return value is in milliseconds, or + -1 for no timeout. + + Returns: `integer` + +uv.now() *uv.now()* + + Returns the current timestamp in milliseconds. The timestamp + is cached at the start of the event loop tick, see + |uv.update_time()| for details and rationale. + + The timestamp increases monotonically from some arbitrary + point in time. Don't make assumptions about the starting + point, you will only get disappointed. + + Returns: `integer` + + Note: Use |uv.hrtime()| if you need sub-millisecond + granularity. + +uv.update_time() *uv.update_time()* + + Update the event loop's concept of "now". Libuv caches the + current time at the start of the event loop tick in order to + reduce the number of time-related system calls. + + You won't normally need to call this function unless you have + callbacks that block the event loop for longer periods of + time, where "longer" is somewhat subjective but probably on + the order of a millisecond or more. + + Returns: Nothing. + +uv.walk({callback}) *uv.walk()* + + Parameters: + - `callback`: `callable` + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Walk the list of handles: `callback` will be executed with + each handle. + + Returns: Nothing. + + > + -- Example usage of uv.walk to close all handles that + -- aren't already closing. + uv.walk(function (handle) + if not handle:is_closing() then + handle:close() + end + end) +< + +============================================================================== +`uv_req_t` — Base request *luv-base-request* *uv_req_t* + +`uv_req_t` is the base type for all libuv request types. + +uv.cancel({req}) *uv.cancel()* + + > method form `req:cancel()` + + Parameters: + - `req`: `userdata` for sub-type of |uv_req_t| + + Cancel a pending request. Fails if the request is executing or + has finished executing. Only cancellation of |uv_fs_t|, + `uv_getaddrinfo_t`, `uv_getnameinfo_t` and `uv_work_t` + requests is currently supported. + + Returns: `0` or `fail` + +uv.req_get_type({req}) *uv.req_get_type()* + + > method form `req:get_type()` + + Parameters: + - `req`: `userdata` for sub-type of |uv_req_t| + + Returns the name of the struct for a given request (e.g. + `"fs"` for |uv_fs_t|) and the libuv enum integer for the + request's type (`uv_req_type`). + + Returns: `string, integer` + +============================================================================== +`uv_handle_t` — Base handle *luv-base-handle* *uv_handle_t* + +`uv_handle_t` is the base type for all libuv handle types. All API functions +defined here work with any handle type. + +uv.is_active({handle}) *uv.is_active()* + + > method form `handle:is_active()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Returns `true` if the handle is active, `false` if it's + inactive. What "active” means depends on the type of handle: + + - A |uv_async_t| handle is always active and cannot be + deactivated, except by closing it with |uv.close()|. + + - A |uv_pipe_t|, |uv_tcp_t|, |uv_udp_t|, etc. + handle - basically any handle that deals with I/O - is + active when it is doing something that involves I/O, like + reading, writing, connecting, accepting new connections, + etc. + + - A |uv_check_t|, |uv_idle_t|, |uv_timer_t|, + etc. handle is active when it has been started with a call + to |uv.check_start()|, |uv.idle_start()|, + |uv.timer_start()| etc. until it has been stopped with a + call to its respective stop function. + + Returns: `boolean` or `fail` + +uv.is_closing({handle}) *uv.is_closing()* + + > method form `handle:is_closing()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Returns `true` if the handle is closing or closed, `false` + otherwise. + + Returns: `boolean` or `fail` + + Note: This function should only be used between the + initialization of the handle and the arrival of the close + callback. + +uv.close({handle} [, {callback}]) *uv.close()* + + > method form `handle:close([callback])` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + - `callback`: `callable` or `nil` + + Request handle to be closed. `callback` will be called + asynchronously after this call. This MUST be called on each + handle before memory is released. + + Handles that wrap file descriptors are closed immediately but + `callback` will still be deferred to the next iteration of the + event loop. It gives you a chance to free up any resources + associated with the handle. + + In-progress requests, like `uv_connect_t` or `uv_write_t`, are + cancelled and have their callbacks called asynchronously with + `ECANCELED`. + + Returns: Nothing. + +uv.ref({handle}) *uv.ref()* + + > method form `handle:ref()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Reference the given handle. References are idempotent, that + is, if a handle is already referenced calling this function + again will have no effect. + + Returns: Nothing. + + See |luv-reference-counting|. + +uv.unref({handle}) *uv.unref()* + + > method form `handle:unref()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Un-reference the given handle. References are idempotent, that + is, if a handle is not referenced calling this function again + will have no effect. + + Returns: Nothing. + +See |luv-reference-counting|. + +uv.has_ref({handle}) *uv.has_ref()* + + > method form `handle:has_ref()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Returns `true` if the handle referenced, `false` if not. + + Returns: `boolean` or `fail` + + See |luv-reference-counting|. + +uv.send_buffer_size({handle} [, {size}]) *uv.send_buffer_size()* + + > method form `handle:send_buffer_size([size])` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + - `size`: `integer` or `nil` (default: `0`) + + Gets or sets the size of the send buffer that the operating + system uses for the socket. + + If `size` is omitted (or `0`), this will return the current + send buffer size; otherwise, this will use `size` to set the + new send buffer size. + + This function works for TCP, pipe and UDP handles on Unix and + for TCP and UDP handles on Windows. + + Returns: + - `integer` or `fail` (if `size` is `nil` or `0`) + - `0` or `fail` (if `size` is not `nil` and not `0`) + + Note: Linux will set double the size and return double the + size of the original set value. + +uv.recv_buffer_size({handle} [, {size}]) *uv.recv_buffer_size()* + + > method form `handle:recv_buffer_size([size])` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + - `size`: `integer` or `nil` (default: `0`) + + Gets or sets the size of the receive buffer that the operating + system uses for the socket. + + If `size` is omitted (or `0`), this will return the current + send buffer size; otherwise, this will use `size` to set the + new send buffer size. + + This function works for TCP, pipe and UDP handles on Unix and + for TCP and UDP handles on Windows. + + Returns: + - `integer` or `fail` (if `size` is `nil` or `0`) + - `0` or `fail` (if `size` is not `nil` and not `0`) + + Note: Linux will set double the size and return double the + size of the original set value. + +uv.fileno({handle}) *uv.fileno()* + + > method form `handle:fileno()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Gets the platform dependent file descriptor equivalent. + + The following handles are supported: TCP, pipes, TTY, UDP and + poll. Passing any other handle type will fail with `EINVAL`. + + If a handle doesn't have an attached file descriptor yet or + the handle itself has been closed, this function will return + `EBADF`. + + Returns: `integer` or `fail` + + WARNING: Be very careful when using this function. libuv + assumes it's in control of the file descriptor so any change + to it may lead to malfunction. + +uv.handle_get_type({handle}) *uv.handle_get_type()* + + > method form `handle:get_type()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Returns the name of the struct for a given handle (e.g. + `"pipe"` for |uv_pipe_t|) and the libuv enum integer for the + handle's type (`uv_handle_type`). + + Returns: `string, integer` + +============================================================================== +REFERENCE COUNTING *luv-reference-counting* + +The libuv event loop (if run in the default mode) will run until there are no +active and referenced handles left. The user can force the loop to exit early +by unreferencing handles which are active, for example by calling |uv.unref()| +after calling |uv.timer_start()|. + +A handle can be referenced or unreferenced, the refcounting scheme doesn't use +a counter, so both operations are idempotent. + +All handles are referenced when active by default, see |uv.is_active()| for a +more detailed explanation on what being active involves. + +============================================================================== +`uv_timer_t` — Timer handle *luv-timer-handle* *uv_timer_t* + +> |uv_handle_t| functions also apply. + +Timer handles are used to schedule callbacks to be called in the future. + +uv.new_timer() *uv.new_timer()* + + Creates and initializes a new |uv_timer_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_timer_t userdata` or `fail` + + > + -- Creating a simple setTimeout wrapper + local function setTimeout(timeout, callback) + local timer = uv.new_timer() + timer:start(timeout, 0, function () + timer:stop() + timer:close() + callback() + end) + return timer + end + + -- Creating a simple setInterval wrapper + local function setInterval(interval, callback) + local timer = uv.new_timer() + timer:start(interval, interval, function () + callback() + end) + return timer + end + + -- And clearInterval + local function clearInterval(timer) + timer:stop() + timer:close() + end +< + +uv.timer_start({timer}, {timeout}, {repeat}, {callback}) *uv.timer_start()* + + > method form `timer:start(timeout, repeat, callback)` + + Parameters: + - `timer`: `uv_timer_t userdata` + - `timeout`: `integer` + - `repeat`: `integer` + - `callback`: `callable` + + Start the timer. `timeout` and `repeat` are in milliseconds. + + If `timeout` is zero, the callback fires on the next event + loop iteration. If `repeat` is non-zero, the callback fires + first after `timeout` milliseconds and then repeatedly after + `repeat` milliseconds. + + Returns: `0` or `fail` + +uv.timer_stop({timer}) *uv.timer_stop()* + + > method form `timer:stop()` + + Parameters: + - `timer`: `uv_timer_t userdata` + + Stop the timer, the callback will not be called anymore. + + Returns: `0` or `fail` + +uv.timer_again({timer}) *uv.timer_again()* + + > method form `timer:again()` + + Parameters: + - `timer`: `uv_timer_t userdata` + + Stop the timer, and if it is repeating restart it using the + repeat value as the timeout. If the timer has never been + started before it raises `EINVAL`. + + Returns: `0` or `fail` + +uv.timer_set_repeat({timer}, {repeat}) *uv.timer_set_repeat()* + + > method form `timer:set_repeat(repeat)` + + Parameters: + - `timer`: `uv_timer_t userdata` + - `repeat`: `integer` + + Set the repeat interval value in milliseconds. The timer will + be scheduled to run on the given interval, regardless of the + callback execution duration, and will follow normal timer + semantics in the case of a time-slice overrun. + + For example, if a 50 ms repeating timer first runs for 17 ms, + it will be scheduled to run again 33 ms later. If other tasks + consume more than the 33 ms following the first timer + callback, then the callback will run as soon as possible. + + Returns: Nothing. + +uv.timer_get_repeat({timer}) *uv.timer_get_repeat()* + + > method form `timer:get_repeat()` + + Parameters: + - `timer`: `uv_timer_t userdata` + + Get the timer repeat value. + + Returns: `integer` + +uv.timer_get_due_in({timer}) *uv.timer_get_due_in()* + + > method form `timer:get_due_in()` + + Parameters: + - `timer`: `uv_timer_t userdata` + + Get the timer due value or 0 if it has expired. The time is + relative to |uv.now()|. + + Returns: `integer` + + Note: New in libuv version 1.40.0. + +============================================================================== +`uv_prepare_t` — Prepare handle *luv-prepare-handle* *uv_prepare_t* + +> |uv_handle_t| functions also apply. + +Prepare handles will run the given callback once per loop iteration, right +before polling for I/O. + + > + local prepare = uv.new_prepare() + prepare:start(function() + print("Before I/O polling") + end) +< + +uv.new_prepare() *uv.new_prepare()* + + Creates and initializes a new |uv_prepare_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_prepare_t userdata` or `fail` + +uv.prepare_start({prepare}, {callback}) *uv.prepare_start()* + + > method form `prepare:start(callback)` + + Parameters: + - `prepare`: `uv_prepare_t userdata` + - `callback`: `callable` + + Start the handle with the given callback. + + Returns: `0` or `fail` + +uv.prepare_stop({prepare}) *uv.prepare_stop()* + + > method form `prepare:stop()` + + Parameters: + - `prepare`: `uv_prepare_t userdata` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_check_t` — Check handle *luv-check-handle* *uv_check_t* + +> |uv_handle_t| functions also apply. + +Check handles will run the given callback once per loop iteration, right after +polling for I/O. + + > + local check = uv.new_check() + check:start(function() + print("After I/O polling") + end) +< + +uv.new_check() *uv.new_check()* + + Creates and initializes a new |uv_check_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_check_t userdata` or `fail` + +uv.check_start({check}, {callback}) *uv.check_start()* + + > method form `check:start(callback)` + + Parameters: + - `check`: `uv_check_t userdata` + - `callback`: `callable` + + Start the handle with the given callback. + + Returns: `0` or `fail` + +uv.check_stop({check}) *uv.check_stop()* + + > method form `check:stop()` + + Parameters: + - `check`: `uv_check_t userdata` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_idle_t` — Idle handle *luv-idle-handle* *uv_idle_t* + +> |uv_handle_t| functions also apply. + +Idle handles will run the given callback once per loop iteration, right before +the |uv_prepare_t| handles. + +Note: The notable difference with prepare handles is that when there are +active idle handles, the loop will perform a zero timeout poll instead of +blocking for I/O. + +WARNING: Despite the name, idle handles will get their callbacks called on +every loop iteration, not when the loop is actually "idle". + + > + local idle = uv.new_idle() + idle:start(function() + print("Before I/O polling, no blocking") + end) +< + +uv.new_idle() *uv.new_idle()* + + Creates and initializes a new |uv_idle_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_idle_t userdata` or `fail` + +uv.idle_start({idle}, {callback}) *uv.idle_start()* + + > method form `idle:start(callback)` + + Parameters: + - `idle`: `uv_idle_t userdata` + - `callback`: `callable` + + Start the handle with the given callback. + + Returns: `0` or `fail` + +uv.idle_stop({check}) *uv.idle_stop()* + + > method form `idle:stop()` + + Parameters: + - `idle`: `uv_idle_t userdata` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_async_t` — Async handle *luv-async-handle* *uv_async_t* + +> |uv_handle_t| functions also apply. + +Async handles allow the user to "wakeup" the event loop and get a callback +called from another thread. + + > + local async + async = uv.new_async(function() + print("async operation ran") + async:close() + end) + + async:send() +< + +uv.new_async([{callback}]) *uv.new_async()* + + Parameters: + - `callback`: `callable` or `nil` + - `...`: `threadargs` passed to/from + `uv.async_send(async, ...)` + + Creates and initializes a new |uv_async_t|. Returns the Lua + userdata wrapping it. A `nil` callback is allowed. + + Returns: `uv_async_t userdata` or `fail` + + Note: Unlike other handle initialization functions, this + immediately starts the handle. + +uv.async_send({async}, {...}) *uv.async_send()* + + > method form `async:send(...)` + + Parameters: + - `async`: `uv_async_t userdata` + - `...`: `threadargs` + + Wakeup the event loop and call the async handle's callback. + + Returns: `0` or `fail` + + Note: It's safe to call this function from any thread. The + callback will be called on the loop thread. + + WARNING: libuv will coalesce calls to `uv.async_send(async)`, + that is, not every call to it will yield an execution of the + callback. For example: if `uv.async_send()` is called 5 times + in a row before the callback is called, the callback will only + be called once. If `uv.async_send()` is called again after the + callback was called, it will be called again. + +============================================================================== +`uv_poll_t` — Poll handle *luv-poll-handle* *uv_poll_t* + +> |uv_handle_t| functions also apply. + +Poll handles are used to watch file descriptors for readability and +writability, similar to the purpose of poll(2) +(http://linux.die.net/man/2/poll). + +The purpose of poll handles is to enable integrating external libraries that +rely on the event loop to signal it about the socket status changes, like +c-ares or libssh2. Using `uv_poll_t` for any other purpose is not recommended; +|uv_tcp_t|, |uv_udp_t|, etc. provide an implementation that is faster and more +scalable than what can be achieved with `uv_poll_t`, especially on Windows. + +It is possible that poll handles occasionally signal that a file descriptor is +readable or writable even when it isn't. The user should therefore always be +prepared to handle EAGAIN or equivalent when it attempts to read from or write +to the fd. + +It is not okay to have multiple active poll handles for the same socket, this +can cause libuv to busyloop or otherwise malfunction. + +The user should not close a file descriptor while it is being polled by an +active poll handle. This can cause the handle to report an error, but it might +also start polling another socket. However the fd can be safely closed +immediately after a call to |uv.poll_stop()| or |uv.close()|. + +Note: On windows only sockets can be polled with poll handles. On Unix any +file descriptor that would be accepted by poll(2) can be used. + +uv.new_poll({fd}) *uv.new_poll()* + + Parameters: + - `fd`: `integer` + + Initialize the handle using a file descriptor. + + The file descriptor is set to non-blocking mode. + + Returns: `uv_poll_t userdata` or `fail` + +uv.new_socket_poll({fd}) *uv.new_socket_poll()* + + Parameters: + - `fd`: `integer` + + Initialize the handle using a socket descriptor. On Unix this + is identical to |uv.new_poll()|. On windows it takes a SOCKET + handle. + + The socket is set to non-blocking mode. + + Returns: `uv_poll_t userdata` or `fail` + +uv.poll_start({poll}, {events}, {callback}) *uv.poll_start()* + + > method form `poll:start(events, callback)` + + Parameters: + - `poll`: `uv_poll_t userdata` + - `events`: `string` or `nil` (default: `"rw"`) + - `callback`: `callable` + - `err`: `nil` or `string` + - `events`: `string` or `nil` + + Starts polling the file descriptor. `events` are: `"r"`, + `"w"`, `"rw"`, `"d"`, `"rd"`, `"wd"`, `"rwd"`, `"p"`, `"rp"`, + `"wp"`, `"rwp"`, `"dp"`, `"rdp"`, `"wdp"`, or `"rwdp"` where + `r` is `READABLE`, `w` is `WRITABLE`, `d` is `DISCONNECT`, and + `p` is `PRIORITIZED`. As soon as an event is detected the + callback will be called with status set to 0, and the detected + events set on the events field. + + The user should not close the socket while the handle is + active. If the user does that anyway, the callback may be + called reporting an error status, but this is not guaranteed. + + Returns: `0` or `fail` + + Note Calling `uv.poll_start()` on a handle that is already + active is fine. Doing so will update the events mask that is + being watched for. + +uv.poll_stop({poll}) *uv.poll_stop()* + + > method form `poll:stop()` + + Parameters: + - `poll`: `uv_poll_t userdata` + + Stop polling the file descriptor, the callback will no longer + be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_signal_t` — Signal handle *luv-signal-handle* *uv_signal_t* + +> |uv_handle_t| functions also apply. + +Signal handles implement Unix style signal handling on a per-event loop bases. + +Windows Notes: + +Reception of some signals is emulated on Windows: + - SIGINT is normally delivered when the user presses CTRL+C. However, like + on Unix, it is not generated when terminal raw mode is enabled. + - SIGBREAK is delivered when the user pressed CTRL + BREAK. + - SIGHUP is generated when the user closes the console window. On SIGHUP the + program is given approximately 10 seconds to perform cleanup. After that + Windows will unconditionally terminate it. + - SIGWINCH is raised whenever libuv detects that the console has been + resized. SIGWINCH is emulated by libuv when the program uses a uv_tty_t + handle to write to the console. SIGWINCH may not always be delivered in a + timely manner; libuv will only detect size changes when the cursor is + being moved. When a readable |uv_tty_t| handle is used in raw mode, + resizing the console buffer will also trigger a SIGWINCH signal. + - Watchers for other signals can be successfully created, but these signals + are never received. These signals are: SIGILL, SIGABRT, SIGFPE, SIGSEGV, + SIGTERM and SIGKILL. + - Calls to raise() or abort() to programmatically raise a signal are not + detected by libuv; these will not trigger a signal watcher. + +Unix Notes: + + - SIGKILL and SIGSTOP are impossible to catch. + - Handling SIGBUS, SIGFPE, SIGILL or SIGSEGV via libuv results into + undefined behavior. + - SIGABRT will not be caught by libuv if generated by abort(), e.g. through + assert(). + - On Linux SIGRT0 and SIGRT1 (signals 32 and 33) are used by the NPTL + pthreads library to manage threads. Installing watchers for those signals + will lead to unpredictable behavior and is strongly discouraged. Future + versions of libuv may simply reject them. + + > + -- Create a new signal handler + local signal = uv.new_signal() + -- Define a handler function + uv.signal_start(signal, "sigint", function(signal) + print("got " .. signal .. ", shutting down") + os.exit(1) + end) +< + +uv.new_signal() *uv.new_signal()* + + Creates and initializes a new |uv_signal_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_signal_t userdata` or `fail` + +uv.signal_start({signal}, {signum}, {callback}) *uv.signal_start()* + + > method form `signal:start(signum, callback)` + + Parameters: + - `signal`: `uv_signal_t userdata` + - `signum`: `integer` or `string` + - `callback`: `callable` + - `signum`: `string` + + Start the handle with the given callback, watching for the + given signal. + + Returns: `0` or `fail` + *uv.signal_start_oneshot()* +uv.signal_start_oneshot({signal}, {signum}, {callback}) + + > method form `signal:start_oneshot(signum, callback)` + + Parameters: + - `signal`: `uv_signal_t userdata` + - `signum`: `integer` or `string` + - `callback`: `callable` + - `signum`: `string` + + Same functionality as |uv.signal_start()| but the signal + handler is reset the moment the signal is received. + + Returns: `0` or `fail` + +uv.signal_stop({signal}) *uv.signal_stop()* + + > method form `signal:stop()` + + Parameters: + - `signal`: `uv_signal_t userdata` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_process_t` — Process handle *luv-process-handle* *uv_process_t* + +> |uv_handle_t| functions also apply. + +Process handles will spawn a new process and allow the user to control it and +establish communication channels with it using streams. + +uv.disable_stdio_inheritance() *uv.disable_stdio_inheritance()* + + Disables inheritance for file descriptors / handles that this + process inherited from its parent. The effect is that child + processes spawned by this process don't accidentally inherit + these handles. + + It is recommended to call this function as early in your + program as possible, before the inherited file descriptors can + be closed or duplicated. + + Returns: Nothing. + + Note: This function works on a best-effort basis: there is no + guarantee that libuv can discover all file descriptors that + were inherited. In general it does a better job on Windows + than it does on Unix. + +uv.spawn({path}, {options}, {on_exit}) *uv.spawn()* + + Parameters: + - `path`: `string` + - `options`: `table` (see below) + - `on_exit`: `callable` + - `code`: `integer` + - `signal`: `integer` + + Initializes the process handle and starts the process. If the + process is successfully spawned, this function will return the + handle and pid of the child process. + + Possible reasons for failing to spawn would include (but not + be limited to) the file to execute not existing, not having + permissions to use the setuid or setgid specified, or not + having enough memory to allocate for the new process. + + > + local stdin = uv.new_pipe() + local stdout = uv.new_pipe() + local stderr = uv.new_pipe() + + print("stdin", stdin) + print("stdout", stdout) + print("stderr", stderr) + + local handle, pid = uv.spawn("cat", { + stdio = {stdin, stdout, stderr} + }, function(code, signal) -- on exit + print("exit code", code) + print("exit signal", signal) + end) + + print("process opened", handle, pid) + + uv.read_start(stdout, function(err, data) + assert(not err, err) + if data then + print("stdout chunk", stdout, data) + else + print("stdout end", stdout) + end + end) + + uv.read_start(stderr, function(err, data) + assert(not err, err) + if data then + print("stderr chunk", stderr, data) + else + print("stderr end", stderr) + end + end) + + uv.write(stdin, "Hello World") + + uv.shutdown(stdin, function() + print("stdin shutdown", stdin) + uv.close(handle, function() + print("process closed", handle, pid) + end) + end) +< + *uv.spawn-options* + The `options` table accepts the following fields: + + - `options.args` - Command line arguments as a list of + string. The first string should be the path to the + program. On Windows, this uses CreateProcess which + concatenates the arguments into a string. This can cause + some strange errors. (See `options.verbatim` below for + Windows.) + - `options.stdio` - Set the file descriptors that will be + made available to the child process. The convention is + that the first entries are stdin, stdout, and stderr. + (Note: On Windows, file descriptors after the third are + available to the child process only if the child processes + uses the MSVCRT runtime.) + - `options.env` - Set environment variables for the new + process. + - `options.cwd` - Set the current working directory for the + sub-process. + - `options.uid` - Set the child process' user id. + - `options.gid` - Set the child process' group id. + - `options.verbatim` - If true, do not wrap any arguments in + quotes, or perform any other escaping, when converting the + argument list into a command line string. This option is + only meaningful on Windows systems. On Unix it is silently + ignored. + - `options.detached` - If true, spawn the child process in a + detached state - this will make it a process group leader, + and will effectively enable the child to keep running + after the parent exits. Note that the child process will + still keep the parent's event loop alive unless the parent + process calls |uv.unref()| on the child's process handle. + - `options.hide` - If true, hide the subprocess console + window that would normally be created. This option is only + meaningful on Windows systems. On Unix it is silently + ignored. + + The `options.stdio` entries can take many shapes. + + - If they are numbers, then the child process inherits that + same zero-indexed fd from the parent process. + - If |uv_stream_t| handles are passed in, those are used as + a read-write pipe or inherited stream depending if the + stream has a valid fd. + - Including `nil` placeholders means to ignore that fd in + the child process. + + When the child process exits, `on_exit` is called with an exit + code and signal. + + Returns: `uv_process_t userdata`, `integer` + +uv.process_kill({process}, {signum}) *uv.process_kill()* + + > method form `process:kill(signum)` + + Parameters: + - `process`: `uv_process_t userdata` + - `signum`: `integer` or `string` + + Sends the specified signal to the given process handle. Check + the documentation on |uv_signal_t| for signal support, + specially on Windows. + + Returns: `0` or `fail` + +uv.kill({pid}, {signum}) *uv.kill()* + + Parameters: + - `pid`: `integer` + - `signum`: `integer` or `string` + + Sends the specified signal to the given PID. Check the + documentation on |uv_signal_t| for signal support, specially + on Windows. + + Returns: `0` or `fail` + +uv.process_get_pid({process}) *uv.process_get_pid()* + + > method form `process:get_pid()` + + Parameters: + - `process`: `uv_process_t userdata` + + Returns the handle's pid. + + Returns: `integer` + +============================================================================== +`uv_stream_t` — Stream handle *luv-stream-handle* *uv_stream_t* + +> |uv_handle_t| functions also apply. + +Stream handles provide an abstraction of a duplex communication channel. +`uv_stream_t` is an abstract type, libuv provides 3 stream implementations +in the form of |uv_tcp_t|, |uv_pipe_t| and |uv_tty_t|. + +uv.shutdown({stream} [, {callback}]) *uv.shutdown()* + + > method form `stream:shutdown([callback])` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `callback`: `callable` or `nil` + - `err`: `nil` or `string` + + Shutdown the outgoing (write) side of a duplex stream. It + waits for pending write requests to complete. The callback is + called after shutdown is complete. + + Returns: `uv_shutdown_t userdata` or `fail` + +uv.listen({stream}, {backlog}, {callback}) *uv.listen()* + + > method form `stream:listen(backlog, callback)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `backlog`: `integer` + - `callback`: `callable` + - `err`: `nil` or `string` + + Start listening for incoming connections. `backlog` indicates + the number of connections the kernel might queue, same as + `listen(2)`. When a new incoming connection is received the + callback is called. + + Returns: `0` or `fail` + +uv.accept({stream}, {client_stream}) *uv.accept()* + + > method form `stream:accept(client_stream)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `client_stream`: `userdata` for sub-type of |uv_stream_t| + + This call is used in conjunction with |uv.listen()| to accept + incoming connections. Call this function after receiving a + callback to accept the connection. + + When the connection callback is called it is guaranteed that + this function will complete successfully the first time. If + you attempt to use it more than once, it may fail. It is + suggested to only call this function once per connection call. + + Returns: `0` or `fail` + + > + server:listen(128, function (err) + local client = uv.new_tcp() + server:accept(client) + end) +< + +uv.read_start({stream}, {callback}) *uv.read_start()* + + > method form `stream:read_start(callback)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `callback`: `callable` + - `err`: `nil` or `string` + - `data`: `string` or `nil` + + Read data from an incoming stream. The callback will be made + several times until there is no more data to read or + |uv.read_stop()| is called. When we've reached EOF, `data` + will be `nil`. + + Returns: `0` or `fail` + + > + stream:read_start(function (err, chunk) + if err then + -- handle read error + elseif chunk then + -- handle data + else + -- handle disconnect + end + end) +< + +uv.read_stop({stream}) *uv.read_stop()* + + > method form `stream:read_stop()` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + + Stop reading data from the stream. The read callback will no + longer be called. + + This function is idempotent and may be safely called on a + stopped stream. + + Returns: `0` or `fail` + +uv.write({stream}, {data} [, {callback}]) *uv.write()* + + > method form `stream:write(data, [callback])` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `data`: `buffer` + - `callback`: `callable` or `nil` + - `err`: `nil` or `string` + + Write data to stream. + + `data` can either be a Lua string or a table of strings. If a + table is passed in, the C backend will use writev to send all + strings in a single system call. + + The optional `callback` is for knowing when the write is + complete. + + Returns: `uv_write_t userdata` or `fail` + +uv.write2({stream}, {data}, {send_handle} [, {callback}]) *uv.write2()* + + > method form `stream:write2(data, send_handle, [callback])` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `data`: `buffer` + - `send_handle`: `userdata` for sub-type of |uv_stream_t| + - `callback`: `callable` or `nil` + - `err`: `nil` or `string` + + Extended write function for sending handles over a pipe. The + pipe must be initialized with `ipc` option `true`. + + Returns: `uv_write_t userdata` or `fail` + + Note: `send_handle` must be a TCP socket or pipe, which is a + server or a connection (listening or connected state). Bound + sockets or pipes will be assumed to be servers. + +uv.try_write({stream}, {data}) *uv.try_write()* + + > method form `stream:try_write(data)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `data`: `buffer` + + Same as |uv.write()|, but won't queue a write request if it + can't be completed immediately. + + Will return number of bytes written (can be less than the + supplied buffer size). + + Returns: `integer` or `fail` + +uv.try_write2({stream}, {data}, {send_handle}) *uv.try_write2()* + + > method form `stream:try_write2(data, send_handle)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `data`: `buffer` + - `send_handle`: `userdata` for sub-type of |uv_stream_t| + + Like |uv.write2()|, but with the properties of + |uv.try_write()|. Not supported on Windows, where it returns + `UV_EAGAIN`. + + Will return number of bytes written (can be less than the + supplied buffer size). + + Returns: `integer` or `fail` + +uv.is_readable({stream}) *uv.is_readable()* + + > method form `stream:is_readable()` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + + Returns `true` if the stream is readable, `false` otherwise. + + Returns: `boolean` + +uv.is_writable({stream}) *uv.is_writable()* + + > method form `stream:is_writable()` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + + Returns `true` if the stream is writable, `false` otherwise. + + Returns: `boolean` + +uv.stream_set_blocking({stream}, {blocking}) *uv.stream_set_blocking()* + + > method form `stream:set_blocking(blocking)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `blocking`: `boolean` + + Enable or disable blocking mode for a stream. + + When blocking mode is enabled all writes complete + synchronously. The interface remains unchanged otherwise, e.g. + completion or failure of the operation will still be reported + through a callback which is made asynchronously. + + Returns: `0` or `fail` + + WARNING: Relying too much on this API is not recommended. It + is likely to change significantly in the future. Currently + this only works on Windows and only for |uv_pipe_t| handles. + Also libuv currently makes no ordering guarantee when the + blocking mode is changed after write requests have already + been submitted. Therefore it is recommended to set the + blocking mode immediately after opening or creating the + stream. + +uv.stream_get_write_queue_size() *uv.stream_get_write_queue_size()* + + > method form `stream:get_write_queue_size()` + + Returns the stream's write queue size. + + Returns: `integer` + +============================================================================== +`uv_tcp_t` — TCP handle *luv-tcp-handle* *uv_tcp_t* + +> |uv_handle_t| and |uv_stream_t| functions also apply. + +TCP handles are used to represent both TCP streams and servers. + +uv.new_tcp([{flags}]) *uv.new_tcp()* + + Parameters: + - `flags`: `string` or `nil` + + Creates and initializes a new |uv_tcp_t|. Returns the Lua + userdata wrapping it. Flags may be a family string: `"unix"`, + `"inet"`, `"inet6"`, `"ipx"`, `"netlink"`, `"x25"`, `"ax25"`, + `"atmpvc"`, `"appletalk"`, or `"packet"`. + + Returns: `uv_tcp_t userdata` or `fail` + +uv.tcp_open({tcp}, {sock}) *uv.tcp_open()* + + > method form `tcp:open(sock)` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `sock`: `integer` + + Open an existing file descriptor or SOCKET as a TCP handle. + + Returns: `0` or `fail` + + Note: The passed file descriptor or SOCKET is not checked for + its type, but it's required that it represents a valid stream + socket. + +uv.tcp_nodelay({tcp}, {enable}) *uv.tcp_nodelay()* + + > method form `tcp:nodelay(enable)` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `enable`: `boolean` + + Enable / disable Nagle's algorithm. + + Returns: `0` or `fail` + +uv.tcp_keepalive({tcp}, {enable} [, {delay}]) *uv.tcp_keepalive()* + + > method form `tcp:keepalive(enable, [delay])` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `enable`: `boolean` + - `delay`: `integer` or `nil` + + Enable / disable TCP keep-alive. `delay` is the initial delay + in seconds, ignored when enable is `false`. + + Returns: `0` or `fail` + +uv.tcp_simultaneous_accepts({tcp}, {enable}) *uv.tcp_simultaneous_accepts()* + + > method form `tcp:simultaneous_accepts(enable)` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `enable`: `boolean` + + Enable / disable simultaneous asynchronous accept requests + that are queued by the operating system when listening for new + TCP connections. + + This setting is used to tune a TCP server for the desired + performance. Having simultaneous accepts can significantly + improve the rate of accepting connections (which is why it is + enabled by default) but may lead to uneven load distribution + in multi-process setups. + + Returns: `0` or `fail` + +uv.tcp_bind({tcp}, {host}, {port} [, {flags}]) *uv.tcp_bind()* + + > method form `tcp:bind(host, port, [flags])` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `host`: `string` + - `port`: `integer` + - `flags`: `table` or `nil` + - `ipv6only`: `boolean` + + Bind the handle to an host and port. `host` should be an IP + address and not a domain name. Any `flags` are set with a + table with field `ipv6only` equal to `true` or `false`. + + When the port is already taken, you can expect to see an + `EADDRINUSE` error from either `uv.tcp_bind()`, |uv.listen()| + or |uv.tcp_connect()|. That is, a successful call to this + function does not guarantee that the call to |uv.listen()| or + |uv.tcp_connect()| will succeed as well. + + Use a port of `0` to let the OS assign an ephemeral port. You + can look it up later using |uv.tcp_getsockname()|. + + Returns: `0` or `fail` + +uv.tcp_getpeername({tcp}) *uv.tcp_getpeername()* + + > method form `tcp:getpeername()` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + + Get the address of the peer connected to the handle. + + Returns: `table` or `fail` + - `ip` : `string` + - `family` : `string` + - `port` : `integer` + +uv.tcp_getsockname({tcp}) *uv.tcp_getsockname()* + + > method form `tcp:getsockname()` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + + Get the current address to which the handle is bound. + + Returns: `table` or `fail` + - `ip` : `string` + - `family` : `string` + - `port` : `integer` + +uv.tcp_connect({tcp}, {host}, {port}, {callback}) *uv.tcp_connect()* + + > method form `tcp:connect(host, port, callback)` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `host`: `string` + - `port`: `integer` + - `callback`: `callable` + - `err`: `nil` or `string` + + Establish an IPv4 or IPv6 TCP connection. + + Returns: `uv_connect_t userdata` or `fail` + + > + local client = uv.new_tcp() + client:connect("127.0.0.1", 8080, function (err) + -- check error and carry on. + end) +< + +uv.tcp_write_queue_size({tcp}) *uv.tcp_write_queue_size()* + + > method form `tcp:write_queue_size()` + + DEPRECATED: Please use |uv.stream_get_write_queue_size()| + instead. + +uv.tcp_close_reset([{callback}]) *uv.tcp_close_reset()* + + > method form `tcp:close_reset([callback])` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `callback`: `callable` or `nil` + + Resets a TCP connection by sending a RST packet. This is + accomplished by setting the SO_LINGER socket option with a + linger interval of zero and then calling |uv.close()|. Due to + some platform inconsistencies, mixing of |uv.shutdown()| and + `uv.tcp_close_reset()` calls is not allowed. + + Returns: `0` or `fail` + *uv.socketpair()* +uv.socketpair([{socktype}, [{protocol}, [{flags1}, [{flags2}]]]]) + + Parameters: + - `socktype`: `string`, `integer` or `nil` (default: `stream`) + - `protocol`: `string`, `integer` or `nil` (default: 0) + - `flags1`: `table` or `nil` + - `nonblock`: `boolean` (default: `false`) + - `flags2`: `table` or `nil` + - `nonblock`: `boolean` (default: `false`) + + Create a pair of connected sockets with the specified + properties. The resulting handles can be passed to + |uv.tcp_open()|, used with |uv.spawn()|, or for any other + purpose. + + When specified as a string, `socktype` must be one of + `"stream"`, `"dgram"`, `"raw"`, `"rdm"`, or `"seqpacket"`. + + When `protocol` is set to 0 or nil, it will be automatically + chosen based on the socket's domain and type. When `protocol` + is specified as a string, it will be looked up using the + `getprotobyname(3)` function (examples: `"ip"`, `"icmp"`, + `"tcp"`, `"udp"`, etc). + + Flags: + - `nonblock`: Opens the specified socket handle for + `OVERLAPPED` or `FIONBIO`/`O_NONBLOCK` I/O usage. This is + recommended for handles that will be used by libuv, and not + usually recommended otherwise. + + Equivalent to `socketpair(2)` with a domain of `AF_UNIX`. + + Returns: `table` or `fail` + - `[1, 2]` : `integer` (file descriptor) + + > + -- Simple read/write with tcp + local fds = uv.socketpair(nil, nil, {nonblock=true}, {nonblock=true}) + + local sock1 = uv.new_tcp() + sock1:open(fds[1]) + + local sock2 = uv.new_tcp() + sock2:open(fds[2]) + + sock1:write("hello") + sock2:read_start(function(err, chunk) + assert(not err, err) + print(chunk) + end) +< + +============================================================================== +`uv_pipe_t` — Pipe handle *luv-pipe-handle* *uv_pipe_t* + +> |uv_handle_t| and |uv_stream_t| functions also apply. + +Pipe handles provide an abstraction over local domain sockets on Unix and +named pipes on Windows. + + > + local pipe = uv.new_pipe(false) + + pipe:bind('/tmp/sock.test') + + pipe:listen(128, function() + local client = uv.new_pipe(false) + pipe:accept(client) + client:write("hello!\n") + client:close() + end) +< + +uv.new_pipe([{ipc}]) *uv.new_pipe()* + + Parameters: + - `ipc`: `boolean` or `nil` (default: `false`) + + Creates and initializes a new |uv_pipe_t|. Returns the Lua + userdata wrapping it. The `ipc` argument is a boolean to + indicate if this pipe will be used for handle passing between + processes. + + Returns: `uv_pipe_t userdata` or `fail` + +uv.pipe_open({pipe}, {fd}) *uv.pipe_open()* + + > method form `pipe:open(fd)` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `fd`: `integer` + + Open an existing file descriptor or |uv_handle_t| as a + pipe. + + Returns: `0` or `fail` + + Note: The file descriptor is set to non-blocking mode. + +uv.pipe_bind({pipe}, {name}) *uv.pipe_bind()* + + > method form `pipe:bind(name)` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `name`: `string` + + Bind the pipe to a file path (Unix) or a name (Windows). + + Returns: `0` or `fail` + + Note: Paths on Unix get truncated to + sizeof(sockaddr_un.sun_path) bytes, typically between 92 and + 108 bytes. + +uv.pipe_connect({pipe}, {name} [, {callback}]) *uv.pipe_connect()* + + > method form `pipe:connect(name, [callback])` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `name`: `string` + - `callback`: `callable` or `nil` + - `err`: `nil` or `string` + + Connect to the Unix domain socket or the named pipe. + + Returns: `uv_connect_t userdata` or `fail` + + Note: Paths on Unix get truncated to + sizeof(sockaddr_un.sun_path) bytes, typically between 92 and + 108 bytes. + +uv.pipe_getsockname({pipe}) *uv.pipe_getsockname()* + + > method form `pipe:getsockname()` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + + Get the name of the Unix domain socket or the named pipe. + + Returns: `string` or `fail` + +uv.pipe_getpeername({pipe}) *uv.pipe_getpeername()* + + > method form `pipe:getpeername()` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + + Get the name of the Unix domain socket or the named pipe to + which the handle is connected. + + Returns: `string` or `fail` + +uv.pipe_pending_instances({pipe}, {count}) *uv.pipe_pending_instances()* + + > method form `pipe:pending_instances(count)` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `count`: `integer` + + Set the number of pending pipe instance handles when the pipe + server is waiting for connections. + + Returns: Nothing. + + Note: This setting applies to Windows only. + +uv.pipe_pending_count({pipe}) *uv.pipe_pending_count()* + + > method form `pipe:pending_count()` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + + Returns the pending pipe count for the named pipe. + + Returns: `integer` + +uv.pipe_pending_type({pipe}) *uv.pipe_pending_type()* + + > method form `pipe:pending_type()` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + + Used to receive handles over IPC pipes. + + First - call |uv.pipe_pending_count()|, if it's > 0 then + initialize a handle of the given type, returned by + `uv.pipe_pending_type()` and call `uv.accept(pipe, handle)` . + + Returns: `string` + +uv.pipe_chmod({pipe}, {flags}) *uv.pipe_chmod()* + + > method form `pipe:chmod(flags)` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `flags`: `string` + + Alters pipe permissions, allowing it to be accessed from + processes run by different users. Makes the pipe writable or + readable by all users. `flags` are: `"r"`, `"w"`, `"rw"`, or + `"wr"` where `r` is `READABLE` and `w` is `WRITABLE`. This + function is blocking. + + Returns: `0` or `fail` + +uv.pipe({read_flags}, {write_flags}) *uv.pipe()* + + Parameters: + - `read_flags`: `table` or `nil` + - `nonblock`: `boolean` (default: `false`) + - `write_flags`: `table` or `nil` + - `nonblock`: `boolean` (default: `false`) + + Create a pair of connected pipe handles. Data may be written + to the `write` fd and read from the `read` fd. The resulting + handles can be passed to `pipe_open`, used with `spawn`, or + for any other purpose. + + Flags: + - `nonblock`: Opens the specified socket handle for + `OVERLAPPED` or `FIONBIO`/`O_NONBLOCK` I/O usage. This is + recommended for handles that will be used by libuv, and not + usually recommended otherwise. + + Equivalent to `pipe(2)` with the `O_CLOEXEC` flag set. + + Returns: `table` or `fail` + - `read` : `integer` (file descriptor) + - `write` : `integer` (file descriptor) + + > + -- Simple read/write with pipe_open + local fds = uv.pipe({nonblock=true}, {nonblock=true}) + + local read_pipe = uv.new_pipe() + read_pipe:open(fds.read) + + local write_pipe = uv.new_pipe() + write_pipe:open(fds.write) + + write_pipe:write("hello") + read_pipe:read_start(function(err, chunk) + assert(not err, err) + print(chunk) + end) +< + +============================================================================== +`uv_tty_t` — TTY handle *luv-tty-handle* *uv_tty_t* + +> |uv_handle_t| and |uv_stream_t| functions also apply. + +TTY handles represent a stream for the console. + + > + -- Simple echo program + local stdin = uv.new_tty(0, true) + local stdout = uv.new_tty(1, false) + + stdin:read_start(function (err, data) + assert(not err, err) + if data then + stdout:write(data) + else + stdin:close() + stdout:close() + end + end) +< + +uv.new_tty({fd}, {readable}) *uv.new_tty()* + + Parameters: + - `fd`: `integer` + - `readable`: `boolean` + + Initialize a new TTY stream with the given file descriptor. + Usually the file descriptor will be: + + - 0 - stdin + - 1 - stdout + - 2 - stderr + + On Unix this function will determine the path of the fd of the + terminal using ttyname_r(3), open it, and use it if the passed + file descriptor refers to a TTY. This lets libuv put the tty + in non-blocking mode without affecting other processes that + share the tty. + + This function is not thread safe on systems that don’t support + ioctl TIOCGPTN or TIOCPTYGNAME, for instance OpenBSD and + Solaris. + + Returns: `uv_tty_t userdata` or `fail` + + Note: If reopening the TTY fails, libuv falls back to blocking + writes. + +uv.tty_set_mode({tty}, {mode}) *uv.tty_set_mode()* + + > method form `tty:set_mode(mode)` + + Parameters: + - `tty`: `uv_tty_t userdata` + - `mode`: `integer` + + Set the TTY using the specified terminal mode. + + Parameter `mode` is a C enum with the following values: + + - 0 - UV_TTY_MODE_NORMAL: Initial/normal terminal mode + - 1 - UV_TTY_MODE_RAW: Raw input mode (On Windows, + ENABLE_WINDOW_INPUT is also enabled) + - 2 - UV_TTY_MODE_IO: Binary-safe I/O mode for IPC + (Unix-only) + + Returns: `0` or `fail` + +uv.tty_reset_mode() *uv.tty_reset_mode()* + + To be called when the program exits. Resets TTY settings to + default values for the next process to take over. + + This function is async signal-safe on Unix platforms but can + fail with error code `EBUSY` if you call it when execution is + inside |uv.tty_set_mode()|. + + Returns: `0` or `fail` + +uv.tty_get_winsize({tty}) *uv.tty_get_winsize()* + + > method form `tty:get_winsize()` + + Parameters: + - `tty`: `uv_tty_t userdata` + + Gets the current Window width and height. + + Returns: `integer, integer` or `fail` + +uv.tty_set_vterm_state({state}) *uv.tty_set_vterm_state()* + + Parameters: + - `state`: `string` + + Controls whether console virtual terminal sequences are + processed by libuv or console. Useful in particular for + enabling ConEmu support of ANSI X3.64 and Xterm 256 colors. + Otherwise Windows10 consoles are usually detected + automatically. State should be one of: `"supported"` or + `"unsupported"`. + + This function is only meaningful on Windows systems. On Unix + it is silently ignored. + + Returns: none + +uv.tty_get_vterm_state() *uv.tty_get_vterm_state()* + + Get the current state of whether console virtual terminal + sequences are handled by libuv or the console. The return + value is `"supported"` or `"unsupported"`. + + This function is not implemented on Unix, where it returns + `ENOTSUP`. + + Returns: `string` or `fail` + +============================================================================== +`uv_udp_t` — UDP handle *luv-udp-handle* *uv_udp_t* + +> |uv_handle_t| functions also apply. + +UDP handles encapsulate UDP communication for both clients and servers. + +uv.new_udp([{flags}]) *uv.new_udp()* + + Parameters: + - `flags`: `table` or `nil` + - `family`: `string` or `nil` + - `mmsgs`: `integer` or `nil` (default: `1`) + + Creates and initializes a new |uv_udp_t|. Returns the Lua + userdata wrapping it. The actual socket is created lazily. + + When specified, `family` must be one of `"unix"`, `"inet"`, + `"inet6"`, `"ipx"`, `"netlink"`, `"x25"`, `"ax25"`, + `"atmpvc"`, `"appletalk"`, or `"packet"`. + + When specified, `mmsgs` determines the number of messages able + to be received at one time via `recvmmsg(2)` (the allocated + buffer will be sized to be able to fit the specified number of + max size dgrams). Only has an effect on platforms that support + `recvmmsg(2)`. + + Note: For backwards compatibility reasons, `flags` can also be + a string or integer. When it is a string, it will be treated + like the `family` key above. When it is an integer, it will be + used directly as the `flags` parameter when calling + `uv_udp_init_ex`. + + Returns: `uv_udp_t userdata` or `fail` + +uv.udp_get_send_queue_size() *uv.udp_get_send_queue_size()* + + > method form `udp:get_send_queue_size()` + + Returns the handle's send queue size. + + Returns: `integer` + +uv.udp_get_send_queue_count() *uv.udp_get_send_queue_count()* + + > method form `udp:get_send_queue_count()` + + Returns the handle's send queue count. + + Returns: `integer` + +uv.udp_open({udp}, {fd}) *uv.udp_open()* + + > method form `udp:open(fd)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `fd`: `integer` + + Opens an existing file descriptor or Windows SOCKET as a UDP + handle. + + Unix only: The only requirement of the sock argument is that + it follows the datagram contract (works in unconnected mode, + supports sendmsg()/recvmsg(), etc). In other words, other + datagram-type sockets like raw sockets or netlink sockets can + also be passed to this function. + + The file descriptor is set to non-blocking mode. + + Note: The passed file descriptor or SOCKET is not checked for + its type, but it's required that it represents a valid + datagram socket. + + Returns: `0` or `fail` + +uv.udp_bind({udp}, {host}, {port} [, {flags}]) *uv.udp_bind()* + + > method form `udp:bind(host, port, [flags])` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `host`: `string` + - `port`: `number` + - `flags`: `table` or `nil` + - `ipv6only`: `boolean` + - `reuseaddr`: `boolean` + + Bind the UDP handle to an IP address and port. Any `flags` are + set with a table with fields `reuseaddr` or `ipv6only` equal + to `true` or `false`. + + Returns: `0` or `fail` + +uv.udp_getsockname({udp}) *uv.udp_getsockname()* + + > method form `udp:getsockname()` + + Parameters: + - `udp`: `uv_udp_t userdata` + + Get the local IP and port of the UDP handle. + + Returns: `table` or `fail` + - `ip` : `string` + - `family` : `string` + - `port` : `integer` + +uv.udp_getpeername({udp}) *uv.udp_getpeername()* + + > method form `udp:getpeername()` + + Parameters: + - `udp`: `uv_udp_t userdata` + + Get the remote IP and port of the UDP handle on connected UDP + handles. + + Returns: `table` or `fail` + - `ip` : `string` + - `family` : `string` + - `port` : `integer` + + *uv.udp_set_membership()* +uv.udp_set_membership({udp}, {multicast_addr}, {interface_addr}, {membership}) + + > method form + > `udp:set_membership(multicast_addr, interface_addr, membership)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `multicast_addr`: `string` + - `interface_addr`: `string` or `nil` + - `membership`: `string` + + Set membership for a multicast address. `multicast_addr` is + multicast address to set membership for. `interface_addr` is + interface address. `membership` can be the string `"leave"` or + `"join"`. + + Returns: `0` or `fail` + + *uv.udp_set_source_membership()* +uv.udp_set_source_membership({udp}, {multicast_addr}, {interface_addr}, {source_addr}, {membership}) + + > method form + > `udp:set_source_membership(multicast_addr, interface_addr, source_addr, membership)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `multicast_addr`: `string` + - `interface_addr`: `string` or `nil` + - `source_addr`: `string` + - `membership`: `string` + + Set membership for a source-specific multicast group. + `multicast_addr` is multicast address to set membership for. + `interface_addr` is interface address. `source_addr` is source + address. `membership` can be the string `"leave"` or `"join"`. + + Returns: `0` or `fail` + +uv.udp_set_multicast_loop({udp}, {on}) *uv.udp_set_multicast_loop()* + + > method form `udp:set_multicast_loop(on)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `on`: `boolean` + + Set IP multicast loop flag. Makes multicast packets loop back + to local sockets. + + Returns: `0` or `fail` + +uv.udp_set_multicast_ttl({udp}, {ttl}) *uv.udp_set_multicast_ttl()* + + > method form `udp:set_multicast_ttl(ttl)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `ttl`: `integer` + + Set the multicast ttl. + + `ttl` is an integer 1 through 255. + + Returns: `0` or `fail` + + *uv.udp_set_multicast_interface()* +uv.udp_set_multicast_interface({udp}, {interface_addr}) + + > method form `udp:set_multicast_interface(interface_addr)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `interface_addr`: `string` + + Set the multicast interface to send or receive data on. + + Returns: `0` or `fail` + +uv.udp_set_broadcast({udp}, {on}) *uv.udp_set_broadcast()* + + > method form `udp:set_broadcast(on)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `on`: `boolean` + + Set broadcast on or off. + + Returns: `0` or `fail` + +uv.udp_set_ttl({udp}, {ttl}) *uv.udp_set_ttl()* + + > method form `udp:set_ttl(ttl)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `ttl`: `integer` + + Set the time to live. + + `ttl` is an integer 1 through 255. + + Returns: `0` or `fail` + +uv.udp_send({udp}, {data}, {host}, {port}, {callback}) *uv.udp_send()* + + > method form `udp:send(data, host, port, callback)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `data`: `buffer` + - `host`: `string` + - `port`: `integer` + - `callback`: `callable` + - `err`: `nil` or `string` + + Send data over the UDP socket. If the socket has not + previously been bound with |uv.udp_bind()| it will be bound to + `0.0.0.0` (the "all interfaces" IPv4 address) and a random + port number. + + Returns: `uv_udp_send_t userdata` or `fail` + +uv.udp_try_send({udp}, {data}, {host}, {port}) *uv.udp_try_send()* + + > method form `udp:try_send(data, host, port)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `data`: `buffer` + - `host`: `string` + - `port`: `integer` + + Same as |uv.udp_send()|, but won't queue a send request if it + can't be completed immediately. + + Returns: `integer` or `fail` + +uv.udp_recv_start({udp}, {callback}) *uv.udp_recv_start()* + + > method form `udp:recv_start(callback)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `callback`: `callable` + - `err`: `nil` or `string` + - `data`: `string` or `nil` + - `addr`: `table` or `nil` + - `ip`: `string` + - `port`: `integer` + - `family`: `string` + - `flags`: `table` + - `partial`: `boolean` or `nil` + - `mmsg_chunk`: `boolean` or `nil` + + Prepare for receiving data. If the socket has not previously + been bound with |uv.udp_bind()| it is bound to `0.0.0.0` (the + "all interfaces" IPv4 address) and a random port number. + + Returns: `0` or `fail` + +uv.udp_recv_stop({udp}) *uv.udp_recv_stop()* + + > method form `udp:recv_stop()` + + Parameters: + - `udp`: `uv_udp_t userdata` + + Stop listening for incoming datagrams. + + Returns: `0` or `fail` + +uv.udp_connect({udp}, {host}, {port}) *uv.udp_connect()* + + > method form `udp:connect(host, port)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `host`: `string` + - `port`: `integer` + + Associate the UDP handle to a remote address and port, so + every message sent by this handle is automatically sent to + that destination. Calling this function with a NULL addr + disconnects the handle. Trying to call `uv.udp_connect()` on + an already connected handle will result in an `EISCONN` error. + Trying to disconnect a handle that is not connected will + return an `ENOTCONN` error. + + Returns: `0` or `fail` + +============================================================================== +`uv_fs_event_t` — FS Event handle *luv-fs-event-handle* *uv_fs_event_t* + +> |uv_handle_t| functions also apply. + +FS Event handles allow the user to monitor a given path for changes, for +example, if the file was renamed or there was a generic change in it. This +handle uses the best backend for the job on each platform. + +uv.new_fs_event() *uv.new_fs_event()* + + Creates and initializes a new |uv_fs_event_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_fs_event_t userdata` or `fail` + +uv.fs_event_start({fs_event}, {path}, {flags}, {callback}) *uv.fs_event_start()* + + > method form `fs_event:start(path, flags, callback)` + + Parameters: + - `fs_event`: `uv_fs_event_t userdata` + - `path`: `string` + - `flags`: `table` + - `watch_entry`: `boolean` or `nil` (default: `false`) + - `stat`: `boolean` or `nil` (default: `false`) + - `recursive`: `boolean` or `nil` (default: `false`) + - `callback`: `callable` + - `err`: `nil` or `string` + - `filename`: `string` + - `events`: `table` + - `change`: `boolean` or `nil` + - `rename`: `boolean` or `nil` + + Start the handle with the given callback, which will watch the + specified path for changes. + + Returns: `0` or `fail` + +uv.fs_event_stop() *uv.fs_event_stop()* + + > method form `fs_event:stop()` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +uv.fs_event_getpath() *uv.fs_event_getpath()* + + > method form `fs_event:getpath()` + + Get the path being monitored by the handle. + + Returns: `string` or `fail` + +============================================================================== +`uv_fs_poll_t` — FS Poll handle *luv-fs-poll-handle* *uv_fs_poll_t* + +> |uv_handle_t| functions also apply. + +FS Poll handles allow the user to monitor a given path for changes. Unlike +|uv_fs_event_t|, fs poll handles use `stat` to detect when a file has changed +so they can work on file systems where fs event handles can't. + +uv.new_fs_poll() *uv.new_fs_poll()* + + Creates and initializes a new |uv_fs_poll_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_fs_poll_t userdata` or `fail` + +uv.fs_poll_start({fs_poll}, {path}, {interval}, {callback}) *uv.fs_poll_start()* + + > method form `fs_poll:start(path, interval, callback)` + + Parameters: + - `fs_event`: `uv_fs_event_t userdata` + - `path`: `string` + - `interval`: `integer` + - `callback`: `callable` + - `err`: `nil` or `string` + - `prev`: `table` or `nil` (see `uv.fs_stat`) + - `curr`: `table` or `nil` (see `uv.fs_stat`) + + Check the file at `path` for changes every `interval` + milliseconds. + + Note: For maximum portability, use multi-second intervals. + Sub-second intervals will not detect all changes on many file + systems. + + Returns: `0` or `fail` + +uv.fs_poll_stop() *uv.fs_poll_stop()* + + > method form `fs_poll:stop()` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +uv.fs_poll_getpath() *uv.fs_poll_getpath()* + + > method form `fs_poll:getpath()` + + Get the path being monitored by the handle. + + Returns: `string` or `fail` + +============================================================================== +FILE SYSTEM OPERATIONS *luv-file-system-operations* *uv_fs_t* + +Most file system functions can operate synchronously or asynchronously. When a +synchronous version is called (by omitting a callback), the function will +immediately return the results of the FS call. When an asynchronous version is +called (by providing a callback), the function will immediately return a +`uv_fs_t userdata` and asynchronously execute its callback; if an error is +encountered, the first and only argument passed to the callback will be the +`err` error string; if the operation completes successfully, the first +argument will be `nil` and the remaining arguments will be the results of the +FS call. + +Synchronous and asynchronous versions of `readFile` (with naive error +handling) are implemented below as an example: + + > + local function readFileSync(path) + local fd = assert(uv.fs_open(path, "r", 438)) + local stat = assert(uv.fs_fstat(fd)) + local data = assert(uv.fs_read(fd, stat.size, 0)) + assert(uv.fs_close(fd)) + return data + end + + local data = readFileSync("main.lua") + print("synchronous read", data) +< + + > + local function readFile(path, callback) + uv.fs_open(path, "r", 438, function(err, fd) + assert(not err, err) + uv.fs_fstat(fd, function(err, stat) + assert(not err, err) + uv.fs_read(fd, stat.size, 0, function(err, data) + assert(not err, err) + uv.fs_close(fd, function(err) + assert(not err, err) + return callback(data) + end) + end) + end) + end) + end + + readFile("main.lua", function(data) + print("asynchronous read", data) + end) +< + +uv.fs_close({fd} [, {callback}]) *uv.fs_close()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `close(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_open({path}, {flags}, {mode} [, {callback}]) *uv.fs_open()* + + Parameters: + - `path`: `string` + - `flags`: `string` or `integer` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `fd`: `integer` or `nil` + + Equivalent to `open(2)`. Access `flags` may be an integer or + one of: `"r"`, `"rs"`, `"sr"`, `"r+"`, `"rs+"`, `"sr+"`, + `"w"`, `"wx"`, `"xw"`, `"w+"`, `"wx+"`, `"xw+"`, `"a"`, + `"ax"`, `"xa"`, `"a+"`, `"ax+"`, or "`xa+`". + + Returns (sync version): `integer` or `fail` + + Returns (async version): `uv_fs_t userdata` + + Note: On Windows, libuv uses `CreateFileW` and thus the file + is always opened in binary mode. Because of this, the + `O_BINARY` and `O_TEXT` flags are not supported. + +uv.fs_read({fd}, {size} [, {offset} [, {callback}]]) *uv.fs_read()* + + Parameters: + - `fd`: `integer` + - `size`: `integer` + - `offset`: `integer` or `nil` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `data`: `string` or `nil` + + Equivalent to `preadv(2)`. Returns any data. An empty string + indicates EOF. + + If `offset` is nil or omitted, it will default to `-1`, which + indicates 'use and update the current file offset.' + + Note: When `offset` is >= 0, the current file offset will not + be updated by the read. + + Returns (sync version): `string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_unlink({path} [, {callback}]) *uv.fs_unlink()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `unlink(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_write({fd}, {data} [, {offset} [, {callback}]]) *uv.fs_write()* + + Parameters: + - `fd`: `integer` + - `data`: `buffer` + - `offset`: `integer` or `nil` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `bytes`: `integer` or `nil` + + Equivalent to `pwritev(2)`. Returns the number of bytes + written. + + If `offset` is nil or omitted, it will default to `-1`, which + indicates 'use and update the current file offset.' + + Note: When `offset` is >= 0, the current file offset will not + be updated by the write. + + Returns (sync version): `integer` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_mkdir({path}, {mode} [, {callback}]) *uv.fs_mkdir()* + + Parameters: + - `path`: `string` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `mkdir(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_mkdtemp({template} [, {callback}]) *uv.fs_mkdtemp()* + + Parameters: + - `template`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `path`: `string` or `nil` + + Equivalent to `mkdtemp(3)`. + + Returns (sync version): `string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_mkstemp({template} [, {callback}]) *uv.fs_mkstemp()* + + Parameters: + - `template`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `fd`: `integer` or `nil` + - `path`: `string` or `nil` + + Equivalent to `mkstemp(3)`. Returns a temporary file handle + and filename. + + Returns (sync version): `integer, string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_rmdir({path} [, {callback}]) *uv.fs_rmdir()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `rmdir(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_scandir({path} [, {callback}]) *uv.fs_scandir()* + + Parameters: + - `path`: `string` + - `callback`: `callable` + - `err`: `nil` or `string` + - `success`: `uv_fs_t userdata` or `nil` + + Equivalent to `scandir(3)`, with a slightly different API. + Returns a handle that the user can pass to + |uv.fs_scandir_next()|. + + Note: This function can be used synchronously or + asynchronously. The request userdata is always synchronously + returned regardless of whether a callback is provided and the + same userdata is passed to the callback if it is provided. + + Returns: `uv_fs_t userdata` or `fail` + +uv.fs_scandir_next({fs}) *uv.fs_scandir_next()* + + Parameters: + - `fs`: `uv_fs_t userdata` + + Called on a |uv_fs_t| returned by |uv.fs_scandir()| to get the + next directory entry data as a `name, type` pair. When there + are no more entries, `nil` is returned. + + Note: This function only has a synchronous version. See + |uv.fs_opendir()| and its related functions for an + asynchronous version. + + Returns: `string, string` or `nil` or `fail` + +uv.fs_stat({path} [, {callback}]) *uv.fs_stat()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `stat`: `table` or `nil` (see below) + + Equivalent to `stat(2)`. + + Returns (sync version): `table` or `fail` + - `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` : `table` + - `sec` : `integer` + - `nsec` : `integer` + - `mtime` : `table` + - `sec` : `integer` + - `nsec` : `integer` + - `ctime` : `table` + - `sec` : `integer` + - `nsec` : `integer` + - `birthtime` : `table` + - `sec` : `integer` + - `nsec` : `integer` + - `type` : `string` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fstat({fd} [, {callback}]) *uv.fs_fstat()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `stat`: `table` or `nil` (see `uv.fs_stat`) + + Equivalent to `fstat(2)`. + + Returns (sync version): `table` or `fail` (see `uv.fs_stat`) + + Returns (async version): `uv_fs_t userdata` + +uv.fs_lstat({path} [, {callback}]) *uv.fs_lstat()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `stat`: `table` or `nil` (see `uv.fs_stat`) + + Equivalent to `lstat(2)`. + + Returns (sync version): `table` or `fail` (see |uv.fs_stat()|) + + Returns (async version): `uv_fs_t userdata` + +uv.fs_rename({path}, {new_path} [, {callback}]) *uv.fs_rename()* + + Parameters: + - `path`: `string` + - `new_path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `rename(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fsync({fd} [, {callback}]) *uv.fs_fsync()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `fsync(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fdatasync({fd} [, {callback}]) *uv.fs_fdatasync()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `fdatasync(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_ftruncate({fd}, {offset} [, {callback}]) *uv.fs_ftruncate()* + + Parameters: + - `fd`: `integer` + - `offset`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `ftruncate(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + + *uv.fs_sendfile()* +uv.fs_sendfile({out_fd}, {in_fd}, {in_offset}, {size} [, {callback}]) + + Parameters: + - `out_fd`: `integer` + - `in_fd`: `integer` + - `in_offset`: `integer` + - `size`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `bytes`: `integer` or `nil` + + Limited equivalent to `sendfile(2)`. Returns the number of + bytes written. + + Returns (sync version): `integer` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_access({path}, {mode} [, {callback}]) *uv.fs_access()* + + Parameters: + - `path`: `string` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `permission`: `boolean` or `nil` + + Equivalent to `access(2)` on Unix. Windows uses + `GetFileAttributesW()`. Access `mode` can be an integer or a + string containing `"R"` or `"W"` or `"X"`. Returns `true` or + `false` indicating access permission. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_chmod({path}, {mode} [, {callback}]) *uv.fs_chmod()* + + Parameters: + - `path`: `string` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `chmod(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fchmod({fd}, {mode} [, {callback}]) *uv.fs_fchmod()* + + Parameters: + - `fd`: `integer` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `fchmod(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_utime({path}, {atime}, {mtime} [, {callback}]) *uv.fs_utime()* + + Parameters: + - `path`: `string` + - `atime`: `number` + - `mtime`: `number` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `utime(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_futime({fd}, {atime}, {mtime} [, {callback}]) *uv.fs_futime()* + + Parameters: + - `fd`: `integer` + - `atime`: `number` + - `mtime`: `number` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `futime(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_lutime({path}, {atime}, {mtime} [, {callback}]) *uv.fs_lutime()* + + Parameters: + - `path`: `string` + - `atime`: `number` + - `mtime`: `number` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `lutime(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_link({path}, {new_path} [, {callback}]) *uv.fs_link()* + + Parameters: + - `path`: `string` + - `new_path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `link(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_symlink({path}, {new_path} [, {flags} [, {callback}]]) *uv.fs_symlink()* + + Parameters: + - `path`: `string` + - `new_path`: `string` + - `flags`: `table`, `integer`, or `nil` + - `dir`: `boolean` + - `junction`: `boolean` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `symlink(2)`. If the `flags` parameter is + omitted, then the 3rd parameter will be treated as the + `callback`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_readlink({path} [, {callback}]) *uv.fs_readlink()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `path`: `string` or `nil` + + Equivalent to `readlink(2)`. + + Returns (sync version): `string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_realpath({path} [, {callback}]) *uv.fs_realpath()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `path`: `string` or `nil` + + Equivalent to `realpath(3)`. + + Returns (sync version): `string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_chown({path}, {uid}, {gid} [, {callback}]) *uv.fs_chown()* + + Parameters: + - `path`: `string` + - `uid`: `integer` + - `gid`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `chown(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fchown({fd}, {uid}, {gid} [, {callback}]) *uv.fs_fchown()* + + Parameters: + - `fd`: `integer` + - `uid`: `integer` + - `gid`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `fchown(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_lchown({fd}, {uid}, {gid} [, {callback}]) *uv.fs_lchown()* + + Parameters: + - `fd`: `integer` + - `uid`: `integer` + - `gid`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `lchown(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_copyfile({path}, {new_path} [, {flags} [, {callback}]]) *uv.fs_copyfile()* + + Parameters: + - `path`: `string` + - `new_path`: `string` + - `flags`: `table`, `integer`, or `nil` + - `excl`: `boolean` + - `ficlone`: `boolean` + - `ficlone_force`: `boolean` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Copies a file from path to new_path. If the `flags` parameter + is omitted, then the 3rd parameter will be treated as the + `callback`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_opendir({path} [, {callback} [, {entries}]]) *uv.fs_opendir()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `dir`: `luv_dir_t userdata` or `nil` + - `entries`: `integer` or `nil` + + Opens path as a directory stream. Returns a handle that the + user can pass to |uv.fs_readdir()|. The `entries` parameter + defines the maximum number of entries that should be returned + by each call to |uv.fs_readdir()|. + + Returns (sync version): `luv_dir_t userdata` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_readdir({dir} [, {callback}]) *uv.fs_readdir()* + + > method form `dir:readdir([callback])` + + Parameters: + - `dir`: `luv_dir_t userdata` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `entries`: `table` or `nil` (see below) + + Iterates over the directory stream `luv_dir_t` returned by a + successful |uv.fs_opendir()| call. A table of data tables is + returned where the number of entries `n` is equal to or less + than the `entries` parameter used in the associated + |uv.fs_opendir()| call. + + Returns (sync version): `table` or `fail` + - `[1, 2, 3, ..., n]` : `table` + - `name` : `string` + - `type` : `string` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_closedir({dir} [, {callback}]) *uv.fs_closedir()* + + > method form `dir:closedir([callback])` + + Parameters: + - `dir`: `luv_dir_t userdata` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Closes a directory stream returned by a successful + |uv.fs_opendir()| call. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_statfs({path} [, {callback}]) *uv.fs_statfs()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `table` or `nil` (see below) + + Equivalent to `statfs(2)`. + + Returns `table` or `nil` + - `type` : `integer` + - `bsize` : `integer` + - `blocks` : `integer` + - `bfree` : `integer` + - `bavail` : `integer` + - `files` : `integer` + - `ffree` : `integer` + +============================================================================== +THREAD POOL WORK SCHEDULING *luv-thread-pool-work-scheduling* + +Libuv provides a threadpool which can be used to run user code and get +notified in the loop thread. This threadpool is internally used to run all +file system operations, as well as `getaddrinfo` and `getnameinfo` requests. + + > + local function work_callback(a, b) + return a + b + end + + local function after_work_callback(c) + print("The result is: " .. c) + end + + local work = uv.new_work(work_callback, after_work_callback) + + work:queue(1, 2) + + -- output: "The result is: 3" +< + +uv.new_work({work_callback}, {after_work_callback}) *uv.new_work()* + + Parameters: + - `work_callback`: `function` + - `...`: `threadargs` passed to/from + `uv.queue_work(work_ctx, ...)` + - `after_work_callback`: `function` + - `...`: `threadargs` returned from `work_callback` + + Creates and initializes a new `luv_work_ctx_t` (not + `uv_work_t`). Returns the Lua userdata wrapping it. + + Returns: `luv_work_ctx_t userdata` + +uv.queue_work({work_ctx}, {...}) *uv.queue_work()* + + > method form `work_ctx:queue(...)` + + Parameters: + - `work_ctx`: `luv_work_ctx_t userdata` + - `...`: `threadargs` + + Queues a work request which will run `work_callback` in a new + Lua state in a thread from the threadpool with any additional + arguments from `...`. Values returned from `work_callback` are + passed to `after_work_callback`, which is called in the main + loop thread. + + Returns: `boolean` or `fail` + +============================================================================== +DNS UTILITY FUNCTIONS *luv-dns-utility-functions* + +uv.getaddrinfo({host}, {service} [, {hints} [, {callback}]]) *uv.getaddrinfo()* + + Parameters: + - `host`: `string` or `nil` + - `service`: `string` or `nil` + - `hints`: `table` or `nil` + - `family`: `string` or `integer` or `nil` + - `socktype`: `string` or `integer` or `nil` + - `protocol`: `string` or `integer` or `nil` + - `addrconfig`: `boolean` or `nil` + - `v4mapped`: `boolean` or `nil` + - `all`: `boolean` or `nil` + - `numerichost`: `boolean` or `nil` + - `passive`: `boolean` or `nil` + - `numericserv`: `boolean` or `nil` + - `canonname`: `boolean` or `nil` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `addresses`: `table` or `nil` (see below) + + Equivalent to `getaddrinfo(3)`. Either `node` or `service` may + be `nil` but not both. + + Valid hint strings for the keys that take a string: + - `family`: `"unix"`, `"inet"`, `"inet6"`, `"ipx"`, + `"netlink"`, `"x25"`, `"ax25"`, `"atmpvc"`, `"appletalk"`, + or `"packet"` + - `socktype`: `"stream"`, `"dgram"`, `"raw"`, `"rdm"`, or + `"seqpacket"` + - `protocol`: will be looked up using the `getprotobyname(3)` + function (examples: `"ip"`, `"icmp"`, `"tcp"`, `"udp"`, etc) + + Returns (sync version): `table` or `fail` + - `[1, 2, 3, ..., n]` : `table` + - `addr` : `string` + - `family` : `string` + - `port` : `integer` or `nil` + - `socktype` : `string` + - `protocol` : `string` + - `canonname` : `string` or `nil` + + Returns (async version): `uv_getaddrinfo_t userdata` or `fail` + +uv.getnameinfo({address} [, {callback}]) *uv.getnameinfo()* + + Parameters: + - `address`: `table` + - `ip`: `string` or `nil` + - `port`: `integer` or `nil` + - `family`: `string` or `integer` or `nil` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `sring` + - `host`: `string` or `nil` + - `service`: `string` or `nil` + + Equivalent to `getnameinfo(3)`. + + When specified, `family` must be one of `"unix"`, `"inet"`, + `"inet6"`, `"ipx"`, `"netlink"`, `"x25"`, `"ax25"`, + `"atmpvc"`, `"appletalk"`, or `"packet"`. + + Returns (sync version): `string, string` or `fail` + + Returns (async version): `uv_getnameinfo_t userdata` or `fail` + +============================================================================== +THREADING AND SYNCHRONIZATION UTILITIES *luv-threading-and-synchronization-utilities* + +Libuv provides cross-platform implementations for multiple threading an +synchronization primitives. The API largely follows the pthreads API. + +uv.new_thread([{options}, ] {entry}, {...}) *uv.new_thread()* + + Parameters: + - `options`: `table` or `nil` + - `stack_size`: `integer` or `nil` + - `entry`: `function` + - `...`: `threadargs` passed to `entry` + + Creates and initializes a `luv_thread_t` (not `uv_thread_t`). + Returns the Lua userdata wrapping it and asynchronously + executes `entry`, which can be either a Lua function or a Lua + function dumped to a string. Additional arguments `...` are + passed to the `entry` function and an optional `options` table + may be provided. Currently accepted `option` fields are + `stack_size`. + + Returns: `luv_thread_t userdata` or `fail` + +uv.thread_equal({thread}, {other_thread}) *uv.thread_equal()* + + > method form `thread:equal(other_thread)` + + Parameters: + - `thread`: `luv_thread_t userdata` + - `other_thread`: `luv_thread_t userdata` + + Returns a boolean indicating whether two threads are the same. + This function is equivalent to the `__eq` metamethod. + + Returns: `boolean` + +uv.thread_self() *uv.thread_self()* + + Returns the handle for the thread in which this is called. + + Returns: `luv_thread_t` + +uv.thread_join({thread}) *uv.thread_join()* + + > method form `thread:join()` + + Parameters: + - `thread`: `luv_thread_t userdata` + + Waits for the `thread` to finish executing its entry function. + + Returns: `boolean` or `fail` + +uv.sleep({msec}) *uv.sleep()* + + Parameters: + - `msec`: `integer` + + Pauses the thread in which this is called for a number of + milliseconds. + + Returns: Nothing. + +============================================================================== +MISCELLANEOUS UTILITIES *luv-miscellaneous-utilities* + +uv.exepath() *uv.exepath()* + + Returns the executable path. + + Returns: `string` or `fail` + +uv.cwd() *uv.cwd()* + + Returns the current working directory. + + Returns: `string` or `fail` + +uv.chdir({cwd}) *uv.chdir()* + + Parameters: + - `cwd`: `string` + + Sets the current working directory with the string `cwd`. + + Returns: `0` or `fail` + +uv.get_process_title() *uv.get_process_title()* + + Returns the title of the current process. + + Returns: `string` or `fail` + +uv.set_process_title({title}) *uv.set_process_title()* + + Parameters: + - `title`: `string` + + Sets the title of the current process with the string `title`. + + Returns: `0` or `fail` + +uv.get_total_memory() *uv.get_total_memory()* + + Returns the current total system memory in bytes. + + Returns: `number` + +uv.get_free_memory() *uv.get_free_memory()* + + Returns the current free system memory in bytes. + + Returns: `number` + +uv.get_constrained_memory() *uv.get_constrained_memory()* + + Gets the amount of memory available to the process in bytes + based on limits imposed by the OS. If there is no such + constraint, or the constraint is unknown, 0 is returned. Note + that it is not unusual for this value to be less than or + greater than the total system memory. + + Returns: `number` + +uv.resident_set_memory() *uv.resident_set_memory()* + + Returns the resident set size (RSS) for the current process. + + Returns: `integer` or `fail` + +uv.getrusage() *uv.getrusage()* + + Returns the resource usage. + + Returns: `table` or `fail` + - `utime` : `table` (user CPU time used) + - `sec` : `integer` + - `usec` : `integer` + - `stime` : `table` (system CPU time used) + - `sec` : `integer` + - `usec` : `integer` + - `maxrss` : `integer` (maximum resident set size) + - `ixrss` : `integer` (integral shared memory size) + - `idrss` : `integer` (integral unshared data size) + - `isrss` : `integer` (integral unshared stack size) + - `minflt` : `integer` (page reclaims (soft page faults)) + - `majflt` : `integer` (page faults (hard page faults)) + - `nswap` : `integer` (swaps) + - `inblock` : `integer` (block input operations) + - `oublock` : `integer` (block output operations) + - `msgsnd` : `integer` (IPC messages sent) + - `msgrcv` : `integer` (IPC messages received) + - `nsignals` : `integer` (signals received) + - `nvcsw` : `integer` (voluntary context switches) + - `nivcsw` : `integer` (involuntary context switches) + +uv.available_parallelism() *uv.available_parallelism()* + + Returns an estimate of the default amount of parallelism a + program should use. Always returns a non-zero value. + + On Linux, inspects the calling thread’s CPU affinity mask to + determine if it has been pinned to specific CPUs. + + On Windows, the available parallelism may be underreported on + systems with more than 64 logical CPUs. + + On other platforms, reports the number of CPUs that the + operating system considers to be online. + + Returns: `integer` + +uv.cpu_info() *uv.cpu_info()* + + Returns information about the CPU(s) on the system as a table + of tables for each CPU found. + + Returns: `table` or `fail` + - `[1, 2, 3, ..., n]` : `table` + - `model` : `string` + - `speed` : `number` + - `times` : `table` + - `user` : `number` + - `nice` : `number` + - `sys` : `number` + - `idle` : `number` + - `irq` : `number` + +uv.getpid() *uv.getpid()* + + DEPRECATED: Please use |uv.os_getpid()| instead. + +uv.getuid() *uv.getuid()* + + Returns the user ID of the process. + + Returns: `integer` + + Note: This is not a libuv function and is not supported on + Windows. + +uv.getgid() *uv.getgid()* + + Returns the group ID of the process. + + Returns: `integer` + + Note: This is not a libuv function and is not supported on + Windows. + +uv.setuid({id}) *uv.setuid()* + + Parameters: + - `id`: `integer` + + Sets the user ID of the process with the integer `id`. + + Returns: Nothing. + + Note: This is not a libuv function and is not supported on + Windows. + +uv.setgid({id}) *uv.setgid()* + + Parameters: + - `id`: `integer` + + Sets the group ID of the process with the integer `id`. + + Returns: Nothing. + + Note: This is not a libuv function and is not supported on + Windows. + +uv.hrtime() *uv.hrtime()* + + Returns a current high-resolution time in nanoseconds as a + number. This is relative to an arbitrary time in the past. It + is not related to the time of day and therefore not subject to + clock drift. The primary use is for measuring time between + intervals. + + Returns: `number` + +uv.uptime() *uv.uptime()* + + Returns the current system uptime in seconds. + + Returns: `number` or `fail` + +uv.print_all_handles() *uv.print_all_handles()* + + Prints all handles associated with the main loop to stderr. + The format is `[flags] handle-type handle-address` . Flags are + `R` for referenced, `A` for active and `I` for internal. + + Returns: Nothing. + + Note: This is not available on Windows. + + WARNING: This function is meant for ad hoc debugging, there + are no API/ABI stability guarantees. + +uv.print_active_handles() *uv.print_active_handles()* + + The same as |uv.print_all_handles()| except only active + handles are printed. + + Returns: Nothing. + + Note: This is not available on Windows. + + WARNING: This function is meant for ad hoc debugging, there + are no API/ABI stability guarantees. + +uv.guess_handle({fd}) *uv.guess_handle()* + + Parameters: + - `fd`: `integer` + + Used to detect what type of stream should be used with a given + file descriptor `fd`. Usually this will be used during + initialization to guess the type of the stdio streams. + + Returns: `string` + +uv.gettimeofday() *uv.gettimeofday()* + + Cross-platform implementation of `gettimeofday(2)`. Returns + the seconds and microseconds of a unix time as a pair. + + Returns: `integer, integer` or `fail` + +uv.interface_addresses() *uv.interface_addresses()* + + Returns address information about the network interfaces on + the system in a table. Each table key is the name of the + interface while each associated value is an array of address + information where fields are `ip`, `family`, `netmask`, + `internal`, and `mac`. + + Returns: `table` + - `[name(s)]` : `table` + - `ip` : `string` + - `family` : `string` + - `netmask` : `string` + - `internal` : `boolean` + - `mac` : `string` + +uv.if_indextoname({ifindex}) *uv.if_indextoname()* + + Parameters: + - `ifindex`: `integer` + + IPv6-capable implementation of `if_indextoname(3)`. + + Returns: `string` or `fail` + +uv.if_indextoiid({ifindex}) *uv.if_indextoiid()* + + Parameters: + - `ifindex`: `integer` + + Retrieves a network interface identifier suitable for use in + an IPv6 scoped address. On Windows, returns the numeric + `ifindex` as a string. On all other platforms, + |uv.if_indextoname()| is used. + + Returns: `string` or `fail` + +uv.loadavg() *uv.loadavg()* + + Returns the load average as a triad. Not supported on Windows. + + Returns: `number, number, number` + +uv.os_uname() *uv.os_uname()* + + Returns system information. + + Returns: `table` + - `sysname` : `string` + - `release` : `string` + - `version` : `string` + - `machine` : `string` + +uv.os_gethostname() *uv.os_gethostname()* + + Returns the hostname. + + Returns: `string` + +uv.os_getenv({name} [, {size}]) *uv.os_getenv()* + + Parameters: + - `name`: `string` + - `size`: `integer` (default = `LUAL_BUFFERSIZE`) + + Returns the environment variable specified by `name` as + string. The internal buffer size can be set by defining + `size`. If omitted, `LUAL_BUFFERSIZE` is used. If the + environment variable exceeds the storage available in the + internal buffer, `ENOBUFS` is returned. If no matching + environment variable exists, `ENOENT` is returned. + + Returns: `string` or `fail` + + WARNING: This function is not thread safe. + +uv.os_setenv({name}, {value}) *uv.os_setenv()* + + Parameters: + - `name`: `string` + - `value`: `string` + + Sets the environmental variable specified by `name` with the + string `value`. + + Returns: `boolean` or `fail` + + WARNING: This function is not thread safe. + +uv.os_unsetenv() *uv.os_unsetenv()* + + Returns: `boolean` or `fail` + + WARNING: This function is not thread safe. + +uv.os_environ() *uv.os_environ()* + + Returns all environmental variables as a dynamic table of + names associated with their corresponding values. + + Returns: `table` + + WARNING: This function is not thread safe. + +uv.os_homedir() *uv.os_homedir()* + + Returns: `string` or `fail` + + WARNING: This function is not thread safe. + +uv.os_tmpdir() *uv.os_tmpdir()* + + Returns: `string` or `fail` + + WARNING: This function is not thread safe. + +uv.os_get_passwd() *uv.os_get_passwd()* + + Returns password file information. + + Returns: `table` + - `username` : `string` + - `uid` : `integer` + - `gid` : `integer` + - `shell` : `string` + - `homedir` : `string` + +uv.os_getpid() *uv.os_getpid()* + + Returns the current process ID. + + Returns: `number` + +uv.os_getppid() *uv.os_getppid()* + + Returns the parent process ID. + + Returns: `number` + +uv.os_getpriority({pid}) *uv.os_getpriority()* + + Parameters: + - `pid`: `integer` + + Returns the scheduling priority of the process specified by + `pid`. + + Returns: `number` or `fail` + +uv.os_setpriority({pid}, {priority}) *uv.os_setpriority()* + + Parameters: + - `pid`: `integer` + - `priority`: `integer` + + Sets the scheduling priority of the process specified by + `pid`. The `priority` range is between -20 (high priority) and + 19 (low priority). + + Returns: `boolean` or `fail` + +uv.random({len}, {flags} [, {callback}]) *uv.random()* + + Parameters: + - `len`: `integer` + - `flags`: `nil` (see below) + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `bytes`: `string` or `nil` + + Fills a string of length `len` with cryptographically strong + random bytes acquired from the system CSPRNG. `flags` is + reserved for future extension and must currently be `nil` or + `0` or `{}`. + + Short reads are not possible. When less than `len` random + bytes are available, a non-zero error value is returned or + passed to the callback. If the callback is omitted, this + function is completed synchronously. + + The synchronous version may block indefinitely when not enough + entropy is available. The asynchronous version may not ever + finish when the system is low on entropy. + + Returns (sync version): `string` or `fail` + + Returns (async version): `0` or `fail` + +uv.translate_sys_error({errcode}) *uv.translate_sys_error()* + + Parameters: + - `errcode`: `integer` + + Returns the libuv error message and error name (both in string + form, see `err` and `name` in |luv-error-handling|) equivalent + to the given platform dependent error code: POSIX error codes + on Unix (the ones stored in errno), and Win32 error codes on + Windows (those returned by GetLastError() or + WSAGetLastError()). + + Returns: `string, string` or `nil` + +============================================================================== +METRICS OPERATIONS *luv-metrics-operations* + +uv.metrics_idle_time() *uv.metrics_idle_time()* + + Retrieve the amount of time the event loop has been idle in + the kernel’s event provider (e.g. `epoll_wait`). The call is + thread safe. + + The return value is the accumulated time spent idle in the + kernel’s event provider starting from when the |uv_loop_t| was + configured to collect the idle time. + + Note: The event loop will not begin accumulating the event + provider’s idle time until calling `loop_configure` with + `"metrics_idle_time"`. + + Returns: `number` + +============================================================================== +CREDITS *luv-credits* + +This document is a reformatted version of the LUV documentation, based on +commit c51e705 (5 May 2022) of the luv repository +https://github.com/luvit/luv/commit/c51e7052ec4f0a25058f70c1b4ee99dd36180e59. + +Included from https://github.com/nanotee/luv-vimdocs with kind permission. + + +vim:tw=78:ts=8:ft=help:norl: -- cgit From 24bf0490ea3a16c14494358fe45437e43ca8d1d1 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Tue, 9 Aug 2022 20:35:34 +0800 Subject: vim-patch:9.0.0176: checking character options is duplicated and incomplete (#19690) Problem: Checking character options is duplicated and incomplete. Solution: Move checking to check_chars_options(). (closes vim/vim#10863) https://github.com/vim/vim/commit/8ca29b6a3599b82b8822b7697cad63d0244c2d59 --- src/nvim/globals.h | 5 ----- src/nvim/mbyte.c | 22 +++------------------- src/nvim/option.c | 39 +++++++++++++++++++++++++++------------ src/nvim/testdir/test_options.vim | 12 ++++++++++-- 4 files changed, 40 insertions(+), 38 deletions(-) diff --git a/src/nvim/globals.h b/src/nvim/globals.h index 23870a572e..317423ffa0 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -1000,11 +1000,6 @@ EXTERN char e_fnametoolong[] INIT(= N_("E856: Filename too long")); EXTERN char e_float_as_string[] INIT(= N_("E806: using Float as a String")); EXTERN char e_cannot_edit_other_buf[] INIT(= N_("E788: Not allowed to edit another buffer now")); -EXTERN char e_conflicts_with_value_of_listchars[] -INIT(= N_("E834: Conflicts with value of 'listchars'")); -EXTERN char e_conflicts_with_value_of_fillchars[] -INIT(= N_("E835: Conflicts with value of 'fillchars'")); - EXTERN char e_autocmd_err[] INIT(= N_("E5500: autocmd has thrown an exception: %s")); EXTERN char e_cmdmap_err[] INIT(= N_("E5520: mapping must end with ")); EXTERN char e_cmdmap_repeated[] diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index e156fa58d1..8e8cf962c7 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -2844,25 +2844,9 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr) cw_table = table; cw_table_size = (size_t)tv_list_len(l); - // Check that the new value does not conflict with 'fillchars' or - // 'listchars'. - char *error = NULL; - if (set_chars_option(curwin, &p_fcs, false) != NULL) { - error = e_conflicts_with_value_of_fillchars; - } else if (set_chars_option(curwin, &p_lcs, false) != NULL) { - error = e_conflicts_with_value_of_listchars; - } else { - FOR_ALL_TAB_WINDOWS(tp, wp) { - if (set_chars_option(wp, &wp->w_p_lcs, true) != NULL) { - error = e_conflicts_with_value_of_listchars; - break; - } - if (set_chars_option(wp, &wp->w_p_fcs, true) != NULL) { - error = e_conflicts_with_value_of_fillchars; - break; - } - } - } + // Check that the new value does not conflict with 'listchars' or + // 'fillchars'. + const char *const error = check_chars_options(); if (error != NULL) { emsg(_(error)); cw_table = cw_table_save; diff --git a/src/nvim/option.c b/src/nvim/option.c index d7443bc593..8eb3b64e5b 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -339,6 +339,9 @@ static char_u SHM_ALL[] = { static char e_unclosed_expression_sequence[] = N_("E540: Unclosed expression sequence"); static char e_unbalanced_groups[] = N_("E542: unbalanced groups"); +static char e_conflicts_with_value_of_listchars[] = N_("E834: Conflicts with value of 'listchars'"); +static char e_conflicts_with_value_of_fillchars[] = N_("E835: Conflicts with value of 'fillchars'"); + #ifdef INCLUDE_GENERATED_DECLARATIONS # include "option.c.generated.h" #endif @@ -2578,18 +2581,7 @@ static char *did_set_string_option(int opt_idx, char_u **varp, char_u *oldval, c if (check_opt_strings(p_ambw, p_ambw_values, false) != OK) { errmsg = e_invarg; } else { - FOR_ALL_TAB_WINDOWS(tp, wp) { - if (set_chars_option(wp, &wp->w_p_lcs, true) != NULL) { - errmsg = _(e_conflicts_with_value_of_listchars); - goto ambw_end; - } - if (set_chars_option(wp, &wp->w_p_fcs, true) != NULL) { - errmsg = _(e_conflicts_with_value_of_fillchars); - goto ambw_end; - } - } -ambw_end: - {} // clint prefers {} over ; as an empty statement + errmsg = check_chars_options(); } } else if (varp == &p_bg) { // 'background' if (check_opt_strings(p_bg, p_bg_values, false) == OK) { @@ -3823,6 +3815,29 @@ char *set_chars_option(win_T *wp, char_u **varp, bool set) return NULL; // no error } +/// Check all global and local values of 'listchars' and 'fillchars'. +/// May set different defaults in case character widths change. +/// +/// @return an untranslated error message if any of them is invalid, NULL otherwise. +char *check_chars_options(void) +{ + if (set_chars_option(curwin, &p_lcs, false) != NULL) { + return e_conflicts_with_value_of_listchars; + } + if (set_chars_option(curwin, &p_fcs, false) != NULL) { + return e_conflicts_with_value_of_fillchars; + } + FOR_ALL_TAB_WINDOWS(tp, wp) { + if (set_chars_option(wp, &wp->w_p_lcs, true) != NULL) { + return e_conflicts_with_value_of_listchars; + } + if (set_chars_option(wp, &wp->w_p_fcs, true) != NULL) { + return e_conflicts_with_value_of_fillchars; + } + } + return NULL; +} + /// Check validity of options with the 'statusline' format. /// Return an untranslated error message or NULL. char *check_stl_option(char *s) diff --git a/src/nvim/testdir/test_options.vim b/src/nvim/testdir/test_options.vim index b10f0f5030..6e9f2d2377 100644 --- a/src/nvim/testdir/test_options.vim +++ b/src/nvim/testdir/test_options.vim @@ -368,9 +368,17 @@ func Test_set_errors() call assert_fails('set sessionoptions=curdir,sesdir', 'E474:') call assert_fails('set foldmarker={{{,', 'E474:') call assert_fails('set sessionoptions=sesdir,curdir', 'E474:') - call assert_fails('set listchars=trail:· ambiwidth=double', 'E834:') + setlocal listchars=trail:· + call assert_fails('set ambiwidth=double', 'E834:') + setlocal listchars=trail:- + setglobal listchars=trail:· + call assert_fails('set ambiwidth=double', 'E834:') set listchars& - call assert_fails('set fillchars=stl:· ambiwidth=double', 'E835:') + setlocal fillchars=stl:· + call assert_fails('set ambiwidth=double', 'E835:') + setlocal fillchars=stl:- + setglobal fillchars=stl:· + call assert_fails('set ambiwidth=double', 'E835:') set fillchars& call assert_fails('set fileencoding=latin1,utf-8', 'E474:') set nomodifiable -- cgit From 3030b4d65345baaa92606ad47e53573463c842d8 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Tue, 9 Aug 2022 21:08:46 +0800 Subject: feat(tui): allow grid and host to disagree on ambiguous-width chars (#19686) Note: This only applies to ambiguous-width characters. --- src/nvim/tui/tui.c | 68 ++++++++++++++++++++++++++++------- test/functional/terminal/tui_spec.lua | 41 +++++++++++++++++++++ 2 files changed, 96 insertions(+), 13 deletions(-) diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index e2289eb9ce..39133a3275 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -875,6 +875,53 @@ safe_move: ugrid_goto(grid, row, col); } +static void print_spaces(UI *ui, int width) +{ + TUIData *data = ui->data; + UGrid *grid = &data->grid; + + out(ui, data->space_buf, (size_t)width); + grid->col += width; + if (data->immediate_wrap_after_last_column) { + // Printing at the right margin immediately advances the cursor. + final_column_wrap(ui); + } +} + +/// Move cursor to the position given by `row` and `col` and print the character in `cell`. +/// This allows the grid and the host terminal to assume different widths of ambiguous-width chars. +/// +/// @param is_doublewidth whether the character is double-width on the grid. +/// If true and the character is ambiguous-width, clear two cells. +static void print_cell_at_pos(UI *ui, int row, int col, UCell *cell, bool is_doublewidth) +{ + TUIData *data = ui->data; + UGrid *grid = &data->grid; + + if (grid->row == -1 && cell->data[0] == NUL) { + // If cursor needs to repositioned and there is nothing to print, don't move cursor. + return; + } + + cursor_goto(ui, row, col); + + bool is_ambiwidth = utf_ambiguous_width(utf_ptr2char(cell->data)); + if (is_ambiwidth && is_doublewidth) { + // Clear the two screen cells. + // If the character is single-width in the host terminal it won't change the second cell. + update_attrs(ui, cell->attr); + print_spaces(ui, 2); + cursor_goto(ui, row, col); + } + + print_cell(ui, cell); + + if (is_ambiwidth) { + // Force repositioning cursor after printing an ambiguous-width character. + grid->row = -1; + } +} + static void clear_region(UI *ui, int top, int bot, int left, int right, int attr_id) { TUIData *data = ui->data; @@ -888,7 +935,7 @@ static void clear_region(UI *ui, int top, int bot, int left, int right, int attr && left == 0 && right == ui->width && bot == ui->height) { if (top == 0) { unibi_out(ui, unibi_clear_screen); - ugrid_goto(&data->grid, top, left); + ugrid_goto(grid, top, left); } else { cursor_goto(ui, top, 0); unibi_out(ui, unibi_clr_eos); @@ -905,12 +952,7 @@ static void clear_region(UI *ui, int top, int bot, int left, int right, int attr UNIBI_SET_NUM_VAR(data->params[0], width); unibi_out(ui, unibi_erase_chars); } else { - out(ui, data->space_buf, (size_t)width); - grid->col += width; - if (data->immediate_wrap_after_last_column) { - // Printing at the right margin immediately advances the cursor. - final_column_wrap(ui); - } + print_spaces(ui, width); } } } @@ -1302,8 +1344,8 @@ static void tui_flush(UI *ui) } UGRID_FOREACH_CELL(grid, row, r.left, clear_col, { - cursor_goto(ui, row, curcol); - print_cell(ui, cell); + print_cell_at_pos(ui, row, curcol, cell, + curcol < clear_col - 1 && (cell + 1)->data[0] == NUL); }); if (clear_col < r.right) { clear_region(ui, row, row + 1, clear_col, r.right, clear_attr); @@ -1439,8 +1481,8 @@ static void tui_raw_line(UI *ui, Integer g, Integer linerow, Integer startcol, I grid->cells[linerow][c].attr = attrs[c - startcol]; } UGRID_FOREACH_CELL(grid, (int)linerow, (int)startcol, (int)endcol, { - cursor_goto(ui, (int)linerow, curcol); - print_cell(ui, cell); + print_cell_at_pos(ui, (int)linerow, curcol, cell, + curcol < endcol - 1 && (cell + 1)->data[0] == NUL); }); if (clearcol > endcol) { @@ -1458,8 +1500,8 @@ static void tui_raw_line(UI *ui, Integer g, Integer linerow, Integer startcol, I if (endcol != grid->width) { // Print the last char of the row, if we haven't already done so. int size = grid->cells[linerow][grid->width - 1].data[0] == NUL ? 2 : 1; - cursor_goto(ui, (int)linerow, grid->width - size); - print_cell(ui, &grid->cells[linerow][grid->width - size]); + print_cell_at_pos(ui, (int)linerow, grid->width - size, + &grid->cells[linerow][grid->width - size], size == 2); } // Wrap the cursor over to the next line. The next line will be diff --git a/test/functional/terminal/tui_spec.lua b/test/functional/terminal/tui_spec.lua index eee759d2be..99f69ef556 100644 --- a/test/functional/terminal/tui_spec.lua +++ b/test/functional/terminal/tui_spec.lua @@ -1145,6 +1145,47 @@ describe('TUI', function() {3:-- TERMINAL --} | ]=]) end) + + it('allows grid to assume wider ambiguous-width characters than host terminal #19686', function() + child_session:request('nvim_buf_set_lines', 0, 0, 0, true, { ('℃'):rep(60), ('℃'):rep(60) }) + child_session:request('nvim_win_set_option', 0, 'cursorline', true) + child_session:request('nvim_win_set_option', 0, 'list', true) + child_session:request('nvim_win_set_option', 0, 'listchars', 'eol:$') + local attrs = screen:get_default_attr_ids() + attrs[11] = {underline = true} -- CursorLine + attrs[12] = {underline = true, reverse = true} -- CursorLine and TermCursor + attrs[13] = {underline = true, foreground = 12} -- CursorLine and NonText + feed_data('gg') + local singlewidth_screen = [[ + {12:℃}{11:℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃}| + {11:℃℃℃℃℃℃℃℃℃℃}{13:$}{11: }| + ℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃| + ℃℃℃℃℃℃℃℃℃℃{4:$} | + {5:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]] + -- When grid assumes "℃" to be double-width but host terminal assumes it to be single-width, the + -- second cell of "℃" is a space and the attributes of the "℃" are applied to it. + local doublewidth_screen = [[ + {12:℃}{11: ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }| + {11:℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }| + {11:℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }{13:$}{11: }| + ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ >{4:@@@}| + {5:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]] + screen:expect(singlewidth_screen, attrs) + child_session:request('nvim_set_option', 'ambiwidth', 'double') + screen:expect(doublewidth_screen, attrs) + child_session:request('nvim_set_option', 'ambiwidth', 'single') + screen:expect(singlewidth_screen, attrs) + child_session:request('nvim_call_function', 'setcellwidths', {{{0x2103, 0x2103, 2}}}) + screen:expect(doublewidth_screen, attrs) + child_session:request('nvim_call_function', 'setcellwidths', {{{0x2103, 0x2103, 1}}}) + screen:expect(singlewidth_screen, attrs) + end) end) describe('TUI', function() -- cgit From 48241c3b238e0cf5b4b5af61db4e54f2b8c02897 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 9 Aug 2022 17:05:56 +0200 Subject: ci(release): bump deprecated ubuntu image to 20.04 `ubuntu-18.04` is now deprecated and subject to outages, see https://github.blog/changelog/2022-08-09-github-actions-the-ubuntu-18-04-actions-runner-image-is-being-deprecated-and-will-be-removed-by-12-1-22/ --- .github/workflows/release.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cab57add52..cbb7bf64b4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,7 +16,7 @@ on: # Upgrade to gcc-11 to prevent it from using its builtins (#14150) jobs: linux: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 outputs: version: ${{ steps.build.outputs.version }} release: ${{ steps.build.outputs.release }} @@ -50,7 +50,7 @@ jobs: retention-days: 1 appimage: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v3 with: @@ -150,7 +150,7 @@ jobs: publish: needs: [linux, appimage, macOS, windows] - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest env: GH_REPO: ${{ github.repository }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} -- cgit From d212dfd676a32fc7c205c43cf58f86a7a02d0440 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 9 Aug 2022 17:35:19 +0200 Subject: ci(release): build with standard gcc on Ubuntu Ubuntu-20.04 ships with GCC 10.3.0, which is enough to avoid #14150 --- .github/workflows/release.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cbb7bf64b4..3b5c992fc7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,7 +13,7 @@ on: - v[0-9]+.[0-9]+.[0-9]+ # Build on the oldest supported images, so we have broader compatibility -# Upgrade to gcc-11 to prevent it from using its builtins (#14150) +# Build with gcc-10 to prevent triggering #14150 (default is still gcc-9 on 20.04) jobs: linux: runs-on: ubuntu-20.04 @@ -27,7 +27,7 @@ jobs: - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y autoconf automake build-essential cmake gcc-11 gettext libtool-bin locales ninja-build pkg-config unzip + sudo apt-get install -y autoconf automake build-essential cmake gettext libtool-bin locales ninja-build pkg-config unzip - if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.tag_name != 'nightly') run: printf 'NVIM_BUILD_TYPE=Release\n' >> $GITHUB_ENV - if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.event.inputs.tag_name == 'nightly') @@ -35,7 +35,7 @@ jobs: - name: Build release id: build run: | - CC=gcc-11 make CMAKE_BUILD_TYPE=${NVIM_BUILD_TYPE} CMAKE_EXTRA_FLAGS="-DCMAKE_INSTALL_PREFIX:PATH=" + CC=gcc-10 make CMAKE_BUILD_TYPE=${NVIM_BUILD_TYPE} CMAKE_EXTRA_FLAGS="-DCMAKE_INSTALL_PREFIX:PATH=" printf '::set-output name=version::%s\n' "$(./build/bin/nvim --version | head -n 3 | sed -z 's/\n/%0A/g')" printf '::set-output name=release::%s\n' "$(./build/bin/nvim --version | head -n 1)" make DESTDIR="$GITHUB_WORKSPACE/build/release/nvim-linux64" install @@ -58,11 +58,11 @@ jobs: - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y autoconf automake build-essential cmake gcc-11 gettext libtool-bin locales ninja-build pkg-config unzip + sudo apt-get install -y autoconf automake build-essential cmake gettext libtool-bin locales ninja-build pkg-config unzip - if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.tag_name != 'nightly') - run: CC=gcc-11 make appimage-latest + run: CC=gcc-10 make appimage-latest - if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.event.inputs.tag_name == 'nightly') - run: CC=gcc-11 make appimage-nightly + run: CC=gcc-10 make appimage-nightly - uses: actions/upload-artifact@v3 with: name: appimage -- cgit From bebfbfab3bca1808678bb196904b7570d6806458 Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Tue, 9 Aug 2022 22:20:40 +0200 Subject: fix(lsp): handle multiple clients with incremental sync (#19658) The change tracking used a single lines/lines_tmp table to track changes to a buffer. If multiple clients using incremental sync are connected to a buffer, they both made changes to the same lines table. That resulted in an inconsistent state. This commit changes the didChange handling to group clients by synchronization scheme and offset encoding. This avoids computing the diff multiple times for clients using the same scheme and resolves the lines/lines_tmp conflicts. Fixes https://github.com/neovim/neovim/issues/19325 --- runtime/lua/vim/lsp.lua | 384 +++++++++++++++++++++++++++++++----------------- 1 file changed, 248 insertions(+), 136 deletions(-) diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index 7f3237bdd0..10a74ba257 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -338,54 +338,165 @@ end local changetracking = {} do - --@private - --- client_id → state + ---@private + --- + --- LSP has 3 different sync modes: + --- - None (Servers will read the files themselves when needed) + --- - Full (Client sends the full buffer content on updates) + --- - Incremental (Client sends only the changed parts) + --- + --- Changes are tracked per buffer. + --- A buffer can have multiple clients attached and each client needs to send the changes + --- To minimize the amount of changesets to compute, computation is grouped: --- - --- state - --- use_incremental_sync: bool - --- buffers: bufnr -> buffer_state + --- None: One group for all clients + --- Full: One group for all clients + --- Incremental: One group per `offset_encoding` --- - --- buffer_state - --- pending_change?: function that the timer starts to trigger didChange - --- pending_changes: table (uri -> list of pending changeset tables)); - --- Only set if incremental_sync is used + --- Sending changes can be debounced per buffer. To simplify the implementation the + --- smallest debounce interval is used and we don't group clients by different intervals. --- - --- timer?: uv_timer - --- lines: table - local state_by_client = {} + --- @class CTGroup + --- @field sync_kind number TextDocumentSyncKind, considers config.flags.allow_incremental_sync + --- @field offset_encoding "utf-8"|"utf-16"|"utf-32" + --- + --- @class CTBufferState + --- @field name string name of the buffer + --- @field lines string[] snapshot of buffer lines from last didChange + --- @field lines_tmp string[] + --- @field pending_changes table[] List of debounced changes in incremental sync mode + --- @field timer nil|userdata uv_timer + --- @field last_flush nil|number uv.hrtime of the last flush/didChange-notification + --- @field needs_flush boolean true if buffer updates haven't been sent to clients/servers yet + --- @field refs number how many clients are using this group + --- + --- @class CTGroupState + --- @field buffers table + --- @field debounce number debounce duration in ms + --- @field clients table clients using this state. {client_id, client} ---@private - function changetracking.init(client, bufnr) - local use_incremental_sync = ( - if_nil(client.config.flags.allow_incremental_sync, true) - and vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change') - == protocol.TextDocumentSyncKind.Incremental + ---@param group CTGroup + ---@return string + local function group_key(group) + if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then + return tostring(group.sync_kind) .. '\0' .. group.offset_encoding + end + return tostring(group.sync_kind) + end + + ---@private + ---@type table + local state_by_group = setmetatable({}, { + __index = function(tbl, k) + return rawget(tbl, group_key(k)) + end, + __newindex = function(tbl, k, v) + rawset(tbl, group_key(k), v) + end, + }) + + ---@private + ---@return CTGroup + local function get_group(client) + local allow_inc_sync = if_nil(client.config.flags.allow_incremental_sync, true) + local change_capability = vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change') + local sync_kind = change_capability or protocol.TextDocumentSyncKind.None + if not allow_inc_sync and change_capability == protocol.TextDocumentSyncKind.Incremental then + sync_kind = protocol.TextDocumentSyncKind.Full + end + return { + sync_kind = sync_kind, + offset_encoding = client.offset_encoding, + } + end + + ---@private + ---@param state CTBufferState + local function incremental_changes(state, encoding, bufnr, firstline, lastline, new_lastline) + local prev_lines = state.lines + local curr_lines = state.lines_tmp + + local changed_lines = nvim_buf_get_lines(bufnr, firstline, new_lastline, true) + for i = 1, firstline do + curr_lines[i] = prev_lines[i] + end + for i = firstline + 1, new_lastline do + curr_lines[i] = changed_lines[i - firstline] + end + for i = lastline + 1, #prev_lines do + curr_lines[i - lastline + new_lastline] = prev_lines[i] + end + if tbl_isempty(curr_lines) then + -- Can happen when deleting the entire contents of a buffer, see https://github.com/neovim/neovim/issues/16259. + curr_lines[1] = '' + end + + local line_ending = buf_get_line_ending(bufnr) + local incremental_change = sync.compute_diff( + state.lines, + curr_lines, + firstline, + lastline, + new_lastline, + encoding, + line_ending ) - local state = state_by_client[client.id] - if not state then + + -- Double-buffering of lines tables is used to reduce the load on the garbage collector. + -- At this point the prev_lines table is useless, but its internal storage has already been allocated, + -- so let's keep it around for the next didChange event, in which it will become the next + -- curr_lines table. Note that setting elements to nil doesn't actually deallocate slots in the + -- internal storage - it merely marks them as free, for the GC to deallocate them. + for i in ipairs(prev_lines) do + prev_lines[i] = nil + end + state.lines = curr_lines + state.lines_tmp = prev_lines + + return incremental_change + end + + ---@private + function changetracking.init(client, bufnr) + assert(client.offset_encoding, 'lsp client must have an offset_encoding') + local group = get_group(client) + local state = state_by_group[group] + if state then + state.debounce = math.min(state.debounce, client.config.flags.debounce_text_changes or 150) + state.clients[client.id] = client + else state = { buffers = {}, debounce = client.config.flags.debounce_text_changes or 150, - use_incremental_sync = use_incremental_sync, + clients = { + [client.id] = client, + }, } - state_by_client[client.id] = state + state_by_group[group] = state end - if not state.buffers[bufnr] then - local buf_state = { + local buf_state = state.buffers[bufnr] + if buf_state then + buf_state.refs = buf_state.refs + 1 + else + buf_state = { name = api.nvim_buf_get_name(bufnr), + lines = {}, + lines_tmp = {}, + pending_changes = {}, + needs_flush = false, + refs = 1, } state.buffers[bufnr] = buf_state - if use_incremental_sync then + if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then buf_state.lines = nvim_buf_get_lines(bufnr, 0, -1, true) - buf_state.lines_tmp = {} - buf_state.pending_changes = {} end end end ---@private function changetracking._get_and_set_name(client, bufnr, name) - local state = state_by_client[client.id] or {} + local state = state_by_group[get_group(client)] or {} local buf_state = (state.buffers or {})[bufnr] local old_name = buf_state.name buf_state.name = name @@ -395,32 +506,33 @@ do ---@private function changetracking.reset_buf(client, bufnr) changetracking.flush(client, bufnr) - local state = state_by_client[client.id] - if state and state.buffers then - local buf_state = state.buffers[bufnr] + local state = state_by_group[get_group(client)] + if not state then + return + end + assert(state.buffers, 'CTGroupState must have buffers') + local buf_state = state.buffers[bufnr] + buf_state.refs = buf_state.refs - 1 + assert(buf_state.refs >= 0, 'refcount on buffer state must not get negative') + if buf_state.refs == 0 then state.buffers[bufnr] = nil - if buf_state and buf_state.timer then - buf_state.timer:stop() - buf_state.timer:close() - buf_state.timer = nil - end + changetracking._reset_timer(buf_state) end end ---@private - function changetracking.reset(client_id) - local state = state_by_client[client_id] + function changetracking.reset(client) + local state = state_by_group[get_group(client)] if not state then return end - for _, buf_state in pairs(state.buffers) do - if buf_state.timer then - buf_state.timer:stop() - buf_state.timer:close() - buf_state.timer = nil + state.clients[client.id] = nil + if vim.tbl_count(state.clients) == 0 then + for _, buf_state in pairs(state.buffers) do + changetracking._reset_timer(buf_state) end + state.buffers = {} end - state.buffers = {} end ---@private @@ -430,6 +542,10 @@ do -- debounce can be skipped and otherwise maybe reduced. -- -- This turns the debounce into a kind of client rate limiting + -- + ---@param debounce number + ---@param buf_state CTBufferState + ---@return number local function next_debounce(debounce, buf_state) if debounce == 0 then return 0 @@ -444,83 +560,36 @@ do end ---@private - function changetracking.prepare(bufnr, firstline, lastline, new_lastline) - local incremental_changes = function(client, buf_state) - local prev_lines = buf_state.lines - local curr_lines = buf_state.lines_tmp - - local changed_lines = nvim_buf_get_lines(bufnr, firstline, new_lastline, true) - for i = 1, firstline do - curr_lines[i] = prev_lines[i] - end - for i = firstline + 1, new_lastline do - curr_lines[i] = changed_lines[i - firstline] - end - for i = lastline + 1, #prev_lines do - curr_lines[i - lastline + new_lastline] = prev_lines[i] - end - if tbl_isempty(curr_lines) then - -- Can happen when deleting the entire contents of a buffer, see https://github.com/neovim/neovim/issues/16259. - curr_lines[1] = '' - end - - local line_ending = buf_get_line_ending(bufnr) - local incremental_change = sync.compute_diff( - buf_state.lines, - curr_lines, - firstline, - lastline, - new_lastline, - client.offset_encoding or 'utf-16', - line_ending - ) - - -- Double-buffering of lines tables is used to reduce the load on the garbage collector. - -- At this point the prev_lines table is useless, but its internal storage has already been allocated, - -- so let's keep it around for the next didChange event, in which it will become the next - -- curr_lines table. Note that setting elements to nil doesn't actually deallocate slots in the - -- internal storage - it merely marks them as free, for the GC to deallocate them. - for i in ipairs(prev_lines) do - prev_lines[i] = nil - end - buf_state.lines = curr_lines - buf_state.lines_tmp = prev_lines + ---@param bufnr number + ---@param sync_kind number protocol.TextDocumentSyncKind + ---@param state CTGroupState + ---@param buf_state CTBufferState + local function send_changes(bufnr, sync_kind, state, buf_state) + if not buf_state.needs_flush then + return + end + buf_state.last_flush = uv.hrtime() + buf_state.needs_flush = false - return incremental_change + if not api.nvim_buf_is_valid(bufnr) then + buf_state.pending_changes = {} + return end - local full_changes = once(function() - return { - text = buf_get_full_text(bufnr), + + local changes + if sync_kind == protocol.TextDocumentSyncKind.None then + return + elseif sync_kind == protocol.TextDocumentSyncKind.Incremental then + changes = buf_state.pending_changes + buf_state.pending_changes = {} + else + changes = { + { text = buf_get_full_text(bufnr) }, } - end) + end local uri = vim.uri_from_bufnr(bufnr) - return function(client) - if - vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change') - == protocol.TextDocumentSyncKind.None - then - return - end - local state = state_by_client[client.id] - local buf_state = state.buffers[bufnr] - changetracking._reset_timer(buf_state) - local debounce = next_debounce(state.debounce, buf_state) - if state.use_incremental_sync then - -- This must be done immediately and cannot be delayed - -- The contents would further change and startline/endline may no longer fit - table.insert(buf_state.pending_changes, incremental_changes(client, buf_state)) - end - buf_state.pending_change = function() - if buf_state.pending_change == nil then - return - end - buf_state.pending_change = nil - buf_state.last_flush = uv.hrtime() - if client.is_stopped() or not api.nvim_buf_is_valid(bufnr) then - return - end - local changes = state.use_incremental_sync and buf_state.pending_changes - or { full_changes() } + for _, client in pairs(state.clients) do + if not client.is_stopped() and lsp.buf_is_attached(bufnr, client.id) then client.notify('textDocument/didChange', { textDocument = { uri = uri, @@ -528,46 +597,90 @@ do }, contentChanges = changes, }) - buf_state.pending_changes = {} + end + end + end + + ---@private + function changetracking.send_changes(bufnr, firstline, lastline, new_lastline) + local groups = {} + for _, client in pairs(lsp.get_active_clients({ bufnr = bufnr })) do + local group = get_group(client) + groups[group_key(group)] = group + end + for _, group in pairs(groups) do + local state = state_by_group[group] + if not state then + error( + string.format( + 'changetracking.init must have been called for all LSP clients. group=%s states=%s', + vim.inspect(group), + vim.inspect(vim.tbl_keys(state_by_group)) + ) + ) + end + local buf_state = state.buffers[bufnr] + buf_state.needs_flush = true + changetracking._reset_timer(buf_state) + local debounce = next_debounce(state.debounce, buf_state) + if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then + -- This must be done immediately and cannot be delayed + -- The contents would further change and startline/endline may no longer fit + local changes = incremental_changes( + buf_state, + group.offset_encoding, + bufnr, + firstline, + lastline, + new_lastline + ) + table.insert(buf_state.pending_changes, changes) end if debounce == 0 then - buf_state.pending_change() + send_changes(bufnr, group.sync_kind, state, buf_state) else local timer = uv.new_timer() buf_state.timer = timer - -- Must use schedule_wrap because `full_changes()` calls nvim_buf_get_lines - timer:start(debounce, 0, vim.schedule_wrap(buf_state.pending_change)) + timer:start( + debounce, + 0, + vim.schedule_wrap(function() + changetracking._reset_timer(buf_state) + send_changes(bufnr, group.sync_kind, state, buf_state) + end) + ) end end end + ---@private function changetracking._reset_timer(buf_state) - if buf_state.timer then - buf_state.timer:stop() - buf_state.timer:close() + local timer = buf_state.timer + if timer then buf_state.timer = nil + if not timer:is_closing() then + timer:stop() + timer:close() + end end end --- Flushes any outstanding change notification. ---@private function changetracking.flush(client, bufnr) - local state = state_by_client[client.id] + local group = get_group(client) + local state = state_by_group[group] if not state then return end if bufnr then local buf_state = state.buffers[bufnr] or {} changetracking._reset_timer(buf_state) - if buf_state.pending_change then - buf_state.pending_change() - end + send_changes(bufnr, group.sync_kind, state, buf_state) else - for _, buf_state in pairs(state.buffers) do + for buf, buf_state in pairs(state.buffers) do changetracking._reset_timer(buf_state) - if buf_state.pending_change then - buf_state.pending_change() - end + send_changes(buf, group.sync_kind, state, buf_state) end end end @@ -1030,11 +1143,12 @@ function lsp.start_client(config) end) end end - + local client = active_clients[client_id] and active_clients[client_id] + or uninitialized_clients[client_id] active_clients[client_id] = nil uninitialized_clients[client_id] = nil - changetracking.reset(client_id) + changetracking.reset(client) if code ~= 0 or (signal ~= 0 and signal ~= 15) then local msg = string.format('Client %s quit with exit code %s and signal %s', client_id, code, signal) @@ -1414,9 +1528,7 @@ do return true end util.buf_versions[bufnr] = changedtick - local compute_change_and_notify = - changetracking.prepare(bufnr, firstline, lastline, new_lastline) - for_each_buffer_client(bufnr, compute_change_and_notify) + changetracking.send_changes(bufnr, firstline, lastline, new_lastline) end end -- cgit From 512e0441f1c92727efed69cb01f7bbee16777c2c Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 10 Aug 2022 12:47:38 +0800 Subject: docs: fix some mistakes and missing docs (#19699) --- runtime/doc/autocmd.txt | 4 ++-- runtime/doc/builtin.txt | 53 +++++++++++++++++++++++++------------------------ runtime/doc/cmdline.txt | 2 +- runtime/doc/options.txt | 11 +++++----- runtime/doc/syntax.txt | 2 +- runtime/doc/usr_41.txt | 3 ++- runtime/doc/windows.txt | 2 +- 7 files changed, 40 insertions(+), 37 deletions(-) diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt index 59e5c078a3..63226fe701 100644 --- a/runtime/doc/autocmd.txt +++ b/runtime/doc/autocmd.txt @@ -441,8 +441,8 @@ CompleteChanged *CompleteChanged* Non-recursive (event cannot trigger itself). Cannot change the text. |textlock| - The size and position of the popup are also - available by calling |pum_getpos()|. + The size and position of the popup are also + available by calling |pum_getpos()|. *CompleteDonePre* CompleteDonePre After Insert mode completion is done. Either diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index b80bedfac5..d0b28ce875 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -119,7 +119,7 @@ dictwatcherdel({dict}, {pattern}, {callback}) did_filetype() Number |TRUE| if FileType autocommand event used diff_filler({lnum}) Number diff filler lines about {lnum} diff_hlID({lnum}, {col}) Number diff highlighting at {lnum}/{col} -digraph_get({chars}) String get the digraph of {chars} +digraph_get({chars}) String get the |digraph| of {chars} digraph_getlist([{listall}]) List get all |digraph|s digraph_set({chars}, {digraph}) Boolean register |digraph| digraph_setlist({digraphlist}) Boolean register multiple |digraph|s @@ -239,8 +239,8 @@ haslocaldir([{winnr} [, {tabnr}]]) the tab executed |:tcd| hasmapto({what} [, {mode} [, {abbr}]]) Number |TRUE| if mapping to {what} exists -histadd({history}, {item}) String add an item to a history -histdel({history} [, {item}]) String remove an item from a history +histadd({history}, {item}) Number add an item to a history +histdel({history} [, {item}]) Number remove an item from a history histget({history} [, {index}]) String get the item {index} from a history histnr({history}) Number highest index of a history hlID({name}) Number syntax ID of highlight group {name} @@ -587,7 +587,7 @@ acos({expr}) *acos()* {expr} must evaluate to a |Float| or a |Number| in the range [-1, 1]. Returns NaN if {expr} is outside the range [-1, 1]. Returns - 0.0 if {expr} is not a |Float| or a |Number|. + 0.0 if {expr} is not a |Float| or a |Number|. Examples: > :echo acos(0) < 1.570796 > @@ -1136,8 +1136,8 @@ cindent({lnum}) *cindent()* GetLnum()->cindent() clearmatches([{win}]) *clearmatches()* - Clears all matches previously defined for the current window - by |matchadd()| and the |:match| commands. + Clears all matches previously defined for the current window + by |matchadd()| and the |:match| commands. If {win} is specified, use the window with this number or window ID instead of the current window. @@ -1989,6 +1989,7 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* autocmd file name autocmd buffer number (as a String!) autocmd matched name + C expression under the cursor sourced script file or function name sourced script line number or function line number @@ -2981,10 +2982,10 @@ getcurpos([{winid}]) current value of the buffer if it is not the current window. If {winid} is invalid a list with zeroes is returned. - This can be used to save and restore the cursor position: > - let save_cursor = getcurpos() - MoveTheCursorAround - call setpos('.', save_cursor) + This can be used to save and restore the cursor position: > + let save_cursor = getcurpos() + MoveTheCursorAround + call setpos('.', save_cursor) < Note that this only works within the window. See |winrestview()| for restoring more state. @@ -3119,7 +3120,7 @@ getjumplist([{winnr} [, {tabnr}]]) *getjumplist()* {winnr} can also be a |window-ID|. With {winnr} and {tabnr} use the window in the specified tab page. If {winnr} or {tabnr} is invalid, an empty list is - returned. + returned. The returned list contains two entries: a list with the jump locations and the last used jump position number in the list. @@ -3506,7 +3507,7 @@ gettabwinvar({tabnr}, {winnr}, {varname} [, {def}]) *gettabwinvar()* Get the value of window-local variable {varname} in window {winnr} in tab page {tabnr}. The {varname} argument is a string. When {varname} is empty a - dictionary with all window-local variables is returned. + dictionary with all window-local variables is returned. When {varname} is equal to "&" get the values of all window-local options in a |Dictionary|. Otherwise, when {varname} starts with "&" get the value of a @@ -4728,9 +4729,9 @@ maparg({name} [, {mode} [, {abbr} [, {dict}]]]) *maparg()* listing. When there is no mapping for {name}, an empty String is - returned if {dict} is FALSE, otherwise returns an empty Dict. - When the mapping for {name} is empty, then "" is - returned. + returned if {dict} is FALSE, otherwise returns an empty Dict. + When the mapping for {name} is empty, then "" is + returned. The {name} can have special key names, like in the ":map" command. @@ -5904,7 +5905,7 @@ pum_getpos() *pum_getpos()* size total nr of items scrollbar |TRUE| if scrollbar is visible - The values are the same as in |v:event| during |CompleteChanged|. + The values are the same as in |v:event| during |CompleteChanged|. pumvisible() *pumvisible()* Returns non-zero when the popup menu is visible, zero @@ -6654,7 +6655,7 @@ searchpair({start}, {middle}, {end} [, {flags} [, {skip} When {skip} is omitted or empty, every match is accepted. When evaluating {skip} causes an error the search is aborted and -1 returned. - {skip} can be a string, a lambda, a funcref or a partial. + {skip} can be a string, a lambda, a funcref or a partial. Anything else makes the function fail. For {stopline} and {timeout} see |search()|. @@ -7692,15 +7693,15 @@ stdpath({what}) *stdpath()* *E6100* str2float({string} [, {quoted}]) *str2float()* - Convert String {string} to a Float. This mostly works the - same as when using a floating point number in an expression, - see |floating-point-format|. But it's a bit more permissive. - E.g., "1e40" is accepted, while in an expression you need to - write "1.0e40". The hexadecimal form "0x123" is also - accepted, but not others, like binary or octal. - When {quoted} is present and non-zero then embedded single - quotes before the dot are ignored, thus "1'000.0" is a - thousand. + Convert String {string} to a Float. This mostly works the + same as when using a floating point number in an expression, + see |floating-point-format|. But it's a bit more permissive. + E.g., "1e40" is accepted, while in an expression you need to + write "1.0e40". The hexadecimal form "0x123" is also + accepted, but not others, like binary or octal. + When {quoted} is present and non-zero then embedded single + quotes before the dot are ignored, thus "1'000.0" is a + thousand. Text after the number is silently ignored. The decimal point is always '.', no matter what the locale is set to. A comma ends the number: "12,345.67" is converted to diff --git a/runtime/doc/cmdline.txt b/runtime/doc/cmdline.txt index 5d82f5985b..87f1589ea1 100644 --- a/runtime/doc/cmdline.txt +++ b/runtime/doc/cmdline.txt @@ -875,7 +875,7 @@ Note: these are typed literally, they are not special keys! match with (for FileType, Syntax and SpellFileMissing events). When the match is with a file name, it is expanded to the - full path. + full path. *:* ** When executing a `:source` command, is replaced with the file name of the sourced file. *E498* diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index f8e60f0d0d..614c6aec60 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -2144,7 +2144,8 @@ A jump table for the options with a short description can be found at |Q_op|. When on all Unicode emoji characters are considered to be full width. This excludes "text emoji" characters, which are normally displayed as single width. Unfortunately there is no good specification for this - and it has been determined on trial-and-error basis. + and it has been determined on trial-and-error basis. Use the + |setcellwidths()| function to change the behavior. *'encoding'* *'enc'* *E543* 'encoding' 'enc' @@ -4717,8 +4718,8 @@ A jump table for the options with a short description can be found at |Q_op|. in read-only mode ("vim -R") or when the executable is called "view". When using ":w!" the 'readonly' option is reset for the current buffer, unless the 'Z' flag is in 'cpoptions'. - When using the ":view" command the 'readonly' option is - set for the newly edited buffer. + When using the ":view" command the 'readonly' option is set for the + newly edited buffer. See 'modifiable' for disallowing changes to the buffer. *'redrawdebug'* *'rdb'* @@ -4839,7 +4840,7 @@ A jump table for the options with a short description can be found at |Q_op|. search "/" and "?" commands - This is useful for languages such as Hebrew and Arabic. + This is useful for languages such as Hebrew, Arabic and Farsi. The 'rightleft' option must be set for 'rightleftcmd' to take effect. *'ruler'* *'ru'* *'noruler'* *'noru'* @@ -6190,7 +6191,7 @@ A jump table for the options with a short description can be found at |Q_op|. global This option controls the behavior when switching between buffers. Mostly for |quickfix| commands some values are also used for other - commands, as mentioned below. + commands, as mentioned below. Possible values (comma-separated list): useopen If included, jump to the first open window that contains the specified buffer (if there is one). diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index 9ed3c37b8c..b74611633f 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -5250,7 +5250,7 @@ TabLineSel Tab pages line, active tab page label. Title Titles for output from ":set all", ":autocmd" etc. *hl-Visual* Visual Visual mode selection. - *hl-VisualNOS* + *hl-VisualNOS* VisualNOS Visual mode selection when vim is "Not Owning the Selection". *hl-WarningMsg* WarningMsg Warning messages. diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index af5ef0ab2d..235925c033 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -743,6 +743,7 @@ Cursor and mark position: *cursor-functions* *mark-functions* cursor() position the cursor at a line/column screencol() get screen column of the cursor screenrow() get screen row of the cursor + screenpos() screen row and col of a text character getcurpos() get position of the cursor getpos() get position of cursor, mark, etc. setpos() set position of cursor, mark, etc. @@ -852,9 +853,9 @@ Buffers, windows and the argument list: win_gotoid() go to window with ID win_id2tabwin() get tab and window nr from window ID win_id2win() get window nr from window ID - win_splitmove() move window to a split of another window win_move_separator() move window vertical separator win_move_statusline() move window status line + win_splitmove() move window to a split of another window getbufinfo() get a list with buffer information gettabinfo() get a list with tab page information getwininfo() get a list with window information diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 8062b9e28f..9d6a790a9c 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -372,7 +372,7 @@ CTRL-W o *CTRL-W_o* *E445* CTRL-W CTRL-O *CTRL-W_CTRL-O* *:on* *:only* Make the current window the only one on the screen. All other windows are closed. For {count} see the `:quit` command - above |:count_quit|. + above |:count_quit|. When the 'hidden' option is set, all buffers in closed windows become hidden. -- cgit From 78658ef3834baf7d202eb16a8778813e08e58412 Mon Sep 17 00:00:00 2001 From: Famiu Haque Date: Wed, 10 Aug 2022 16:37:59 +0600 Subject: fix(api): `vim.cmd.make` crashes when argument count isn't 1 (#19701) Closes #19696 --- src/nvim/api/command.c | 7 +++++-- test/functional/api/vim_spec.lua | 7 +++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/nvim/api/command.c b/src/nvim/api/command.c index bc766ff39c..fc1f6a04f2 100644 --- a/src/nvim/api/command.c +++ b/src/nvim/api/command.c @@ -819,9 +819,12 @@ static void build_cmdline_str(char **cmdlinep, exarg_T *eap, CmdParseInfo *cmdin char *p = replace_makeprg(eap, eap->arg, cmdlinep); if (p != eap->arg) { // If replace_makeprg modified the cmdline string, correct the argument pointers. - assert(argc == 1); eap->arg = p; - eap->args[0] = p; + // We can only know the position of the first argument because the argument list can be used + // multiple times in makeprg / grepprg. + if (argc >= 1) { + eap->args[0] = p; + } } } diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua index fe623ff824..3338fc6538 100644 --- a/test/functional/api/vim_spec.lua +++ b/test/functional/api/vim_spec.lua @@ -3829,5 +3829,12 @@ describe('API', function() eq({'aa'}, meths.buf_get_lines(0, 0, 1, false)) assert_alive() end) + it("'make' command works when argument count isn't 1 #19696", function() + command('set makeprg=echo') + meths.cmd({ cmd = 'make' }, {}) + assert_alive() + meths.cmd({ cmd = 'make', args = { 'foo', 'bar' } }, {}) + assert_alive() + end) end) end) -- cgit From ff1266aaaaba80f86ab9624eea8939d644d7e730 Mon Sep 17 00:00:00 2001 From: Jonas Strittmatter <40792180+smjonas@users.noreply.github.com> Date: Wed, 10 Aug 2022 13:44:57 +0200 Subject: vim-patch:9.0.0182: quarto files are not recognized (#19702) Problem: Quarto files are not recognized. Solution: Recognize quarto files by the extension. (Jonas Strittmatter, closes vim/vim#10880) https://github.com/vim/vim/commit/3a9687fb2749cb3da6e3bbf60cb9eaa81f7889ae --- runtime/filetype.vim | 3 +++ runtime/lua/vim/filetype.lua | 1 + src/nvim/testdir/test_filetype.vim | 1 + 3 files changed, 5 insertions(+) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index fbb4b9f6aa..e32374863f 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -1532,6 +1532,9 @@ au BufNewFile,BufRead *.ptl,*.pyi,SConstruct setf python " QL au BufRead,BufNewFile *.ql,*.qll setf ql +" Quarto +au BufRead,BufNewFile *.qmd setf quarto + " Radiance au BufNewFile,BufRead *.rad,*.mat setf radiance diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 1b209e6a9d..e9e81caec0 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -776,6 +776,7 @@ local extension = { ptl = 'python', ql = 'ql', qll = 'ql', + qmd = 'quarto', R = function(path, bufnr) return require('vim.filetype.detect').r(bufnr) end, diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index eedad15e9e..beaf5fdcfa 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -441,6 +441,7 @@ let s:filename_checks = { \ 'python': ['file.py', 'file.pyw', '.pythonstartup', '.pythonrc', 'file.ptl', 'file.pyi', 'SConstruct'], \ 'ql': ['file.ql', 'file.qll'], \ 'quake': ['anybaseq2/file.cfg', 'anyid1/file.cfg', 'quake3/file.cfg', 'baseq2/file.cfg', 'id1/file.cfg', 'quake1/file.cfg', 'some-baseq2/file.cfg', 'some-id1/file.cfg', 'some-quake1/file.cfg'], + \ 'quarto': ['file.qmd'], \ 'r': ['file.r'], \ 'radiance': ['file.rad', 'file.mat'], \ 'raku': ['file.pm6', 'file.p6', 'file.t6', 'file.pod6', 'file.raku', 'file.rakumod', 'file.rakudoc', 'file.rakutest'], -- cgit From faccae47fca5cb671e5c900e128b7da5a9937534 Mon Sep 17 00:00:00 2001 From: bfredl Date: Wed, 10 Aug 2022 20:36:28 +0200 Subject: fix(mpack): make sure a `bool` always is a `bool` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit before, RelWithDebInfo linking gave this warning: src/mpack/conv.h:36:16: warning: type of ‘mpack_unpack_boolean’ does not match original declaration [-Wlto-type-mismatch] 36 | MPACK_API bool mpack_unpack_boolean(mpack_token_t t) FUNUSED FPURE; | ^ src/mpack/conv.c:196:16: note: return value type mismatch 196 | MPACK_API bool mpack_unpack_boolean(mpack_token_t t) | ^ --- src/mpack/mpack_core.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mpack/mpack_core.h b/src/mpack/mpack_core.h index 1d601bc82d..336b778931 100644 --- a/src/mpack/mpack_core.h +++ b/src/mpack/mpack_core.h @@ -8,6 +8,7 @@ #include #include #include +#include #ifdef __GNUC__ # define FPURE __attribute__((const)) -- cgit From 252dea5927906208ab60f68d70891a82ab9ddd18 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Thu, 11 Aug 2022 08:53:15 +0200 Subject: build(deps): bump LuaJIT to HEAD - 633f265f6 (#19703) --- cmake.deps/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt index 8724ab4916..f65111f9ff 100644 --- a/cmake.deps/CMakeLists.txt +++ b/cmake.deps/CMakeLists.txt @@ -159,8 +159,8 @@ set(MSGPACK_URL https://github.com/msgpack/msgpack-c/releases/download/c-4.0.0/m set(MSGPACK_SHA256 420fe35e7572f2a168d17e660ef981a589c9cbe77faa25eb34a520e1fcc032c8) # https://github.com/LuaJIT/LuaJIT/tree/v2.1 -set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/a7d0265480c662964988f83d4e245bf139eb7cc0.tar.gz) -set(LUAJIT_SHA256 7d7f58ca5c02b453ed4ddd2298e741053cbd6cd3d96e79460d06ec6684244c59) +set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/633f265f67f322cbe2c5fd11d3e46d968ac220f7.tar.gz) +set(LUAJIT_SHA256 2681f0a6f624a64a8dfb70a5a377d494daf38960442c547d9c468674c1afa3c2) set(LUA_URL https://www.lua.org/ftp/lua-5.1.5.tar.gz) set(LUA_SHA256 2640fc56a795f29d28ef15e13c34a47e223960b0240e8cb0a82d9b0738695333) -- cgit From 94c317647845b92d675548a481f664a6a1808426 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 11 Aug 2022 15:44:55 +0800 Subject: refactor: use CLEAR_FIELD and CLEAR_POINTER macros (#19709) vim-patch:8.2.0559: clearing a struct is verbose Problem: Clearing a struct is verbose. Solution: Define and use CLEAR_FIELD() and CLEAR_POINTER(). https://github.com/vim/vim/commit/a80faa8930ed5a554beeb2727762538873135e83 --- src/nvim/api/command.c | 4 ++-- src/nvim/api/ui.c | 2 +- src/nvim/buffer.c | 4 ++-- src/nvim/charset.c | 2 +- src/nvim/cmdhist.c | 4 ++-- src/nvim/decoration.c | 2 +- src/nvim/diff.c | 10 +++++----- src/nvim/eval.c | 2 +- src/nvim/eval/funcs.c | 20 ++++++++++---------- src/nvim/eval/typval.c | 4 ++-- src/nvim/eval/userfunc.c | 2 +- src/nvim/ex_docmd.c | 38 +++++++++++++++++++------------------- src/nvim/ex_getln.c | 26 +++++++++++++------------- src/nvim/fileio.c | 2 +- src/nvim/hardcopy.c | 8 ++++---- src/nvim/hashtab.c | 10 ++++++---- src/nvim/highlight_group.c | 6 +++--- src/nvim/insexpand.c | 2 +- src/nvim/lua/converter.c | 2 +- src/nvim/lua/executor.c | 2 +- src/nvim/lua/xdiff.c | 6 +++--- src/nvim/main.c | 2 +- src/nvim/mapping.c | 2 +- src/nvim/mark.c | 4 ++-- src/nvim/memfile.c | 4 ++-- src/nvim/normal.c | 6 +++--- src/nvim/ops.c | 2 +- src/nvim/option.c | 2 +- src/nvim/os/fs.c | 6 +++--- src/nvim/popupmnu.c | 2 +- src/nvim/quickfix.c | 4 ++-- src/nvim/regexp_bt.c | 2 +- src/nvim/regexp_nfa.c | 4 ++-- src/nvim/screen.c | 2 +- src/nvim/search.c | 10 +++++----- src/nvim/shada.c | 6 +++--- src/nvim/sign.c | 2 +- src/nvim/spell.c | 14 +++++++------- src/nvim/spellfile.c | 6 +++--- src/nvim/syntax.c | 9 ++++----- src/nvim/tag.c | 6 +++--- src/nvim/tui/tui.c | 2 +- src/nvim/undo.c | 24 ++++++++++++------------ src/nvim/vim.h | 1 + src/nvim/window.c | 6 +++--- 45 files changed, 144 insertions(+), 142 deletions(-) diff --git a/src/nvim/api/command.c b/src/nvim/api/command.c index fc1f6a04f2..d264237e37 100644 --- a/src/nvim/api/command.c +++ b/src/nvim/api/command.c @@ -300,10 +300,10 @@ String nvim_cmd(uint64_t channel_id, Dict(cmd) *cmd, Dict(cmd_opts) *opts, Error FUNC_API_SINCE(10) { exarg_T ea; - memset(&ea, 0, sizeof(ea)); + CLEAR_FIELD(ea); CmdParseInfo cmdinfo; - memset(&cmdinfo, 0, sizeof(cmdinfo)); + CLEAR_FIELD(cmdinfo); char *cmdline = NULL; char *cmdname = NULL; diff --git a/src/nvim/api/ui.c b/src/nvim/api/ui.c index 6239e414a7..9cd4c97508 100644 --- a/src/nvim/api/ui.c +++ b/src/nvim/api/ui.c @@ -224,7 +224,7 @@ void nvim_ui_attach(uint64_t channel_id, Integer width, Integer height, Dictiona ui->event = remote_ui_event; ui->inspect = remote_ui_inspect; - memset(ui->ui_ext, 0, sizeof(ui->ui_ext)); + CLEAR_FIELD(ui->ui_ext); for (size_t i = 0; i < options.size; i++) { ui_set_option(ui, true, options.items[i].key, options.items[i].value, err); diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c index f23a1caf8b..657a18e0b6 100644 --- a/src/nvim/buffer.c +++ b/src/nvim/buffer.c @@ -793,8 +793,8 @@ static void free_buffer(buf_T *buf) if (autocmd_busy) { // Do not free the buffer structure while autocommands are executing, // it's still needed. Free it when autocmd_busy is reset. - memset(&buf->b_namedm[0], 0, sizeof(buf->b_namedm)); - memset(&buf->b_changelist[0], 0, sizeof(buf->b_changelist)); + CLEAR_FIELD(buf->b_namedm); + CLEAR_FIELD(buf->b_changelist); buf->b_next = au_pending_free_buf; au_pending_free_buf = buf; } else { diff --git a/src/nvim/charset.c b/src/nvim/charset.c index a26a7f6aaf..6238d85b3a 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -126,7 +126,7 @@ int buf_init_chartab(buf_T *buf, int global) } // Init word char flags all to false - memset(buf->b_chartab, 0, (size_t)32); + CLEAR_FIELD(buf->b_chartab); // In lisp mode the '-' character is included in keywords. if (buf->b_p_lisp) { diff --git a/src/nvim/cmdhist.c b/src/nvim/cmdhist.c index 625bd514ad..cd494d2247 100644 --- a/src/nvim/cmdhist.c +++ b/src/nvim/cmdhist.c @@ -178,7 +178,7 @@ static inline void hist_free_entry(histentry_T *hisptr) static inline void clear_hist_entry(histentry_T *hisptr) FUNC_ATTR_NONNULL_ALL { - memset(hisptr, 0, sizeof(*hisptr)); + CLEAR_POINTER(hisptr); } /// Check if command line 'str' is already in history. @@ -714,7 +714,7 @@ const void *hist_iter(const void *const iter, const uint8_t history_type, const } *hist = *hiter; if (zero) { - memset(hiter, 0, sizeof(*hiter)); + CLEAR_POINTER(hiter); } if (hiter == hlast) { return NULL; diff --git a/src/nvim/decoration.c b/src/nvim/decoration.c index e7c76fe38e..6f946bb41a 100644 --- a/src/nvim/decoration.c +++ b/src/nvim/decoration.c @@ -391,7 +391,7 @@ void decor_redraw_signs(buf_T *buf, int row, int *num_signs, sign_attrs_T sattrs sattrs[j] = sattrs[j - 1]; } if (j < SIGN_SHOW_MAX) { - memset(&sattrs[j], 0, sizeof(sign_attrs_T)); + CLEAR_FIELD(sattrs[j]); sattrs[j].sat_text = decor->sign_text; if (decor->sign_hl_id != 0) { sattrs[j].sat_texthl = syn_id2attr(decor->sign_hl_id); diff --git a/src/nvim/diff.c b/src/nvim/diff.c index 849204f789..e3a6f9039d 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -956,13 +956,13 @@ void ex_diffupdate(exarg_T *eap) // Only use the internal method if it did not fail for one of the buffers. diffio_T diffio; - memset(&diffio, 0, sizeof(diffio)); + CLEAR_FIELD(diffio); diffio.dio_internal = diff_internal() && !diff_internal_failed(); diff_try_update(&diffio, idx_orig, eap); if (diffio.dio_internal && diff_internal_failed()) { // Internal diff failed, use external diff instead. - memset(&diffio, 0, sizeof(diffio)); + CLEAR_FIELD(diffio); diff_try_update(&diffio, idx_orig, eap); } @@ -1075,9 +1075,9 @@ static int diff_file_internal(diffio_T *diffio) xdemitconf_t emit_cfg; xdemitcb_t emit_cb; - memset(¶m, 0, sizeof(param)); - memset(&emit_cfg, 0, sizeof(emit_cfg)); - memset(&emit_cb, 0, sizeof(emit_cb)); + CLEAR_FIELD(param); + CLEAR_FIELD(emit_cfg); + CLEAR_FIELD(emit_cb); param.flags = (unsigned long)diff_algorithm; diff --git a/src/nvim/eval.c b/src/nvim/eval.c index b0a207e5ba..5abaf88e60 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -1308,7 +1308,7 @@ char *get_lval(char *const name, typval_T *const rettv, lval_T *const lp, const int quiet = flags & GLV_QUIET; // Clear everything in "lp". - memset(lp, 0, sizeof(lval_T)); + CLEAR_POINTER(lp); if (skip) { // When skipping just find the end of the name. diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 52386a67f6..4a44c08457 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -2640,7 +2640,7 @@ static void f_get(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type == VAR_PARTIAL) { pt = argvars[0].vval.v_partial; } else { - memset(&fref_pt, 0, sizeof(fref_pt)); + CLEAR_FIELD(fref_pt); fref_pt.pt_name = (char_u *)argvars[0].vval.v_string; pt = &fref_pt; } @@ -7127,7 +7127,6 @@ static int search_cmn(typval_T *argvars, pos_T *match_pos, int *flagsp) long time_limit = 0; int options = SEARCH_KEEP; int subpatnum; - searchit_arg_T sia; bool use_skip = false; const char *const pat = tv_get_string(&argvars[0]); @@ -7178,9 +7177,10 @@ static int search_cmn(typval_T *argvars, pos_T *match_pos, int *flagsp) pos = save_cursor = curwin->w_cursor; pos_T firstpos = { 0 }; - memset(&sia, 0, sizeof(sia)); - sia.sa_stop_lnum = (linenr_T)lnum_stop; - sia.sa_tm = &tm; + searchit_arg_T sia = { + .sa_stop_lnum = (linenr_T)lnum_stop, + .sa_tm = &tm, + }; // Repeat until {skip} returns false. for (;;) { @@ -7799,10 +7799,10 @@ long do_searchpair(const char *spat, const char *mpat, const char *epat, int dir clearpos(&foundpos); pat = pat3; for (;;) { - searchit_arg_T sia; - memset(&sia, 0, sizeof(sia)); - sia.sa_stop_lnum = lnum_stop; - sia.sa_tm = &tm; + searchit_arg_T sia = { + .sa_stop_lnum = lnum_stop, + .sa_tm = &tm, + }; n = searchit(curwin, curbuf, &pos, NULL, dir, pat, 1L, options, RE_SEARCH, &sia); @@ -9500,7 +9500,7 @@ static void f_synconcealed(typval_T *argvars, typval_T *rettv, FunPtr fptr) const linenr_T lnum = tv_get_lnum(argvars); const colnr_T col = (colnr_T)tv_get_number(&argvars[1]) - 1; - memset(str, NUL, sizeof(str)); + CLEAR_FIELD(str); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count && col >= 0 && (size_t)col <= STRLEN(ml_get(lnum)) && curwin->w_p_cole > 0) { diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c index ff1808ed91..8822bb0491 100644 --- a/src/nvim/eval/typval.c +++ b/src/nvim/eval/typval.c @@ -233,7 +233,7 @@ void tv_list_init_static10(staticList10_T *const sl) #define SL_SIZE ARRAY_SIZE(sl->sl_items) list_T *const l = &sl->sl_list; - memset(sl, 0, sizeof(staticList10_T)); + CLEAR_POINTER(sl); l->lv_first = &sl->sl_items[0]; l->lv_last = &sl->sl_items[SL_SIZE - 1]; l->lv_refcount = DO_NOT_FREE_CNT; @@ -261,7 +261,7 @@ void tv_list_init_static10(staticList10_T *const sl) void tv_list_init_static(list_T *const l) FUNC_ATTR_NONNULL_ALL { - memset(l, 0, sizeof(*l)); + CLEAR_POINTER(l); l->lv_refcount = DO_NOT_FREE_CNT; list_log(l, NULL, NULL, "sinit"); } diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 2f4799db57..38a00099bc 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -1702,7 +1702,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp, lval_T lv; if (fdp != NULL) { - memset(fdp, 0, sizeof(funcdict_T)); + CLEAR_POINTER(fdp); } start = *pp; diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 86c5489cf2..e8dc0b8e86 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -391,7 +391,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) if (flags & DOCMD_EXCRESET) { save_dbg_stuff(&debug_saved); } else { - memset(&debug_saved, 0, sizeof(debug_saved)); + CLEAR_FIELD(debug_saved); } initial_trylevel = trylevel; @@ -1428,16 +1428,17 @@ bool parse_cmdline(char *cmdline, exarg_T *eap, CmdParseInfo *cmdinfo, char **er char *after_modifier = NULL; // Initialize cmdinfo - memset(cmdinfo, 0, sizeof(*cmdinfo)); + CLEAR_POINTER(cmdinfo); // Initialize eap - memset(eap, 0, sizeof(*eap)); - eap->line1 = 1; - eap->line2 = 1; - eap->cmd = cmdline; - eap->cmdlinep = &cmdline; - eap->getline = NULL; - eap->cookie = NULL; + *eap = (exarg_T){ + .line1 = 1, + .line2 = 1, + .cmd = cmdline, + .cmdlinep = &cmdline, + .getline = NULL, + .cookie = NULL, + }; const bool save_ex_pressedreturn = ex_pressedreturn; // Parse command modifiers @@ -1877,10 +1878,10 @@ static char *do_one_cmd(char **cmdlinep, int flags, cstack_T *cstack, LineGetter const int save_reg_executing = reg_executing; const bool save_pending_end_reg_executing = pending_end_reg_executing; - exarg_T ea; - memset(&ea, 0, sizeof(ea)); - ea.line1 = 1; - ea.line2 = 1; + exarg_T ea = { + .line1 = 1, + .line2 = 1, + }; ex_nesting_level++; // When the last file has not been edited :q has to be typed twice. @@ -6021,12 +6022,11 @@ theend: /// Open a new tab page. void tabpage_new(void) { - exarg_T ea; - - memset(&ea, 0, sizeof(ea)); - ea.cmdidx = CMD_tabnew; - ea.cmd = "tabn"; - ea.arg = ""; + exarg_T ea = { + .cmdidx = CMD_tabnew, + .cmd = "tabn", + .arg = "", + }; ex_splitview(&ea); } diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 841345d625..22bbefe827 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -311,7 +311,6 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s int delim; char *end; char *dummy; - exarg_T ea; pos_T save_cursor; bool use_last_pat; bool retval = false; @@ -336,11 +335,12 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s } emsg_off++; - memset(&ea, 0, sizeof(ea)); - ea.line1 = 1; - ea.line2 = 1; - ea.cmd = (char *)ccline.cmdbuff; - ea.addr_type = ADDR_LINES; + exarg_T ea = { + .line1 = 1, + .line2 = 1, + .cmd = (char *)ccline.cmdbuff, + .addr_type = ADDR_LINES, + }; cmdmod_T dummy_cmdmod; parse_command_modifiers(&ea, &dummy, &dummy_cmdmod, true); @@ -453,7 +453,6 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat { pos_T end_pos; proftime_T tm; - searchit_arg_T sia; int skiplen, patlen; char_u next_char; char_u use_last_pat; @@ -516,8 +515,9 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat search_flags += SEARCH_START; } ccline.cmdbuff[skiplen + patlen] = NUL; - memset(&sia, 0, sizeof(sia)); - sia.sa_tm = &tm; + searchit_arg_T sia = { + .sa_tm = &tm, + }; found = do_search(NULL, firstc == ':' ? '/' : firstc, search_delim, ccline.cmdbuff + skiplen, count, search_flags, &sia); @@ -731,7 +731,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init save_cmdline(&save_ccline); did_save_ccline = true; } else if (init_ccline) { - memset(&ccline, 0, sizeof(struct cmdline_info)); + CLEAR_FIELD(ccline); } if (s->firstc == -1) { @@ -2677,7 +2677,7 @@ char *getcmdline_prompt(const int firstc, const char *const prompt, const int at save_cmdline(&save_ccline); did_save_ccline = true; } else { - memset(&ccline, 0, sizeof(struct cmdline_info)); + CLEAR_FIELD(ccline); } ccline.prompt_id = last_prompt_id++; ccline.cmdprompt = (char_u *)prompt; @@ -3640,7 +3640,7 @@ void put_on_cmdline(char_u *str, int len, int redraw) static void save_cmdline(struct cmdline_info *ccp) { *ccp = ccline; - memset(&ccline, 0, sizeof(struct cmdline_info)); + CLEAR_FIELD(ccline); ccline.prev_ccline = ccp; ccline.cmdbuff = NULL; // signal that ccline is not in use } @@ -6029,7 +6029,7 @@ int get_list_range(char_u **str, int *num1, int *num2) void cmdline_init(void) { - memset(&ccline, 0, sizeof(struct cmdline_info)); + CLEAR_FIELD(ccline); } /// Open a window on the current command line and history. Allow editing in diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index b98984017b..b467f53bbd 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -5122,7 +5122,7 @@ void buf_reload(buf_T *buf, int orig_mode, bool reload_options) // file, not reset the syntax highlighting, clear marks, diff status, etc. // Force the fileformat and encoding to be the same. if (reload_options) { - memset(&ea, 0, sizeof(ea)); + CLEAR_FIELD(ea); } else { prep_exarg(&ea, buf); } diff --git a/src/nvim/hardcopy.c b/src/nvim/hardcopy.c index d7f7b8eb92..96d3bfb4d3 100644 --- a/src/nvim/hardcopy.c +++ b/src/nvim/hardcopy.c @@ -632,8 +632,8 @@ void ex_hardcopy(exarg_T *eap) int page_line; int jobsplit; - memset(&settings, 0, sizeof(prt_settings_T)); - settings.has_color = TRUE; + CLEAR_FIELD(settings); + settings.has_color = true; if (*eap->arg == '>') { char *errormsg = NULL; @@ -734,7 +734,7 @@ void ex_hardcopy(exarg_T *eap) prt_pos_T page_prtpos; // print position at page start int side; - memset(&page_prtpos, 0, sizeof(prt_pos_T)); + CLEAR_FIELD(page_prtpos); page_prtpos.file_line = eap->line1; prtpos = page_prtpos; @@ -1718,7 +1718,7 @@ static bool prt_open_resource(struct prt_ps_resource_S *resource) semsg(_("E624: Can't open file \"%s\""), resource->filename); return false; } - memset(prt_resfile.buffer, NUL, PRT_FILE_BUFFER_LEN); + CLEAR_FIELD(prt_resfile.buffer); // Parse first line to ensure valid resource file prt_resfile.len = (int)fread((char *)prt_resfile.buffer, sizeof(char_u), diff --git a/src/nvim/hashtab.c b/src/nvim/hashtab.c index 95ae7a152c..951e72ea52 100644 --- a/src/nvim/hashtab.c +++ b/src/nvim/hashtab.c @@ -45,7 +45,7 @@ char hash_removed; void hash_init(hashtab_T *ht) { // This zeroes all "ht_" entries and all the "hi_key" in "ht_smallarray". - memset(ht, 0, sizeof(hashtab_T)); + CLEAR_POINTER(ht); ht->ht_array = ht->ht_smallarray; ht->ht_mask = HT_INIT_SIZE - 1; } @@ -342,11 +342,13 @@ static void hash_may_resize(hashtab_T *ht, size_t minitems) hashitem_T *oldarray = keep_smallarray ? memcpy(temparray, ht->ht_smallarray, sizeof(temparray)) : ht->ht_array; + + if (newarray_is_small) { + CLEAR_FIELD(ht->ht_smallarray); + } hashitem_T *newarray = newarray_is_small ? ht->ht_smallarray - : xmalloc(sizeof(hashitem_T) * newsize); - - memset(newarray, 0, sizeof(hashitem_T) * newsize); + : xcalloc(newsize, sizeof(hashitem_T)); // Move all the items from the old array to the new one, placing them in // the right spot. The new array won't have any removed items, thus this diff --git a/src/nvim/highlight_group.c b/src/nvim/highlight_group.c index f6ec03fb14..5afbaaf121 100644 --- a/src/nvim/highlight_group.c +++ b/src/nvim/highlight_group.c @@ -1765,7 +1765,7 @@ static int syn_add_group(const char *name, size_t len) // Append another syntax_highlight entry. HlGroup *hlgp = GA_APPEND_VIA_PTR(HlGroup, &highlight_ga); - memset(hlgp, 0, sizeof(*hlgp)); + CLEAR_POINTER(hlgp); hlgp->sg_name = (char_u *)arena_memdupz(&highlight_arena, name, len); hlgp->sg_rgb_bg = -1; hlgp->sg_rgb_fg = -1; @@ -1863,7 +1863,7 @@ static void combine_stl_hlt(int id, int id_S, int id_alt, int hlcnt, int i, int HlGroup *const hlt = hl_table; if (id_alt == 0) { - memset(&hlt[hlcnt + i], 0, sizeof(HlGroup)); + CLEAR_POINTER(&hlt[hlcnt + i]); hlt[hlcnt + i].sg_cterm = highlight_attr[hlf]; hlt[hlcnt + i].sg_gui = highlight_attr[hlf]; } else { @@ -1945,7 +1945,7 @@ void highlight_changed(void) hlcnt = highlight_ga.ga_len; if (id_S == -1) { // Make sure id_S is always valid to simplify code below. Use the last entry - memset(&hl_table[hlcnt + 9], 0, sizeof(HlGroup)); + CLEAR_POINTER(&hl_table[hlcnt + 9]); id_S = hlcnt + 10; } for (int i = 0; i < 9; i++) { diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index a64d8e8f00..bddeee119d 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2139,7 +2139,7 @@ static int ins_compl_add_tv(typval_T *const tv, const Direction dir, bool fast) } } else { word = tv_get_string_chk(tv); - memset(cptext, 0, sizeof(cptext)); + CLEAR_FIELD(cptext); } if (word == NULL || (!empty && *word == NUL)) { for (size_t i = 0; i < CPT_COUNT; i++) { diff --git a/src/nvim/lua/converter.c b/src/nvim/lua/converter.c index 4d6e6090b8..49d49f76b9 100644 --- a/src/nvim/lua/converter.c +++ b/src/nvim/lua/converter.c @@ -59,7 +59,7 @@ static LuaTableProps nlua_traverse_table(lua_State *const lstate) size_t other_keys_num = 0; // Number of keys that are not string, integral // or type keys. LuaTableProps ret; - memset(&ret, 0, sizeof(ret)); + CLEAR_FIELD(ret); if (!lua_checkstack(lstate, lua_gettop(lstate) + 3)) { semsg(_("E1502: Lua failed to grow stack to %i"), lua_gettop(lstate) + 2); ret.type = kObjectTypeNil; diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 661dbfc4c2..c7b654482c 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -447,7 +447,7 @@ static nlua_ref_state_t *nlua_new_ref_state(lua_State *lstate, bool is_thread) FUNC_ATTR_NONNULL_ALL { nlua_ref_state_t *ref_state = lua_newuserdata(lstate, sizeof(*ref_state)); - memset(ref_state, 0, sizeof(*ref_state)); + CLEAR_POINTER(ref_state); ref_state->nil_ref = LUA_NOREF; ref_state->empty_dict_ref = LUA_NOREF; if (!is_thread) { diff --git a/src/nvim/lua/xdiff.c b/src/nvim/lua/xdiff.c index 71f85385b6..b2b5dfedee 100644 --- a/src/nvim/lua/xdiff.c +++ b/src/nvim/lua/xdiff.c @@ -269,9 +269,9 @@ int nlua_xdl_diff(lua_State *lstate) xpparam_t params; xdemitcb_t ecb; - memset(&cfg, 0, sizeof(cfg)); - memset(¶ms, 0, sizeof(params)); - memset(&ecb, 0, sizeof(ecb)); + CLEAR_FIELD(cfg); + CLEAR_FIELD(params); + CLEAR_FIELD(ecb); NluaXdiffMode mode = kNluaXdiffModeUnified; diff --git a/src/nvim/main.c b/src/nvim/main.c index 494ff0b4af..378ca6ba71 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -1418,7 +1418,7 @@ scripterror: * copied, so that they can be changed. */ static void init_params(mparm_T *paramp, int argc, char **argv) { - memset(paramp, 0, sizeof(*paramp)); + CLEAR_POINTER(paramp); paramp->argc = argc; paramp->argv = argv; paramp->use_debug_break_level = -1; diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index 342b1b0d47..f0a82b6bec 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -333,7 +333,7 @@ static int str_to_mapargs(const char_u *strargs, bool is_unmap, MapArguments *ma { const char_u *to_parse = strargs; to_parse = (char_u *)skipwhite((char *)to_parse); - memset(mapargs, 0, sizeof(*mapargs)); + CLEAR_POINTER(mapargs); // Accept , , , ,