Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed python expression into :s command in vim?

Tags:

python

vim

I can use \=expr in :s command. For example, to convert timestamps format inplace:

:%s/\v<\d{10}>/\=strftime('%c', submatch(0))/g

But the functionality of built-in functions are so limited. To parse a timestamp, I'd like to use python script like this:

$ python
>>> import datetime
>>> d = 'Apr 11 2012'
>>> datetime.datetime.strptime(d, '%b %d %Y').isoformat()
'2012-04-11T00:00:00'

How to embed this py-expr into :s command?

:%s/\v\w+ \d{2} \d{4}/\={?py-expr?}/g

Thanks!

like image 521
kev Avatar asked Nov 04 '12 13:11

kev


1 Answers

If you have at least vim-7.3.569 then you may do the following:

:python import datetime
:%s/\v\w+\ \d{2}\ \d{4}/\=pyeval('datetime.datetime.strptime(vim.eval("submatch(0)"), "%b %d %Y").isoformat()')/g

. If you don’t you have recent vim you can emulate pyeval in this case:

function Pyeval(expr)
    python import json
    python vim.command('return '+json.dumps(eval(vim.eval('a:expr'))))
endfunction

, then replace pyeval in the above code with Pyeval.

like image 191
ZyX Avatar answered Sep 27 '22 22:09

ZyX