Vim Tips Wiki
(Insert TipProposed template + minor manual clean)
m (Q335r49 moved page Automatically Saving Lists to File to Back up Lists and Dictionaries to viminfo: No need to save to a separate file)
 
(One intermediate revision by one other user not shown)
Line 11: Line 11:
 
|category2=
 
|category2=
 
}}
 
}}
The "!" option in <code>set viminfo</code> stores string and number variables with all uppercase names to the viminfo file. It's possible to extend this behavior to dictionaries and lists too, writing to a file other than viminfo.
+
The "!" option in <code>set viminfo</code> stores string and number variables with all uppercase names to the viminfo file. A patch for vim 7.3 extends this behavior to lists and dictionaries, but apparently has problems with nested lists. This method doesn't have that limitation, and also has the advantage of working on earlier versions. It converts lists and dictionaries to a vimscript string, which then can be stored via the usual method in viminfo. The variables are recovered by executing that string.
   
'''Limitation''' There is no easy way to back up lists that are equivalent to each other, ie, this will make identical lists copies of each other. Before saving:
+
By the way, this doesn't preserve the identity of lists. Variables that point to the same list will become copies of different but equivalent lists after restoring.
<pre>
 
let G=[1,2]
 
let H=G
 
let G[0]=3
 
ec H[0]
 
"This will print 3
 
</pre>
 
And after restoring:
 
<pre>
 
let G[1]=4
 
ec H[1]
 
"This will print 2
 
</pre>
 
   
There are a few interesting bits here:
+
There are a few bits I had to look up:
   
*<code>Ctrl-A</code> lists all possible completions. We can get a list of all global variables via <code>:let g:<c-a></code>. This list can then be written to a variable by going back and changing the line to <code>:let v=...</code>
+
*<code>Ctrl-A</code> lists all possible completions. So you can get a list of all global variables via <code>:let g:<c-a></code>.
   
 
*For some reason directly writing a variable containing "\n" produces errors when sourcing the file, Vim treats it as an actual line break. We have to substitute the \n char with the string <code>'."\n".'</code>
*<code>type(...) > 1</code> means everything except for strings and numbers, that is, funcref, list, dic, float.
 
 
*<code>==#</code> compares strings case sensitively, allowing us to check whether a variable's name remains the same when converted to uppercase.
 
 
*<code>string()</code> converts a list or dictionary into the command used to produce it. Writing the string <code>"let var=..."</code> rather than the raw data is a convenient way to store variables since in order to recover the variables we can simply <code>:source</code> the file.
 
 
*<code>substitute(...)</code> For some reason directly writing a variable containing "\n" produces errors when sourcing the file, Vim treats it as an actual line break. We have to substitute the \n char with the string <code>'."\n".'</code>
 
 
*<code>au VimLeavePre</code> automatically calls this function on exiting Vim.
 
   
 
==Script==
 
==Script==
 
The following script can be placed in your [[vimrc]].
 
The following script can be placed in your [[vimrc]].
 
<pre>
 
<pre>
fun! WriteVars(filename)
+
fun! WriteVars()
silent execute "norm! :let g:\<c-a>'\<c-b>\<right>\<right>\<right>\<right>v='\<cr>"
+
sil exe "norm! :let g:\<c-a>'\<c-b>\<right>\<right>\<right>\<right>v='\<cr>"
let list=[]
+
let i=0
 
for name in split(v)
 
for name in split(v)
if name[2:]==#toupper(name[2:]) && eval("type(".name.")") > 1
+
if name[2:]==#toupper(name[2:]) && eval("type(".name.")")>1
call add(list,substitute("let ".name."="
+
let g:VARSAV_{i}=substitute("let".name."=".eval("string(".name.")"),"\n",'''."\\n".''',"g")
  +
let i+=1
\.eval("string(".name.")"),"\n",'''."\\n".''',"g"))
 
 
en
 
en
 
endfor
 
endfor
  +
"If the number of variables saved is less than last time, clear the extra ones
call writefile(list,a:filename)
 
  +
