tags:

views:

99

answers:

2

When I use vi to open a file *.c, I would like the cursor to move to the string "main" automatically. If there is no "main", I want the cursor to go to "void" without an error prompt.

In my .vimrc I have set

:autocmd BufRead *.c 1;/main 

but this cannot implement all my requirements. Specifically, if there exists no "main" in some opened C source file, vi prompts "Error, cannot find main ...." which is the behaviour I want to remove.

I have also tried adding <silent> or :silent to that autocmd line, but it doesn't do what I want. Can anyone help me? Thanks.

A: 

Try /main\|^, but if cursor in file not on first line - it's not that you want.

W55tKQbuRu28Q4xv
+2  A: 

Just use silent! that runs command blocking not only normal messages but also errors.

By the way, I recommend you to use BufReadPost (to run your command after a buffer would be loaded) and search for "main" as a whole word.

So try this:

:autocmd BufReadPost *.c :silent! 1;/\<main\>
ib
Thanks. Could you tell me how to implement structure control in vimrc such as If-else structure. For example, if there is "main", cursor go to "main" and if no "main", cursor go to "void".
fortunetell
If/else structure is not complicated, just take a look at `:help if`. To search you could use `search` function that returns line number where occurrence has been found or zero (without raising an error). For example `:if search('\<main\>') == 0 | call search('\<void\>') | endif` This command tests whether or not word "main" could be found starting from current cursor position, and if not (search returns zero) calling search function for "void"
ib
So you could transform your autocmd to something like that: `:autocmd BufReadPost *.c :silent! 1 | if search('\<main\>') == 0 | call search('\<void\>') | endif` Note that several statements on one line should be separated with `|`. Also, for calling function outside of Vim command (`if`, `while`, `let`, etc.) it's necessary to use `call`.
ib