vim-patch:8.2.0924: cannot save and restore a register properly

Problem:    Cannot save and restore a register properly.
Solution:   Add getreginfo() and make setreg() accept a dictionary. (Andy
            Massimino, closes vim/vim#3370)
bb861e293e

Cherry-pick eval.txt changes for getreginfo() from:
6aa57295cf
207f009326
This commit is contained in:
Sean Dewar 2021-05-18 22:53:53 +01:00
parent 74ddd14241
commit f9779facca
No known key found for this signature in database
GPG Key ID: 08CC2C83AD41B581
9 changed files with 226 additions and 18 deletions

View File

@ -2436,8 +2436,9 @@ getpos({expr}) List position of cursor, mark, etc.
getqflist() List list of quickfix items
getqflist({what}) Dict get specific quickfix list properties
getreg([{regname} [, 1 [, {list}]]])
String or List contents of register
getregtype([{regname}]) String type of register
String or List contents of a register
getreginfo([{regname}]) Dict information about a register
getregtype([{regname}]) String type of a register
gettabinfo([{expr}]) List list of tab pages
gettabvar({nr}, {varname} [, {def}])
any variable {varname} in tab {nr} or {def}
@ -5247,6 +5248,32 @@ getreg([{regname} [, 1 [, {list}]]]) *getreg()*
If {regname} is not specified, |v:register| is used.
getreginfo([{regname}]) *getreginfo()*
Returns detailed information about register {regname} as a
Dictionary with the following entries:
regcontents List of lines contained in register
{regname}, like
|getreg|({regname}, 1, 1).
regtype the type of register {regname}, as in
|getregtype()|.
isunnamed Boolean flag, v:true if this register
is currently pointed to by the unnamed
register.
points_to for the unnamed register, gives the
single letter name of the register
currently pointed to (see |quotequote|).
For example, after deleting a line
with `dd`, this field will be "1",
which is the register that got the
deleted text.
The {regname} argument is a string. If {regname} is invalid
or not set, an empty Dictionary will be returned.
If {regname} is not specified, |v:register| is used.
The returned Dictionary can be passed to |setreg()|.
Can also be used as a |method|: >
GetRegname()->getreginfo()
getregtype([{regname}]) *getregtype()*
The result is a String, which is type of register {regname}.
@ -8435,8 +8462,8 @@ setreg({regname}, {value} [, {options}])
Set the register {regname} to {value}.
The {regname} argument is a string.
{value} may be any value returned by |getreg()|, including
a |List|.
{value} may be any value returned by |getreg()| or
|getreginfo()|, including a |List| or |Dict|.
If {options} contains "a" or {regname} is upper case,
then the value is appended.
@ -8466,9 +8493,13 @@ setreg({regname}, {value} [, {options}])
:call setreg(v:register, @*)
:call setreg('*', @%, 'ac')
:call setreg('a', "1\n2\n3", 'b5')
:call setreg('"', { 'points_to': 'a'})
< This example shows using the functions to save and restore a
register: >
:let var_a = getreginfo()
:call setreg('a', var_a)
< or: >
:let var_a = getreg('a', 1, 1)
:let var_amode = getregtype('a')
....

View File

@ -1025,6 +1025,7 @@ Various: *various-functions*
undotree() return the state of the undo tree
getreg() get contents of a register
getreginfo() get information about a register
getregtype() get type of a register
setreg() set contents and type of a register
reg_executing() return the name of the register being executed

View File

@ -166,6 +166,7 @@ return {
getpos={args=1},
getqflist={args={0, 1}},
getreg={args={0, 3}},
getreginfo={args={0, 1}, base=1},
getregtype={args={0, 1}},
gettabinfo={args={0, 1}},
gettabvar={args={2, 3}},

View File

@ -7218,6 +7218,61 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
fclose(fd);
}
/// "getreginfo()" function
static void f_getreginfo(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *strregname;
if (argvars[0].v_type != VAR_UNKNOWN) {
strregname = tv_get_string_chk(&argvars[0]);
if (strregname == NULL) {
return;
}
} else {
strregname = (const char *)get_vim_var_str(VV_REG);
}
int regname = (strregname == NULL ? '"' : *strregname);
if (regname == 0 || regname == '@') {
regname = '"';
}
tv_dict_alloc_ret(rettv);
dict_T *const dict = rettv->vval.v_dict;
list_T *const list = get_reg_contents(regname, kGRegExprSrc | kGRegList);
if (list == NULL) {
return;
}
tv_dict_add_list(dict, S_LEN("regcontents"), list);
char buf[NUMBUFLEN + 2];
buf[0] = NUL;
buf[1] = NUL;
colnr_T reglen = 0;
switch (get_reg_type(regname, &reglen)) {
case kMTLineWise:
buf[0] = 'V';
break;
case kMTCharWise:
buf[0] = 'v';
break;
case kMTBlockWise:
vim_snprintf(buf, sizeof(buf), "%c%d", Ctrl_V, reglen + 1);
break;
case kMTUnknown:
abort();
}
tv_dict_add_str(dict, S_LEN("regtype"), buf);
buf[0] = get_register_name(get_unname_register());
buf[1] = NUL;
if (regname == '"') {
tv_dict_add_str(dict, S_LEN("points_to"), buf);
} else {
tv_dict_add_bool(dict, S_LEN("isunnamed"), regname == buf[0] ? kBoolVarTrue : kBoolVarFalse);
}
}
// "reg_executing()" function
static void f_reg_executing(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
@ -9063,6 +9118,48 @@ static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
regname = '"';
}
const typval_T *regcontents = NULL;
int pointreg = 0;
if (argvars[1].v_type == VAR_DICT) {
dict_T *const d = argvars[1].vval.v_dict;
dictitem_T *const di = tv_dict_find(d, "regcontents", -1);
if (di != NULL) {
regcontents = &di->di_tv;
}
const char *stropt = tv_dict_get_string(d, "regtype", false);
if (stropt != NULL) {
switch (*stropt) {
case 'v': // character-wise selection
yank_type = kMTCharWise;
break;
case 'V': // line-wise selection
yank_type = kMTLineWise;
break;
case Ctrl_V: // block-wise selection
yank_type = kMTBlockWise;
if (ascii_isdigit(stropt[1])) {
stropt++;
block_len = getdigits_long((char_u **)&stropt, true, 0) - 1;
stropt--;
}
break;
}
}
if (regname == '"') {
stropt = tv_dict_get_string(d, "points_to", false);
if (stropt != NULL) {
pointreg = *stropt;
regname = pointreg;
}
} else if (tv_dict_get_number(d, "isunnamed")) {
pointreg = regname;
}
} else {
regcontents = &argvars[1];
}
bool set_unnamed = false;
if (argvars[2].v_type != VAR_UNKNOWN) {
const char *stropt = tv_get_string_chk(&argvars[2]);
@ -9100,8 +9197,8 @@ static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
if (argvars[1].v_type == VAR_LIST) {
list_T *ll = argvars[1].vval.v_list;
if (regcontents != NULL && regcontents->v_type == VAR_LIST) {
list_T *const ll = regcontents->vval.v_list;
// If the list is NULL handle like an empty list.
const int len = tv_list_len(ll);
@ -9137,14 +9234,17 @@ free_lstval:
xfree(*--curallocval);
}
xfree(lstval);
} else {
const char *strval = tv_get_string_chk(&argvars[1]);
} else if (regcontents != NULL) {
const char *const strval = tv_get_string_chk(regcontents);
if (strval == NULL) {
return;
}
write_reg_contents_ex(regname, (const char_u *)strval, STRLEN(strval),
append, yank_type, block_len);
}
if (pointreg != 0) {
get_yank_register(pointreg, YREG_YANK);
}
rettv->vval.v_number = 0;
if (set_unnamed) {

View File

@ -804,12 +804,6 @@ bool valid_yank_reg(int regname, bool writing)
return false;
}
typedef enum {
YREG_PASTE,
YREG_YANK,
YREG_PUT,
} yreg_mode_t;
/// Return yankreg_T to use, according to the value of `regname`.
/// Cannot handle the '_' (black hole) register.
/// Must only be called with a valid register name!
@ -3650,6 +3644,12 @@ int get_register_name(int num)
}
}
/// @return the index of the register "" points to.
int get_unname_register(void)
{
return y_previous == NULL ? -1 : (int)(y_previous - &y_regs[0]);
}
/*
* ":dis" and ":registers": Display the contents of the yank registers.
*/

