0

Consider the below function definition:

def function(self, arg1, arg2):
    """Function for doing something.

    Args:
         arg1: Argument 1.
         arg2: Argument 2.
    Returns:
         Returns something.
    """
    ...
    ...

What would the easiest way of selecting the whole docstring be? For example, I can easily select the inner and outer perimeters of a function using built-in square bracket mappings (i.e. [m or ]m), but what about the docstrings themselves? The best I can do now is using square-bracket mappings to jump to the beginning of a function definition, going down a line, then manually highlighting using visual-mode selection. Assuming my cursor is within the function block, this is how I would approach docstring selection:

  1. [m to go to beginning of function definition
  2. j to go down a line
  3. V to go to line-wise visual mode
  4. {n}j to go down whatever the relative-line number of last """ is

Is there any way of making this easier? I think at least there must be some workaround for step 4 which can be quite tedious. Perhaps some pattern matching? g* for selection was an idea I had but it only works if the triple quotation marks are isolated in their own line.

3
  • That's a docstring, not a comment. Commented Feb 28, 2018 at 0:23
  • @IgnacioVazquez-Abrams Oops. Thank you for clarifying. I edited the question appropriately. Commented Feb 28, 2018 at 0:43
  • I am very happy you found the [m and other "method" mappings. I find these to be very under utilized. Commented Feb 28, 2018 at 16:00

2 Answers 2

2

I would recommend making a docstring text-object. Like id/ad.

Put the following in ~/.vim/after/ftplugin/python.vim:

function! s:docstring(...)
    call search('^\s*def.*\n\s*\zs"""\_s*.', 'bc' . (a:0 ? 'e' : ''))
    normal! m<
    if a:0
        call search('.\ze\_s*"""', 'e')
    else
        call search('"""', 'e')
        call search('"""', 'e')
    endif
    normal! m>
    normal! `<v`>
endfunction

xnoremap <buffer> id :<c-u>call <SID>docstring(1)<cr>gv
xnoremap <buffer> ad :<c-u>call <SID>docstring()<cr>gv
onoremap <buffer> id :normal vid<cr>
onoremap <buffer> ad :normal vad<cr>

Now you can do use the id/ad text-objects as you would any Vim text objects.

Sign up to request clarification or add additional context in comments.

Comments

1

quick and dirty:

nmap <f10> [m/"""<cr>vn

in function/method body, press <f10> will select docstring.

1 Comment

there is [m @phd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.