API: deprecate nvim_command_output

This commit is contained in:
Justin M. Keyes
2019-12-01 22:43:16 -08:00
parent 22b52dd462
commit c34130d13a
16 changed files with 90 additions and 117 deletions

View File

@@ -479,6 +479,24 @@ created for extmark changes.
============================================================================== ==============================================================================
Global Functions *api-global* Global Functions *api-global*
nvim_exec({src}, {output}) *nvim_exec()*
Executes Vimscript (multiline block of Ex-commands), like
anonymous |:source|.
Optionally returns (non-error, non-shell |:!|) output.
On execution error: fails with VimL error, does not update
v:errmsg.
Parameters: ~
{src} Vimscript code
{output} Capture and return all (non-error, non-shell
|:!|) output
See also: ~
|execute()|
|nvim_command()|
nvim_command({command}) *nvim_command()* nvim_command({command}) *nvim_command()*
Executes an ex-command. Executes an ex-command.
@@ -488,6 +506,9 @@ nvim_command({command}) *nvim_command()*
Parameters: ~ Parameters: ~
{command} Ex-command string {command} Ex-command string
See also: ~
|nvim_exec()|
nvim_get_hl_by_name({name}, {rgb}) *nvim_get_hl_by_name()* nvim_get_hl_by_name({name}, {rgb}) *nvim_get_hl_by_name()*
Gets a highlight definition by name. Gets a highlight definition by name.
@@ -609,19 +630,9 @@ nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special})
replace_termcodes replace_termcodes
cpoptions cpoptions
nvim_command_output({command}) *nvim_command_output()*
Executes an ex-command and returns its (non-error) output.
Shell |:!| output is not captured.
On execution error: fails with VimL error, does not update
v:errmsg.
Parameters: ~
{command} Ex-command string
nvim_eval({expr}) *nvim_eval()* nvim_eval({expr}) *nvim_eval()*
Evaluates a VimL expression (:help expression). Dictionaries Evaluates a VimL |expression|. Dictionaries and Lists are
and Lists are recursively expanded. recursively expanded.
On execution error: fails with VimL error, does not update On execution error: fails with VimL error, does not update
v:errmsg. v:errmsg.

View File

@@ -14,6 +14,7 @@ updated.
API ~ API ~
*nvim_buf_clear_highlight()* Use |nvim_buf_clear_namespace()| instead. *nvim_buf_clear_highlight()* Use |nvim_buf_clear_namespace()| instead.
*nvim_command_output()* Use |nvim_exec()| instead.
Commands ~ Commands ~
*:rv* *:rv*

View File