View File

@ -90,6 +90,13 @@ typedef struct yankreg {
dict_T *additional_data; ///< Additional data from ShaDa file.
} yankreg_T;
/// Modes for get_yank_register()
typedef enum {
YREG_PASTE,
YREG_YANK,
YREG_PUT,
} yreg_mode_t;
/// Convert register name into register index
///
/// @param[in] regname Register name.

View File

@ -294,7 +294,6 @@ func Test_setreg_basic()
call assert_fails('call setreg(1)', 'E119:')
call assert_fails('call setreg(1, 2, 3, 4)', 'E118:')
call assert_fails('call setreg([], 2)', 'E730:')
call assert_fails('call setreg(1, {})', 'E731:')
call assert_fails('call setreg(1, 2, [])', 'E730:')
call assert_fails('call setreg("/", ["1", "2"])', 'E883:')
call assert_fails('call setreg("=", ["1", "2"])', 'E883:')

View File

@ -283,4 +283,76 @@ func Test_insert_small_delete()
bwipe!
endfunc
" Test for getting register info
func Test_get_reginfo()
enew
call setline(1, ['foo', 'bar'])
exe 'norm! "zyy'
let info = getreginfo('"')
call assert_equal('z', info.points_to)
call setreg('y', 'baz')
call assert_equal('z', getreginfo('').points_to)
call setreg('y', { 'isunnamed': v:true })
call assert_equal('y', getreginfo('"').points_to)
exe '$put'
call assert_equal(getreg('y'), getline(3))
call setreg('', 'qux')
call assert_equal('0', getreginfo('').points_to)
call setreg('x', 'quux')
call assert_equal('0', getreginfo('').points_to)
let info = getreginfo('')
call assert_equal(getreg('', 1, 1), info.regcontents)
call assert_equal(getregtype(''), info.regtype)
exe "norm! 0\<c-v>e" .. '"zy'
let info = getreginfo('z')
call assert_equal(getreg('z', 1, 1), info.regcontents)
call assert_equal(getregtype('z'), info.regtype)
call assert_equal(1, +info.isunnamed)
let info = getreginfo('"')
call assert_equal('z', info.points_to)
bwipe!
endfunc
" Test for restoring register with dict from getreginfo
func Test_set_register_dict()
enew!
call setreg('"', #{ regcontents: ['one', 'two'],
\ regtype: 'V', points_to: 'z' })
call assert_equal(['one', 'two'], getreg('"', 1, 1))
let info = getreginfo('"')
call assert_equal('z', info.points_to)
call assert_equal('V', info.regtype)
call assert_equal(1, +getreginfo('z').isunnamed)
call setreg('x', #{ regcontents: ['three', 'four'],
\ regtype: 'v', isunnamed: v:true })
call assert_equal(['three', 'four'], getreg('"', 1, 1))
let info = getreginfo('"')
call assert_equal('x', info.points_to)
call assert_equal('v', info.regtype)
call assert_equal(1, +getreginfo('x').isunnamed)
call setreg('y', #{ regcontents: 'five',
\ regtype: "\<c-v>", isunnamed: v:false })
call assert_equal("\<c-v>4", getreginfo('y').regtype)
call assert_equal(0, +getreginfo('y').isunnamed)
call assert_equal(['three', 'four'], getreg('"', 1, 1))
call assert_equal('x', getreginfo('"').points_to)
call setreg('"', #{ regcontents: 'six' })
call assert_equal('0', getreginfo('"').points_to)
call assert_equal(1, +getreginfo('0').isunnamed)
call assert_equal(['six'], getreginfo('0').regcontents)
call assert_equal(['six'], getreginfo('"').regcontents)
bwipe!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@ -600,7 +600,6 @@ describe('eval', function()
command([[call ErrExe('call setreg(1)')]])
command([[call ErrExe('call setreg(1, 2, 3, 4)')]])
command([=[call ErrExe('call setreg([], 2)')]=])
command([[call ErrExe('call setreg(1, {})')]])
command([=[call ErrExe('call setreg(1, 2, [])')]=])
command([=[call ErrExe('call setreg("/", ["1", "2"])')]=])
command([=[call ErrExe('call setreg("=", ["1", "2"])')]=])
@ -615,8 +614,6 @@ describe('eval', function()
Vim(call):E118: Too many arguments for function: setreg
Executing call setreg([], 2)
Vim(call):E730: using List as a String
Executing call setreg(1, {})
Vim(call):E731: using Dictionary as a String
Executing call setreg(1, 2, [])
Vim(call):E730: using List as a String
Executing call setreg("/", ["1", "2"])