honza / vim-snippets

vim-snipmate default snippets (Previously snipmate-snippets)
MIT License
4.81k stars 2.03k forks source link

Is it possible to generate dosctring after defining a function? #1494

Open castroavila opened 1 year ago

castroavila commented 1 year ago

Hi,

Is it possible to run some command to create the docstring after a function has been defined? Let's suppose I already have defined the function:

def function(a, b=2, c=3):
    """

    """

    .....

And I want to generate the docstring to have:

def function(a, b=2, c=3):
    """Function

    Parameters
    ----------
    a : TODO
    b : TODO, optional
    c : TODO, optional

    Returns
    -------
    TODO

    """
    pass

I have checked other options to generate the docstring, however the style does match the one followed by this plugin.

Best regards, Manuel

PhilippFeO commented 8 months ago

Out of curiosity: Have you already defined your own snippet?

Probably, this repo is not the right address for your issue since it's (in my understanding) rather a collection of templates than dealing with the expansion mechanism itself–this is done with a snippet engine, fi. UltiSnips.

You wish to generate code based on existing one, ie 'Generate X based on code I have already typed/saved'. A snippet is more like 'Generate X based on this recently typed character sequence (while still being in insert mode)'. You stop the snippet expansion algorithm each time quitting insert mode. Having a snippet working on an already defined function is (based on my understanding) not possible (or at least not sensible since the trigger would be utterly complex).

Nevertheless, your wish can be fullfilled. You can either use Treesitter and, especially, Treesitter Playground to filter for the function node, ie. getting it's signature. Then you parse the signature generating your docstring and insert it via :h nvim_buf_set_lines(). You will find video on Treesitter Playground on YouTube. Another option involves moving to the line of function signature (anywhere), read the line with :h nvim_get_current_line(), parse (as above) and insert (as above). This approach has more manual labor but is a bit easier to implement.