@@ -76,7 +76,8 @@ void api_vim_free_all_mem(void)
/// Executes Vimscript (multiline block of Ex-commands), like anonymous /// Executes Vimscript (multiline block of Ex-commands), like anonymous
/// |:source|. /// |:source|.
/// ///
/// Optionally returns (non-error, non-shell |:!|) output. /// Unlike |nvim_command()| this function supports heredocs, script-scope (s:),
/// etc.
/// ///
/// On execution error: fails with VimL error, does not update v:errmsg. /// On execution error: fails with VimL error, does not update v:errmsg.
/// ///
@@ -86,24 +87,21 @@ void api_vim_free_all_mem(void)
/// @param src Vimscript code /// @param src Vimscript code
/// @param output Capture and return all (non-error, non-shell |:!|) output /// @param output Capture and return all (non-error, non-shell |:!|) output
/// @param[out] err Error details (Vim error), if any /// @param[out] err Error details (Vim error), if any
/// @return Output (non-error, non-shell |:!|) if `output` is true,
/// else empty string.
String nvim_exec(String src, Boolean output, Error *err) String nvim_exec(String src, Boolean output, Error *err)
FUNC_API_SINCE(7) FUNC_API_SINCE(7)
{ {
if (!output) {
try_start();
do_source_str(src.data, "nvim_exec()");
try_end(err);
return (String)STRING_INIT;
}
const int save_msg_silent = msg_silent; const int save_msg_silent = msg_silent;
garray_T *const save_capture_ga = capture_ga; garray_T *const save_capture_ga = capture_ga;
garray_T capture_local; garray_T capture_local;
ga_init(&capture_local, 1, 80); if (output) {
ga_init(&capture_local, 1, 80);
capture_ga = &capture_local;
}
try_start(); try_start();
msg_silent++; msg_silent++;
capture_ga = &capture_local;
do_source_str(src.data, "nvim_exec()"); do_source_str(src.data, "nvim_exec()");
capture_ga = save_capture_ga; capture_ga = save_capture_ga;
msg_silent = save_msg_silent; msg_silent = save_msg_silent;
@@ -113,10 +111,10 @@ String nvim_exec(String src, Boolean output, Error *err)
goto theend; goto theend;
} }
if (capture_local.ga_len > 1) { if (output && capture_local.ga_len > 1) {
String s = (String){ String s = (String){
.data = capture_local.ga_data, .data = capture_local.ga_data,
.size = (size_t)capture_local.ga_len, .size = (size_t)capture_local.ga_len,
}; };
// redir usually (except :echon) prepends a newline. // redir usually (except :echon) prepends a newline.
if (s.data[0] == '\n') { if (s.data[0] == '\n') {
@@ -127,7 +125,9 @@ String nvim_exec(String src, Boolean output, Error *err)
return s; // Caller will free the memory. return s; // Caller will free the memory.
} }
theend: theend:
ga_clear(&capture_local); if (output) {
ga_clear(&capture_local);
}
return (String)STRING_INIT; return (String)STRING_INIT;
} }
@@ -393,50 +393,13 @@ String nvim_replace_termcodes(String str, Boolean from_part, Boolean do_lt,
return cstr_as_string(ptr); return cstr_as_string(ptr);
} }
/// Executes an ex-command and returns its (non-error) output. /// @deprecated
/// Shell |:!| output is not captured. /// @see nvim_exec
///
/// On execution error: fails with VimL error, does not update v:errmsg.
///
/// @param command Ex-command string
/// @param[out] err Error details (Vim error), if any
String nvim_command_output(String command, Error *err) String nvim_command_output(String command, Error *err)
FUNC_API_SINCE(1) FUNC_API_SINCE(1)
FUNC_API_DEPRECATED_SINCE(7)
{ {
const int save_msg_silent = msg_silent; return nvim_exec(command, true, err);
garray_T *const save_capture_ga = capture_ga;
garray_T capture_local;
ga_init(&capture_local, 1, 80);
try_start();
msg_silent++;
capture_ga = &capture_local;
do_cmdline_cmd(command.data);
capture_ga = save_capture_ga;
msg_silent = save_msg_silent;
try_end(err);
if (ERROR_SET(err)) {
goto theend;
}
if (capture_local.ga_len > 1) {
String s = (String){
.data = capture_local.ga_data,
.size = (size_t)capture_local.ga_len,
};
// redir usually (except :echon) prepends a newline.
if (s.data[0] == '\n') {
memmove(s.data, s.data + 1, s.size - 1);
s.data[s.size - 1] = '\0';
s.size = s.size - 1;
}
return s; // Caller will free the memory.
}
theend:
ga_clear(&capture_local);
return (String)STRING_INIT;
} }
/// Evaluates a VimL |expression|. /// Evaluates a VimL |expression|.

View File

