Skip to content

Instantly share code, notes, and snippets.

@tranch
Forked from vpetro/gist:1204166
Last active February 28, 2018 03:24
Show Gist options
  • Save tranch/2994eeeab39104953f2505d9b5ce36e1 to your computer and use it in GitHub Desktop.
Save tranch/2994eeeab39104953f2505d9b5ce36e1 to your computer and use it in GitHub Desktop.
add docstring for python function in vim
function! WriteParams()
python << endpython
import re
import vim
# get the function definition line
line = vim.eval("getline(line('.'))")
# get the number of spaces to add to the start of the line
num_spaces = 4 + len(line) - len(line.lstrip())
# get the line number wher to do the insertion
line_number = int(vim.eval("line('.')"))
# find the parameter names in the function definition
params = re.findall("[\w=]+", line)[2:]
# the header and the footer of the doctstring
lines = ['"""', ""]
for param in params:
# skip the 'self' since it doesn't have to be documented.
if param == "self":
continue
# handle the default argument parameters
if "=" in param:
param_name = param.split('=')[0]
param_default_value = "".join(param.split('=')[1:])
lines.append(":param %s: (Default value: %s)" % (param_name, param_default_value))
lines.append(":type %s:" % param_name)
else:
lines.append(":param %s:" % param)
lines.append(":type %s:" % param)
lines.append(":returns:")
lines.append('"""')
# insert the contents of the list into the buffer
vim.current.buffer[:] = vim.current.buffer[:line_number] + [(" "*num_spaces)+line for line in lines] + vim.current.buffer[line_number:]
endpython
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment