Skip to content

Commit 038be27

Browse files
yegappanchrisbra
authored andcommitted
patch 9.1.1239: if_python: no tuple data type support
Problem: if_python: no tuple data type support (after v9.1.1232) Solution: Add support for using Vim tuple in the python interface (Yegappan Lakshmanan) closes: #16964 Signed-off-by: Yegappan Lakshmanan <[email protected]> Signed-off-by: Christian Brabandt <[email protected]>
1 parent 9d5487f commit 038be27

17 files changed

Lines changed: 1065 additions & 32 deletions

runtime/doc/builtin.txt

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
*builtin.txt* For Vim version 9.1. Last change: 2025 Mar 24
1+
*builtin.txt* For Vim version 9.1. Last change: 2025 Mar 26
22

33

44
VIM REFERENCE MANUAL by Bram Moolenaar
@@ -8336,13 +8336,14 @@ py3eval({expr} [, {locals}]) *py3eval()*
83368336
converted to Vim data structures.
83378337
If a {locals} |Dictionary| is given, it defines set of local
83388338
variables available in the expression. The keys are variable
8339-
names and the values are the variable values. |Dictionary| and
8340-
|List| values are referenced, and may be updated by the
8341-
expression (as if |python-bindeval| was used).
8339+
names and the values are the variable values. |Dictionary|,
8340+
|List| and |Tuple| values are referenced, and may be updated
8341+
by the expression (as if |python-bindeval| was used).
83428342
Numbers and strings are returned as they are (strings are
83438343
copied though, Unicode strings are additionally converted to
83448344
'encoding').
83458345
Lists are represented as Vim |List| type.
8346+
Tuples are represented as Vim |Tuple| type.
83468347
Dictionaries are represented as Vim |Dictionary| type with
83478348
keys converted to strings.
83488349
Note that in a `:def` function local variables are not visible
@@ -8364,6 +8365,7 @@ pyeval({expr} [, {locals}]) *pyeval()*
83648365
Numbers and strings are returned as they are (strings are
83658366
copied though).
83668367
Lists are represented as Vim |List| type.
8368+
Tuples are represented as Vim |Tuple| type.
83678369
Dictionaries are represented as Vim |Dictionary| type,
83688370
non-string keys result in error.
83698371
Note that in a `:def` function local variables are not visible

runtime/doc/if_pyth.txt

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
*if_pyth.txt* For Vim version 9.1. Last change: 2024 Nov 09
1+
*if_pyth.txt* For Vim version 9.1. Last change: 2025 Mar 26
22

33

