2

So I wrote a small ulti-snips snippet with python interpolation. usually when you hit undo, after expanding the snippet, it goes back to trigger word. But in this case I have to hit the undo twice. I suspect it's the search function I am using. I would really appreciate some help on this. I would like to either use a better function than search or somehow use search (or whatever is causing this problem) to not pollute the undo history. Here is the snippet:

snippet super "Adds a super function for the current function" b
`!p
import vim
# get the class name
line_number = int(vim.eval('search("class .*(", "bn")'))
line = vim.current.buffer[line_number - 1]
class_name = re.findall(r'class\s+(.*?)\s*\(', line)[0]
# get the function signature
line_number = int(vim.eval('search("def.*self.*", "bn")'))
line = vim.current.buffer[line_number - 1]
func = re.findall(r'def\s+(.*):', line)[0]
matches = re.findall(r'(.*)\(self,?\s*(.*)\)', func)
snip.rv = 'super(%s, self).%s(%s)' % (class_name, matches[0][0], matches[0][1])
`
endsnippet
linusx
  • 306
  • 2
  • 10
  • You use `vim.eval('search`, which will move the cursor. this is the reason causing you undo twice. You can get current buffer content by `content = "\n".join(vim.current.buffer)`. then do the work in python. – SolaWing Dec 11 '15 at 01:48
  • I added a n flag to the command so that it does not move the cursor. Is there some better way of searching? – linusx Dec 11 '15 at 14:27

1 Answers1

1

You can work with text completely in python. python is more powerful than vim script. here is my example:

buf = vim.current.buffer
line_number = vim.current.window.cursor[0] - 1 # cursor line start from 1. so minus it
previous_lines = "\n".join(buf[0:line_number])

try:
    class_name = re.findall(r'class\s+(.*?)\s*\(', previous_lines)[-1]
    func_name, func_other_param = re.findall(r'def\s+(.*)\(self,?\s*(.*)?\):', previous_lines)[-1]
    snip.rv = 'super(%s, self).%s(%s)' % (class_name, func_name, func_other_param)
except IndexError as e:
    snip.rv = 'super'    # regex match fail.
SolaWing
  • 1,652
  • 12
  • 14