I am trying to write a function that allows me to insert a python import at the top of the file with the other imports, so that I can write a snippet that adds an import up there if it doesn't already exist. However, I am getting stuck right at the beginning: when I try to us the python function vim.current.buffer.append(), it results in two lines being inserted not one. For example:
snippet firstimport "Description" b
`!p vim.current.buffer.append('hi', 8)`
endsnippet
This snippet inserts two instances of 'hi' at lines 9 and 10. Running :py vim.current.buffer.append('hi', 8) from vim results in just one insertion at line 9. It seems like the python command is being run twice, is that possible?
@MikeDacre: That's the reason why I've implemented pre-expand/post-expand/jump actions mechanism in UltiSnips (see :h UltiSnips-snippet-actions). You cannot modify buffer directly from the interpolation, because interpolation code runs undefined number of times. You see 2 here because UltiSnips engine run interpolation first time when snippet initialized and then run it second time to insert actual value. In more complex snippet it can insert hi as well as 100 times.
Please, see how to use actions feature in the vim help, and regarding your issue there is a test, which shows how to write snippet which will insert import smthing in the beginning of file: https://github.com/SirVer/ultisnips/blob/master/test/test_SnippetActions.py#L126
Note, that you should use snip.buffer special variable to access and modify buffer inside such functions, not just plain vim.current.buffer.
The you so much @seletskiy, I obviously just didn't read the documentation well enough.
In case anyone else is interested, I just wrote a snippet that will scan for the wanted import in the imports at the top of the file, and add your import to either the start or the end of the imports if they are found there. The snippet code is long because it also handles inserting the snippet at the first blank line in the file that isn't in a comment string, or at the current line if there are both no imports and no blank lines.
The full snippet code is here: https://gist.github.com/MikeDacre/365d716258d13a833831
Thanks again for the tip @seletskiy, it works perfectly now.
@MikeDacre: No problem, you're welcome!
Most helpful comment
The you so much @seletskiy, I obviously just didn't read the documentation well enough.
In case anyone else is interested, I just wrote a snippet that will scan for the wanted import in the imports at the top of the file, and add your import to either the start or the end of the imports if they are found there. The snippet code is long because it also handles inserting the snippet at the first blank line in the file that isn't in a comment string, or at the current line if there are both no imports and no blank lines.
The full snippet code is here: https://gist.github.com/MikeDacre/365d716258d13a833831
Thanks again for the tip @seletskiy, it works perfectly now.