@@ -254,7 +254,7 @@ static inline void ctx_save_funcs(Context *ctx, bool scriptonly)
size_t cmd_len = sizeof("func! ") + STRLEN(name); size_t cmd_len = sizeof("func! ") + STRLEN(name);
char *cmd = xmalloc(cmd_len); char *cmd = xmalloc(cmd_len);
snprintf(cmd, cmd_len, "func! %s", name); snprintf(cmd, cmd_len, "func! %s", name);
String func_body = nvim_command_output(cstr_as_string(cmd), &err); String func_body = nvim_exec(cstr_as_string(cmd), true, &err);
xfree(cmd); xfree(cmd);
if (!ERROR_SET(&err)) { if (!ERROR_SET(&err)) {
ADD(ctx->funcs, STRING_OBJ(func_body)); ADD(ctx->funcs, STRING_OBJ(func_body));

View File

@@ -3428,7 +3428,7 @@ char_u *get_scriptname(LastSet last_set, bool *should_free)
last_set.channel_id); last_set.channel_id);
return IObuff; return IObuff;
case SID_STR: case SID_STR:
return (char_u *)_(":source (no file)"); return (char_u *)_("anonymous :source");
default: default:
*should_free = true; *should_free = true;
return home_replace_save(NULL, return home_replace_save(NULL,

View File

@@ -296,25 +296,23 @@ int do_cmdline_cmd(const char *cmd)
DOCMD_NOWAIT|DOCMD_KEYTYPED); DOCMD_NOWAIT|DOCMD_KEYTYPED);
} }
/* /// do_cmdline(): execute one Ex command line
* do_cmdline(): execute one Ex command line ///
* /// 1. Execute "cmdline" when it is not NULL.
* 1. Execute "cmdline" when it is not NULL. /// If "cmdline" is NULL, or more lines are needed, fgetline() is used.
* If "cmdline" is NULL, or more lines are needed, fgetline() is used. /// 2. Split up in parts separated with '|'.
* 2. Split up in parts separated with '|'. ///
* /// This function can be called recursively!
* This function can be called recursively! ///
* /// flags:
* flags: /// DOCMD_VERBOSE - The command will be included in the error message.
* DOCMD_VERBOSE - The command will be included in the error message. /// DOCMD_NOWAIT - Don't call wait_return() and friends.
* DOCMD_NOWAIT - Don't call wait_return() and friends. /// DOCMD_REPEAT - Repeat execution until fgetline() returns NULL.
* DOCMD_REPEAT - Repeat execution until fgetline() returns NULL. /// DOCMD_KEYTYPED - Don't reset KeyTyped.
* DOCMD_KEYTYPED - Don't reset KeyTyped. /// DOCMD_EXCRESET - Reset the exception environment (used for debugging).
* DOCMD_EXCRESET - Reset the exception environment (used for debugging). /// DOCMD_KEEPLINE - Store first typed line (for repeating with ".").
* DOCMD_KEEPLINE - Store first typed line (for repeating with "."). ///
* /// @return FAIL if cmdline could not be executed, OK otherwise
* return FAIL if cmdline could not be executed, OK otherwise
*/
int do_cmdline(char_u *cmdline, LineGetter fgetline, int do_cmdline(char_u *cmdline, LineGetter fgetline,
void *cookie, /* argument for fgetline() */ void *cookie, /* argument for fgetline() */
int flags) int flags)

View File

