Can you access registers from python functions in vim

Question:

It seems vims python sripting is designed to edit buffer and files rather than work nicely with vims registers. You can use some of the vim packages commands to get access to the registers but its not pretty.

My solution for creating a vim function using python that uses a register
is something like this.

function printUnnamedRegister()
python <<EOF
print vim.eval('@@')
EOF
endfunction

Setting registers may also be possible using something like

function setUnnamedRegsiter()
python <<EOF
s = "Some "crazy" stringnwith interesting characters"
vim.command('let @@="%s"' % myescapefn(s) )
EOF
endfunction

However this feels a bit cumbersome and I’m not sure exactly what myescapefn should be.
So I’ve never been able to get the setting version to work properly.

So if there’s a way to do something more like

function printUnnamedRegister()
python <<EOF
print vim.getRegister('@')
EOF
endfunction

function setUnnamedRegsiter()
python <<EOF
s = "Some "crazy" stringnwith interesting characters"
vim.setRegister('@',s)
EOF
endfunction

Or even a nice version of myescapefn I could use then that would be very handy.

UPDATE:

Based on the solution by ZyX I’m using this piece of python

def setRegister(reg, value):
  vim.command( "let @%s='%s'" % (reg, value.replace("'","''") ) )
Asked By: Michael Anderson

||

Answers:

If you use single quotes everything you need is to replace every occurence of single quote with two single quotes.
Something like that:

python import vim, re
python def senclose(str): return "'"+re.sub(re.compile("'"), "''", str)+"'"
python vim.command("let @r="+senclose("string with single 'quotes'"))

Update: this method relies heavily on an (undocumented) feature of the difference between

let abc='string
with newline'

and

execute "let abc='stringnwith newline'"

: while the first fails the second succeeds (and it is not the single example of differences between newline handling in :execute and plain files). On the other hand, eval() is somewhat more expected to handle this since string("stringnwith newline") returns exactly the same thing senclose does, so I write this things now only using vim.eval:

python senclose = lambda str: "'"+str.replace("'", "''")+"'"
python vim.eval("setreg('@r', {0})".format(senclose("string with single 'quotes'")))
Answered By: ZyX
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.