7

I'm trying to jump to the next python class or function in vim with the following commands:

autocmd FileType python nnoremap <buffer> [[ ?^class|^\s*def<CR>
autocmd FileType python nnoremap <buffer> ]] /^class|^\s*def<CR>

But it doesn't work. Vim prompted:

Error detected while processing FileType Auto commands for "python":
E492: Not an editor command: ^\s*def<CR>

How to fix this?

Searene
  • 25,920
  • 39
  • 129
  • 186
  • Why don't use a plugin, for example, [**Python-mode**](https://github.com/klen/python-mode)? Please check [this answer](http://stackoverflow.com/a/28284564/5299236). – Remi Guan Jan 06 '16 at 05:27
  • @KevinGuan Thank you, I tried that before. It has some bugs, and I only need a small part of functionalities in it. So I think maybe I can write something that is more suitable for me :) – Searene Jan 06 '16 at 05:30
  • Why do you go through all that trouble when those mappings are *already* defined in `$VIMRUNTIME/ftplugin/python.vim`? – romainl Jan 06 '16 at 08:29
  • 1
    @romainl But when I tried `[[` or `]]` in vim without any extra configurations, it can only jump to the previous/next class, skipping all the class methods in between. – Searene Jan 06 '16 at 10:55
  • 1
    @romainl I just leafed through `python.vim` file, and found that `[m` and `]m` worked the way as I expected. Thank you. :) – Searene Jan 06 '16 at 11:03

1 Answers1

6

After lots of trying, I found the following code worked. I need to add \\ before |

autocmd FileType python nnoremap <buffer> [[ ?^class\\|^\s*def<CR>
autocmd FileType python nnoremap <buffer> ]] /^class\\|^\s*def<CR>

As an alternative way, I found that putting the two lines in ~/.vim/ftplugin/python.vim is more convenient

nnoremap [[ ?^class\|^\s*def<CR>
nnoremap ]] /^class\|^\s*def<CR>
Searene
  • 25,920
  • 39
  • 129
  • 186
  • Thank you. I used the following improved regex: ``autocmd FileType python nnoremap ?^\s*\zs\\\|^\s*\zs\`` (other one analogous, mapped to C-j) – Torben Klein Jul 21 '20 at 07:59
  • Hi, why second code without `` `nnoremap [[ ?^class\|^\s*def` is not working in `.vimrc` ? I am using mostly python. – Grzegorz Krug Dec 03 '20 at 14:35
  • @GrzegorzKrug, the observation on changing "\" to "\\" is valid for the second form too. – Caco Dec 08 '22 at 20:54