@@ -585,13 +585,13 @@ describe('nvim_set_keymap, nvim_del_keymap', function()
end) end)
it('can set <expr> mappings whose RHS change dynamically', function() it('can set <expr> mappings whose RHS change dynamically', function()
meths.command_output([[ meths.exec([[
function! FlipFlop() abort function! FlipFlop() abort
if !exists('g:flip') | let g:flip = 0 | endif if !exists('g:flip') | let g:flip = 0 | endif
let g:flip = !g:flip let g:flip = !g:flip
return g:flip return g:flip
endfunction endfunction
]]) ]], true)
eq(1, meths.call_function('FlipFlop', {})) eq(1, meths.call_function('FlipFlop', {}))
eq(0, meths.call_function('FlipFlop', {})) eq(0, meths.call_function('FlipFlop', {}))
eq(1, meths.call_function('FlipFlop', {})) eq(1, meths.call_function('FlipFlop', {}))

View File

@@ -84,7 +84,7 @@ describe('API', function()
it(':verbose set {option}?', function() it(':verbose set {option}?', function()
nvim('exec', 'set nowrap', false) nvim('exec', 'set nowrap', false)
eq('nowrap\n\tLast set from :source (no file)', eq('nowrap\n\tLast set from anonymous :source',
nvim('exec', 'verbose set wrap?', true)) nvim('exec', 'verbose set wrap?', true))
end) end)
@@ -1800,7 +1800,7 @@ describe('API', function()
eq(' 1 %a "[No Name]" line 1\n'.. eq(' 1 %a "[No Name]" line 1\n'..
' 3 h "[Scratch]" line 0\n'.. ' 3 h "[Scratch]" line 0\n'..
' 4 h "[Scratch]" line 0', ' 4 h "[Scratch]" line 0',
meths.command_output("ls")) meths.exec('ls', true))
-- current buffer didn't change -- current buffer didn't change
eq({id=1}, meths.get_current_buf()) eq({id=1}, meths.get_current_buf())

View File

@@ -11,10 +11,10 @@ describe('TabClosed', function()
repeat repeat
nvim('command', 'tabnew') nvim('command', 'tabnew')
until nvim('eval', 'tabpagenr()') == 6 -- current tab is now 6 until nvim('eval', 'tabpagenr()') == 6 -- current tab is now 6
eq("tabclosed:6:6:5", nvim('command_output', 'tabclose')) -- close last 6, current tab is now 5 eq("tabclosed:6:6:5", nvim('exec', 'tabclose', true)) -- close last 6, current tab is now 5
eq("tabclosed:5:5:4", nvim('command_output', 'close')) -- close last window on tab, closes tab eq("tabclosed:5:5:4", nvim('exec', 'close', true)) -- close last window on tab, closes tab
eq("tabclosed:2:2:3", nvim('command_output', '2tabclose')) -- close tab 2, current tab is now 3 eq("tabclosed:2:2:3", nvim('exec', '2tabclose', true)) -- close tab 2, current tab is now 3
eq("tabclosed:1:1:2\ntabclosed:1:1:1", nvim('command_output', 'tabonly')) -- close tabs 1 and 2 eq("tabclosed:1:1:2\ntabclosed:1:1:1", nvim('exec', 'tabonly', true)) -- close tabs 1 and 2
end) end)
it('is triggered when closing a window via bdelete from another tab', function() it('is triggered when closing a window via bdelete from another tab', function()
@@ -23,7 +23,7 @@ describe('TabClosed', function()
nvim('command', '1tabedit Xtestfile') nvim('command', '1tabedit Xtestfile')
nvim('command', 'normal! 1gt') nvim('command', 'normal! 1gt')
eq({1, 3}, nvim('eval', '[tabpagenr(), tabpagenr("$")]')) eq({1, 3}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
eq("tabclosed:2:2:1\ntabclosed:2:2:1", nvim('command_output', 'bdelete Xtestfile')) eq("tabclosed:2:2:1\ntabclosed:2:2:1", nvim('exec', 'bdelete Xtestfile', true))
eq({1, 1}, nvim('eval', '[tabpagenr(), tabpagenr("$")]')) eq({1, 1}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
end) end)
@@ -35,7 +35,7 @@ describe('TabClosed', function()
-- Only one tab is closed, and the alternate file is used for the other. -- Only one tab is closed, and the alternate file is used for the other.
eq({2, 3}, nvim('eval', '[tabpagenr(), tabpagenr("$")]')) eq({2, 3}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
eq("tabclosed:2:2:2", nvim('command_output', 'bdelete Xtestfile2')) eq("tabclosed:2:2:2", nvim('exec', 'bdelete Xtestfile2', true))
eq('Xtestfile1', nvim('eval', 'bufname("")')) eq('Xtestfile1', nvim('eval', 'bufname("")'))
end) end)
end) end)
@@ -48,9 +48,9 @@ describe('TabClosed', function()
nvim('command', 'tabnew') nvim('command', 'tabnew')
until nvim('eval', 'tabpagenr()') == 7 -- current tab is now 7 until nvim('eval', 'tabpagenr()') == 7 -- current tab is now 7
-- sanity check, we shouldn't match on tabs with numbers other than 2 -- sanity check, we shouldn't match on tabs with numbers other than 2
eq("tabclosed:7:7:6", nvim('command_output', 'tabclose')) eq("tabclosed:7:7:6", nvim('exec', 'tabclose', true))
-- close tab page 2, current tab is now 5 -- close tab page 2, current tab is now 5
eq("tabclosed:2:2:5\ntabclosed:match", nvim('command_output', '2tabclose')) eq("tabclosed:2:2:5\ntabclosed:match", nvim('exec', '2tabclose', true))
end) end)
end) end)
@@ -59,7 +59,7 @@ describe('TabClosed', function()
nvim('command', 'au! TabClosed * echom "tabclosed:".expand("<afile>").":".expand("<amatch>").":".tabpagenr()') nvim('command', 'au! TabClosed * echom "tabclosed:".expand("<afile>").":".expand("<amatch>").":".tabpagenr()')
nvim('command', 'tabedit Xtestfile') nvim('command', 'tabedit Xtestfile')
eq({2, 2}, nvim('eval', '[tabpagenr(), tabpagenr("$")]')) eq({2, 2}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
eq("tabclosed:2:2:1", nvim('command_output', 'close')) eq("tabclosed:2:2:1", nvim('exec', 'close', true))
eq({1, 1}, nvim('eval', '[tabpagenr(), tabpagenr("$")]')) eq({1, 1}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
end) end)
end) end)