44
VIM REFERENCE MANUAL by Paul Moore
@@ -184,8 +184,9 @@ vim.eval(str) *python-eval*
184184
evaluator (see |expression|). Returns the expression result as:
185185
- a string if the Vim expression evaluates to a string or number
186186
- a list if the Vim expression evaluates to a Vim list
187+
- a tuple if the Vim expression evaluates to a Vim tuple
187188
- a dictionary if the Vim expression evaluates to a Vim dictionary
188-
Dictionaries and lists are recursively expanded.
189+
Dictionaries, lists and tuples are recursively expanded.
189190
Examples: >
190191
:" value of the 'textwidth' option
191192
:py text_width = vim.eval("&tw")
@@ -196,6 +197,8 @@ vim.eval(str) *python-eval*
196197
:" Result is a string! Use string.atoi() to convert to a number.
197198
:py str = vim.eval("12+12")
198199
:
200+
:py tuple = vim.eval('(1, 2, 3)')
201+
:
199202
:py tagList = vim.eval('taglist("eval_expr")')
200203
< The latter will return a python list of python dicts, for instance:
201204
[{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name': ~
@@ -207,8 +210,8 @@ vim.eval(str) *python-eval*
207210

208211
vim.bindeval(str) *python-bindeval*
209212
Like |python-eval|, but returns special objects described in
210-
|python-bindeval-objects|. These python objects let you modify (|List|
211-
or |Dictionary|) or call (|Funcref|) vim objects.
213+
|python-bindeval-objects|. These python objects let you modify
214+
(|List|, |Tuple| or |Dictionary|) or call (|Funcref|) vim objects.
212215

213216
vim.strwidth(str) *python-strwidth*
214217
Like |strwidth()|: returns number of display cells str occupies, tab
@@ -688,6 +691,22 @@ vim.List object *python-List*
688691
print isinstance(l, vim.List) # True
689692
class List(vim.List): # Subclassing
690693
694+
vim.Tuple object *python-Tuple*
695+
Sequence-like object providing access to vim |Tuple| type.
696+
Supports `.locked` attribute, see |python-.locked|. Also supports the
697+
following methods:
698+
Method Description ~
699+
__new__(), __new__(iterable)
700+
You can use `vim.Tuple()` to create new vim tuples.
701+
Without arguments constructs empty list.
702+
Examples: >
703+
t = vim.Tuple("abc") # Constructor, result: ('a', 'b', 'c')
704+
print t[1:] # slicing
705+
print t[0] # getting item
706+
for i in t: # iteration
707+
print isinstance(t, vim.Tuple) # True
708+
class Tuple(vim.Tuple): # Subclassing
709+
691710
vim.Function object *python-Function*
692711
Function-like object, acting like vim |Funcref| object. Accepts special
693712
keyword argument `self`, see |Dictionary-function|. You can also use

runtime/doc/tags

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9683,6 +9683,7 @@ python-2-and-3 if_pyth.txt /*python-2-and-3*
96839683
python-Dictionary if_pyth.txt /*python-Dictionary*
96849684
python-Function if_pyth.txt /*python-Function*
96859685
python-List if_pyth.txt /*python-List*
9686+
python-Tuple if_pyth.txt /*python-Tuple*
96869687
python-VIM_SPECIAL_PATH if_pyth.txt /*python-VIM_SPECIAL_PATH*
96879688
python-_get_paths if_pyth.txt /*python-_get_paths*
96889689
python-bindeval if_pyth.txt /*python-bindeval*

runtime/syntax/vim.vim

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
" Language: Vim script
33
" Maintainer: Hirohito Higashi <h.east.727 ATMARK gmail.com>
44
" Doug Kearns <[email protected]>
5-
" Last Change: 2025 Mar 18
5+
" Last Change: 2025 Mar 26
66
" Former Maintainer: Charles E. Campbell
77

88
" DO NOT CHANGE DIRECTLY.
@@ -132,16 +132,16 @@ syn case match
132132
syn keyword vimFuncName contained abs acos add and append appendbufline argc argidx arglistid argv asin assert_beeps assert_equal assert_equalfile assert_exception assert_fails assert_false assert_inrange assert_match assert_nobeep assert_notequal assert_notmatch assert_report assert_true atan atan2 autocmd_add autocmd_delete autocmd_get balloon_gettext balloon_show balloon_split base64_decode base64_encode bindtextdomain blob2list blob2str browse browsedir bufadd bufexists buflisted bufload bufloaded bufname bufnr bufwinid bufwinnr byte2line byteidx byteidxcomp call ceil ch_canread ch_close ch_close_in ch_evalexpr ch_evalraw ch_getbufnr ch_getjob ch_info ch_log ch_logfile ch_open ch_read ch_readblob ch_readraw ch_sendexpr ch_sendraw ch_setoptions ch_status changenr
133133
syn keyword vimFuncName contained char2nr charclass charcol charidx chdir cindent clearmatches col complete complete_add complete_check complete_info confirm copy cos cosh count cscope_connection cursor debugbreak deepcopy delete deletebufline did_filetype diff diff_filler diff_hlID digraph_get digraph_getlist digraph_set digraph_setlist echoraw empty environ err_teapot escape eval eventhandler executable execute exepath exists exists_compiled exp expand expandcmd extend extendnew feedkeys filecopy filereadable filewritable filter finddir findfile flatten flattennew float2nr floor fmod fnameescape fnamemodify foldclosed foldclosedend foldlevel foldtext foldtextresult foreach foreground fullcommand funcref function garbagecollect get getbufinfo getbufline getbufoneline
134134
syn keyword vimFuncName contained getbufvar getcellpixels getcellwidths getchangelist getchar getcharmod getcharpos getcharsearch getcharstr getcmdcomplpat getcmdcompltype getcmdline getcmdpos getcmdprompt getcmdscreenpos getcmdtype getcmdwintype getcompletion getcurpos getcursorcharpos getcwd getenv getfontname getfperm getfsize getftime getftype getimstatus getjumplist getline getloclist getmarklist getmatches getmousepos getmouseshape getpid getpos getqflist getreg getreginfo getregion getregionpos getregtype getscriptinfo getstacktrace gettabinfo gettabvar gettabwinvar gettagstack gettext getwininfo getwinpos getwinposx getwinposy getwinvar glob glob2regpat globpath has has_key haslocaldir hasmapto histadd histdel histget histnr hlID hlexists hlget hlset hostname
135-
syn keyword vimFuncName contained iconv id indent index indexof input inputdialog inputlist inputrestore inputsave inputsecret insert instanceof interrupt invert isabsolutepath isdirectory isinf islocked isnan items job_getchannel job_info job_setoptions job_start job_status job_stop join js_decode js_encode json_decode json_encode keys keytrans len libcall libcallnr line line2byte lispindent list2blob list2str listener_add listener_flush listener_remove localtime log log10 luaeval map maparg mapcheck maplist mapnew mapset match matchadd matchaddpos matcharg matchbufline matchdelete matchend matchfuzzy matchfuzzypos matchlist matchstr matchstrlist matchstrpos max menu_info min mkdir mode mzeval nextnonblank ngettext nr2char or pathshorten perleval popup_atcursor
135+
syn keyword vimFuncName contained iconv id indent index indexof input inputdialog inputlist inputrestore inputsave inputsecret insert instanceof interrupt invert isabsolutepath isdirectory isinf islocked isnan items job_getchannel job_info job_setoptions job_start job_status job_stop join js_decode js_encode json_decode json_encode keys keytrans len libcall libcallnr line line2byte lispindent list2blob list2str list2tuple listener_add listener_flush listener_remove localtime log log10 luaeval map maparg mapcheck maplist mapnew mapset match matchadd matchaddpos matcharg matchbufline matchdelete matchend matchfuzzy matchfuzzypos matchlist matchstr matchstrlist matchstrpos max menu_info min mkdir mode mzeval nextnonblank ngettext nr2char or pathshorten perleval popup_atcursor
136136
syn keyword vimFuncName contained popup_beval popup_clear popup_close popup_create popup_dialog popup_filter_menu popup_filter_yesno popup_findecho popup_findinfo popup_findpreview popup_getoptions popup_getpos popup_hide popup_list popup_locate popup_menu popup_move popup_notification popup_setbuf popup_setoptions popup_settext popup_show pow prevnonblank printf prompt_getprompt prompt_setcallback prompt_setinterrupt prompt_setprompt prop_add prop_add_list prop_clear prop_find prop_list prop_remove prop_type_add prop_type_change prop_type_delete prop_type_get prop_type_list pum_getpos pumvisible py3eval pyeval pyxeval rand range readblob readdir readdirex readfile reduce reg_executing reg_recording reltime reltimefloat reltimestr remote_expr remote_foreground
137137
syn keyword vimFuncName contained remote_peek remote_read remote_send remote_startserver remove rename repeat resolve reverse round rubyeval screenattr screenchar screenchars screencol screenpos screenrow screenstring search searchcount searchdecl searchpair searchpairpos searchpos server2client serverlist setbufline setbufvar setcellwidths setcharpos setcharsearch setcmdline setcmdpos setcursorcharpos setenv setfperm setline setloclist setmatches setpos setqflist setreg settabvar settabwinvar settagstack setwinvar sha256 shellescape shiftwidth sign_define sign_getdefined sign_getplaced sign_jump sign_place sign_placelist sign_undefine sign_unplace sign_unplacelist simplify sin sinh slice sort sound_clear sound_playevent sound_playfile sound_stop soundfold spellbadword
138138
syn keyword vimFuncName contained spellsuggest split sqrt srand state str2blob str2float str2list str2nr strcharlen strcharpart strchars strdisplaywidth strftime strgetchar stridx string strlen strpart strptime strridx strtrans strutf16len strwidth submatch substitute swapfilelist swapinfo swapname synID synIDattr synIDtrans synconcealed synstack system systemlist tabpagebuflist tabpagenr tabpagewinnr tagfiles taglist tan tanh tempname term_dumpdiff term_dumpload term_dumpwrite term_getaltscreen term_getansicolors term_getattr term_getcursor term_getjob term_getline term_getscrolled term_getsize term_getstatus term_gettitle term_gettty term_list term_scrape term_sendkeys term_setansicolors term_setapi term_setkill term_setrestore term_setsize term_start term_wait
139-
syn keyword vimFuncName contained terminalprops test_alloc_fail test_autochdir test_feedinput test_garbagecollect_now test_garbagecollect_soon test_getvalue test_gui_event test_ignore_error test_mswin_event test_null_blob test_null_channel test_null_dict test_null_function test_null_job test_null_list test_null_partial test_null_string test_option_not_set test_override test_refcount test_setmouse test_settime test_srand_seed test_unknown test_void timer_info timer_pause timer_start timer_stop timer_stopall tolower toupper tr trim trunc type typename undofile undotree uniq utf16idx values virtcol virtcol2col visualmode wildmenumode win_execute win_findbuf win_getid win_gettype win_gotoid win_id2tabwin win_id2win win_move_separator win_move_statusline win_screenpos
140-
syn keyword vimFuncName contained win_splitmove winbufnr wincol windowsversion winheight winlayout winline winnr winrestcmd winrestview winsaveview winwidth wordcount writefile xor
139+
syn keyword vimFuncName contained terminalprops test_alloc_fail test_autochdir test_feedinput test_garbagecollect_now test_garbagecollect_soon test_getvalue test_gui_event test_ignore_error test_mswin_event test_null_blob test_null_channel test_null_dict test_null_function test_null_job test_null_list test_null_partial test_null_string test_null_tuple test_option_not_set test_override test_refcount test_setmouse test_settime test_srand_seed test_unknown test_void timer_info timer_pause timer_start timer_stop timer_stopall tolower toupper tr trim trunc tuple2list type typename undofile undotree uniq utf16idx values virtcol virtcol2col visualmode wildmenumode win_execute win_findbuf win_getid win_gettype win_gotoid win_id2tabwin win_id2win win_move_separator win_move_statusline
140+
syn keyword vimFuncName contained win_screenpos win_splitmove winbufnr wincol windowsversion winheight winlayout winline winnr winrestcmd winrestview winsaveview winwidth wordcount writefile xor
141141
" Predefined variable names {{{2
142142
" GEN_SYN_VIM: vimVarName, START_STR='syn keyword vimVimVarName contained', END_STR=''
143143
syn keyword vimVimVarName contained count count1 prevcount errmsg warningmsg statusmsg shell_error this_session version lnum termresponse fname lang lc_time ctype charconvert_from charconvert_to fname_in fname_out fname_new fname_diff cmdarg foldstart foldend folddashes foldlevel progname servername dying exception throwpoint register cmdbang insertmode val key profiling fcs_reason fcs_choice beval_bufnr beval_winnr beval_winid beval_lnum beval_col beval_text scrollstart swapname swapchoice swapcommand char mouse_win mouse_winid mouse_lnum mouse_col operator searchforward hlsearch oldfiles windowid progpath completed_item option_new option_old option_oldlocal option_oldglobal option_command option_type errors false true none null numbermax numbermin numbersize
144-
syn keyword vimVimVarName contained vim_did_enter testing t_number t_string t_func t_list t_dict t_float t_bool t_none t_job t_channel t_blob t_class t_object termrfgresp termrbgresp termu7resp termstyleresp termblinkresp event versionlong echospace argv collate exiting colornames sizeofint sizeoflong sizeofpointer maxcol python3_version t_typealias t_enum t_enumvalue stacktrace
144+
syn keyword vimVimVarName contained vim_did_enter testing t_number t_string t_func t_list t_dict t_float t_bool t_none t_job t_channel t_blob t_class t_object termrfgresp termrbgresp termu7resp termstyleresp termblinkresp event versionlong echospace argv collate exiting colornames sizeofint sizeoflong sizeofpointer maxcol python3_version t_typealias t_enum t_enumvalue stacktrace t_tuple
145145

146146
"--- syntax here and above generated by runtime/syntax/generator/gen_syntax_vim.vim ---
147147

src/eval.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2050,7 +2050,7 @@ get_lval_subscript(
20502050
var2.v_type = VAR_UNKNOWN;
20512051
}
20522052

2053-
if (lp->ll_tuple != NULL)
2053+
if (lp->ll_tuple != NULL && (flags & GLV_READ_ONLY) == 0)
20542054
{
20552055
if (!quiet)
20562056
emsg(_(e_tuple_is_immutable));

src/evalfunc.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8632,6 +8632,9 @@ f_islocked(typval_T *argvars, typval_T *rettv)
86328632
else if (lv.ll_list != NULL)
86338633
// List item.
86348634
rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
8635+
else if (lv.ll_tuple != NULL)
8636+
// Tuple item.
8637+
rettv->vval.v_number = tv_islocked(lv.ll_tv);
86358638
else
86368639
// Dictionary item.
86378640
rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);

src/ex_docmd.c

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,6 @@ static void ex_tag_cmd(exarg_T *eap, char_u *name);
289289
# define ex_endif ex_ni
290290
# define ex_endtry ex_ni
291291
# define ex_endwhile ex_ni
292-
# define ex_enum ex_ni
293292
# define ex_eval ex_ni
294293
# define ex_execute ex_ni
295294
# define ex_finally ex_ni

src/gc.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,21 @@ set_ref_in_list_items(
438438
return abort;
439439
}
440440

441+
/*
442+
* Mark a tuple and its items with "copyID".
443+
* Returns TRUE if setting references failed somehow.
444+
*/
445+
int
446+
set_ref_in_tuple(tuple_T *tuple, int copyID)
447+
{
448+
if (tuple != NULL && tuple->tv_copyID != copyID)
449+
{
450+
tuple->tv_copyID = copyID;
451+
return set_ref_in_tuple_items(tuple, copyID, NULL, NULL);
452+
}
453+
return FALSE;
454+
}
455+
441456
/*
442457
* Mark all lists and dicts referenced through tuple "t" with "copyID".
443458
* "ht_stack" is used to add hashtabs to be marked. Can be NULL.

0 commit comments

Comments
 (0)