if exists("g:VARSAVES") && i<g:VARSAVES
  +
exe "unlet! ".join(map(range(i,g:VARSAVES),"'g:VARSAV_'.v:val"))
  +
en
  +
let g:VARSAVES=i
 
endfun
 
endfun
  +
fun! RestoreVars()
  +
if exists("g:VARSAVES")
  +
for i in range(g:VARSAVES)
  +
exe VARSAV_{i}
  +
endfor
  +
en
 
au VimLeavePre * call WriteVars()
 
</pre>
   
  +
To restore the variables, use <code>:call RestoreVars()</code>. Note that if you use this in your vimrc file, you'll have to use <code>:rviminfo</code> to manually read the viminfo file first since the vimrc file is processed before the viminfo.
au VimLeavePre * call WriteVars('vimlistsave')
 
if filereadable('vimlistsave')
 
source vimlistsave
 
endif
 
</pre>
 
   
 
==Comments==
 
==Comments==

Latest revision as of 02:31, 23 July 2013

Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created October 6, 2012 · complexity basic · author Q335r49 · version 7.0

The "!" option in set viminfo stores string and number variables with all uppercase names to the viminfo file. A patch for vim 7.3 extends this behavior to lists and dictionaries, but apparently has problems with nested lists. This method doesn't have that limitation, and also has the advantage of working on earlier versions. It converts lists and dictionaries to a vimscript string, which then can be stored via the usual method in viminfo. The variables are recovered by executing that string.

By the way, this doesn't preserve the identity of lists. Variables that point to the same list will become copies of different but equivalent lists after restoring.

There are a few bits I had to look up:

  • Ctrl-A lists all possible completions. So you can get a list of all global variables via :let g:<c-a>.
  • For some reason directly writing a variable containing "\n" produces errors when sourcing the file, Vim treats it as an actual line break. We have to substitute the \n char with the string '."\n".'

Script[]

The following script can be placed in your vimrc.

fun! WriteVars()
    sil exe "norm! :let g:\<c-a>'\<c-b>\<right>\<right>\<right>\<right>v='\<cr>"
    let i=0
    for name in split(v)
        if name[2:]==#toupper(name[2:])	&& eval("type(".name.")")>1
            let g:VARSAV_{i}=substitute("let".name."=".eval("string(".name.")"),"\n",'''."\\n".''',"g")
            let i+=1
        en
    endfor
    "If the number of variables saved is less than last time, clear the extra ones
    if exists("g:VARSAVES") && i<g:VARSAVES
        exe "unlet! ".join(map(range(i,g:VARSAVES),"'g:VARSAV_'.v:val"))
    en
    let g:VARSAVES=i
endfun
fun! RestoreVars()
    if exists("g:VARSAVES")
        for i in range(g:VARSAVES)
            exe VARSAV_{i}
    endfor
en
au VimLeavePre * call WriteVars()

To restore the variables, use :call RestoreVars(). Note that if you use this in your vimrc file, you'll have to use :rviminfo to manually read the viminfo file first since the vimrc file is processed before the viminfo.

Comments[]

Does this script do anything not done by built-in Vim functionality, after version 7.3.30? --Fritzophrenic (talk) 04:49, October 7, 2012 (UTC)

I'm still running 7.3 compiled by someone long ago for android -- I don't have the means to compile a newer version. Also, the Windows version linked to from the vim.org website isn't patched. I haven't tested the patched version, the help file diff says "Nested List and Dict items may not be read back correctly, you end up with a string representation instead.". I'm not sure what they mean by "may", but this method does nested lists just fine.

It still doesn't do "pointers to the same list" of course, which probably can't be done in vimscript and would definitely require a patch. In my own vimrc file, I've added something along the lines of

if has_key(eval('dictname'),"reinitafterstorate")
  call add(list,"call ".dictname.".reinitafterstorage()")
end

into WriteVar(), so that the reinitafterstorage function would reinitialize any lists in the dictionary so that they point to the same address. I remember being really confused the first time this happened. --Q335r49 October 7, 2012