View File

@@ -7,15 +7,15 @@ describe('TabNewEntered', function()
it('matches when entering any new tab', function() it('matches when entering any new tab', function()
clear() clear()
nvim('command', 'au! TabNewEntered * echom "tabnewentered:".tabpagenr().":".bufnr("")') nvim('command', 'au! TabNewEntered * echom "tabnewentered:".tabpagenr().":".bufnr("")')
eq("tabnewentered:2:2", nvim('command_output', 'tabnew')) eq("tabnewentered:2:2", nvim('exec', 'tabnew', true))
eq("tabnewentered:3:3", nvim('command_output', 'tabnew test.x2')) eq("tabnewentered:3:3", nvim('exec', 'tabnew test.x2', true))
end) end)
end) end)
describe('with FILE as <afile>', function() describe('with FILE as <afile>', function()
it('matches when opening a new tab for FILE', function() it('matches when opening a new tab for FILE', function()
nvim('command', 'au! TabNewEntered Xtest-tabnewentered echom "tabnewentered:match"') nvim('command', 'au! TabNewEntered Xtest-tabnewentered echom "tabnewentered:match"')
eq('tabnewentered:4:4\ntabnewentered:match', eq('tabnewentered:4:4\ntabnewentered:match',
nvim('command_output', 'tabnew Xtest-tabnewentered')) nvim('exec', 'tabnew Xtest-tabnewentered', true))
end) end)
end) end)
describe('with CTRL-W T', function() describe('with CTRL-W T', function()
@@ -24,7 +24,7 @@ describe('TabNewEntered', function()
nvim('command', 'au! TabNewEntered * echom "entered"') nvim('command', 'au! TabNewEntered * echom "entered"')
nvim('command', 'tabnew test.x2') nvim('command', 'tabnew test.x2')
nvim('command', 'split') nvim('command', 'split')
eq('entered', nvim('command_output', 'execute "normal \\<C-W>T"')) eq('entered', nvim('exec', 'execute "normal \\<C-W>T"', true))
end) end)
end) end)
end) end)

View File

