Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM + Python - "gd" command not working properly

I'm getting started with using VIM to program Python. I've run into some issues, hopefully someone can help me with this one.

The "gd" command is supposed to take you to the first place a variable is defined/used in the current function. From what I understand, it's the same as doing "[[" to go to the top of the function, then performing a search for the variable name.

Problem is, when I try this in Python functions, vim finds the first occurrence of the variable in the entire file.

Any thoughts on why this happens/how I can fix this?

like image 372
Edan Maor Avatar asked Jan 17 '11 09:01

Edan Maor


1 Answers

I think the problem is due to the way that Vim treats a function. From the documentation for [[:

                            *[[*
[[          [count] sections backward or to the previous '{' in
            the first column.  |exclusive|
            Note that |exclusive-linewise| often applies.

Unless a section is somehow defined specifically for python files somewhere (I'm not convinced this is possible as they're supposed to be two-letter nroff sections), this will assume that there should be an open-brace in the first column, which isn't relevant for python files.

I'd suggest asking on the Vim mailing list to see if there are any plugins or work-arounds for this. Alternatively, you could define a mapping like this:

nmap gd :let varname = '\<<C-R><C-W>\>'<CR>?\<def\><CR>/<C-R>=varname<CR><CR>

This could be done more elegantly with a function, but this was just a quick hack that should work. It maps gd to a function that sets the variable 'varname' to hold the word the cursor is on, searches backward for def and then searches forward for the variable:

    :let varname =             " Variable setting
    '\<                        " String start and word boundary
    <C-R><C-W>                 " Ctrl-R, Ctrl-W: pull in the word under the cursor
    \>'                        " Word boundary and string end
    <CR>                       " Enter - finish this command
    ?                          " Search backwards for...
    \<def\>                    " def but not undefined etc (using word boundaries)
    <CR>                       " Enter - Perform search
    /                          " Now search forward
    <C-R>=                     " Pull in something from an expression
    varname<CR>                " The expression is 'varname', so pull in the contents of varname
    <CR>                       " Enter - perform search
like image 66
DrAl Avatar answered Sep 29 '22 06:09

DrAl