Created
September 8, 2011 18:17
-
-
Save vpetro/1204166 to your computer and use it in GitHub Desktop.
add docstring for python function in vim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Nice snippet, Befor using it i added:
After current line 5
search the previous method definition.
vim.command("normal ?def ^M")
And
replace current line 14 with (helps finding default string values)
find the parameter names in the function definition
params = re.findall("[\w="']+", line)[2:]