@@ -22,7 +22,7 @@ describe('script_get-based command', function()
%s %s %s %s
endif endif
]])):format(cmd, garbage))) ]])):format(cmd, garbage)))
eq('', meths.command_output('messages')) eq('', meths.exec('messages', true))
if check_neq then if check_neq then
neq(0, exc_exec(dedent([[ neq(0, exc_exec(dedent([[
%s %s %s %s
@@ -37,7 +37,7 @@ describe('script_get-based command', function()
EOF EOF
endif endif
]])):format(cmd, garbage))) ]])):format(cmd, garbage)))
eq('', meths.command_output('messages')) eq('', meths.exec('messages', true))
if check_neq then if check_neq then
eq(true, pcall(source, (dedent([[ eq(true, pcall(source, (dedent([[
let g:exc = 0 let g:exc = 0

View File

@@ -16,8 +16,8 @@ describe('sign', function()
nvim('command', 'sign place 34 line=3 name=Foo buffer='..buf2) nvim('command', 'sign place 34 line=3 name=Foo buffer='..buf2)
-- now unplace without specifying a buffer -- now unplace without specifying a buffer
nvim('command', 'sign unplace 34') nvim('command', 'sign unplace 34')
eq("--- Signs ---\n", nvim('command_output', 'sign place buffer='..buf1)) eq("--- Signs ---\n", nvim('exec', 'sign place buffer='..buf1, true))
eq("--- Signs ---\n", nvim('command_output', 'sign place buffer='..buf2)) eq("--- Signs ---\n", nvim('exec', 'sign place buffer='..buf2, true))
end) end)
end) end)
end) end)

View File

@@ -30,7 +30,7 @@ describe("'keymap' / :lmap", function()
command('lmapclear <buffer>') command('lmapclear <buffer>')
command('set keymap=dvorak') command('set keymap=dvorak')
command('set nomore') command('set nomore')
local bindings = funcs.nvim_command_output('lmap') local bindings = funcs.nvim_exec('lmap', true)
eq(dedent([[ eq(dedent([[
l " @_ l " @_

View File

@@ -60,7 +60,7 @@ describe(':terminal buffer', function()
end) end)
it('does not create swap files', function() it('does not create swap files', function()
local swapfile = nvim('command_output', 'swapname'):gsub('\n', '') local swapfile = nvim('exec', 'swapname', true):gsub('\n', '')
eq(nil, io.open(swapfile)) eq(nil, io.open(swapfile))
end) end)

View File

@@ -362,7 +362,7 @@ describe('Command-line coloring', function()
{EOB:~ }| {EOB:~ }|
:e^ | :e^ |
]]) ]])
eq('', meths.command_output('messages')) eq('', meths.exec('messages', true))
end) end)
it('silences :echon', function() it('silences :echon', function()
set_color_cb('Echoning') set_color_cb('Echoning')
@@ -377,7 +377,7 @@ describe('Command-line coloring', function()
{EOB:~ }| {EOB:~ }|
:e^ | :e^ |
]]) ]])
eq('', meths.command_output('messages')) eq('', meths.exec('messages', true))
end) end)
it('silences :echomsg', function() it('silences :echomsg', function()
set_color_cb('Echomsging') set_color_cb('Echomsging')
@@ -392,7 +392,7 @@ describe('Command-line coloring', function()
{EOB:~ }| {EOB:~ }|
:e^ | :e^ |
]]) ]])
eq('', meths.command_output('messages')) eq('', meths.exec('messages', true))
end) end)
it('does the right thing when throwing', function() it('does the right thing when throwing', function()
set_color_cb('Throwing') set_color_cb('Throwing')
@@ -857,7 +857,7 @@ describe('Ex commands coloring', function()
]]) ]])
feed('<CR>') feed('<CR>')
eq('Error detected while processing :\nE605: Exception not caught: 42\nE749: empty buffer', eq('Error detected while processing :\nE605: Exception not caught: 42\nE749: empty buffer',
meths.command_output('messages')) meths.exec('messages', true))
end) end)
it('errors out when failing to get callback', function() it('errors out when failing to get callback', function()
meths.set_var('Nvim_color_cmdline', 42) meths.set_var('Nvim_color_cmdline', 42)

View File

@@ -861,7 +861,7 @@ describe('ui/builtin messages', function()
-- screen size doesn't affect internal output #10285 -- screen size doesn't affect internal output #10285
eq('ErrorMsg xxx ctermfg=15 ctermbg=1 guifg=White guibg=Red', eq('ErrorMsg xxx ctermfg=15 ctermbg=1 guifg=White guibg=Red',
meths.command_output("hi ErrorMsg")) meths.exec("hi ErrorMsg", true))
end) end)
it(':syntax list langGroup output', function() it(':syntax list langGroup output', function()
@@ -900,7 +900,7 @@ vimComment xxx match /\s"[^\-:.%#=*].*$/ms=s+1,lc=1 excludenl contains=@vim
match /\<endif\s\+".*$/ms=s+5,lc=5 contains=@vimCommentGroup,vimCommentString match /\<endif\s\+".*$/ms=s+5,lc=5 contains=@vimCommentGroup,vimCommentString
match /\<else\s\+".*$/ms=s+4,lc=4 contains=@vimCommentGroup,vimCommentString match /\<else\s\+".*$/ms=s+4,lc=4 contains=@vimCommentGroup,vimCommentString
links to Comment]], links to Comment]],
meths.command_output('syntax list vimComment')) meths.exec('syntax list vimComment', true))
-- luacheck: pop -- luacheck: pop
end) end)