1

When I search for a text with grep it gives the filename followed by a colon and a line number likethis, and then I just double click /foo:123:bar with the mouse:

$ grep -rn bar /
/foo:123:bar

Then I want to open that file at the line number with the cursor centered vertically. I have tried with adding this script to ~/.vimrc without luck but it looks somehow close.

if argc() >= 1 && argv(0) =~ ':'
  let filename = matchstr(argv(0), '^[^:]\+')
  let line_number = matchstr(argv(0), ':\d\+')
  let line_number = tr(line_number, ':', ' ')
  "echo "Filename: " . filename . ", line: " . line_number . ", (" . argv(0) .")"
  if filereadable(filename)
    execute 'edit ' . filename
    filetype detect
    execute line_number
    normal! zz
  else
    echo "File not found: " . filename . " (" . argv(0) .")"
  endif
endif

I could do it with bash but it is not that convenient:

#! /bin/bash
if [[ $1 =~ ^(.*):([0-9]+) ]]
then
    vim "${BASH_REMATCH[1]}" +${BASH_REMATCH[2]} -c 'normal! zz'
else
    vim $@
fi
2

2 Answers 2

1

I believe the problem you have with your solution is that at the moment the .vimrc is executed Vim is not fully ready to execute some of the command on the buffer (in particular the zz command).

Here is what you could do:

function! OpenFile()
  if argc() >= 1 && argv(0) =~ ':'
    let filename = matchstr(argv(0), '^[^:]\+')
    let line_number = matchstr(argv(0), ':\d\+')
    let line_number = tr(line_number, ':', ' ')
    "echo "Filename: " . filename . " (" . argv(0) .")"
    if filereadable(filename)
      execute 'edit ' . filename
      filetype detect
      execute line_number
      normal! zz
    else
      echo "File not found: " . filename . " (" . argv(0) .")"
    endif
  endif
endfunction

autocmd VimEnter * call OpenFile()

It delays the execution of your script after Vim is fully initialized.

0
1

Another idea: use :grep. After :grep -r bar / (-n is implied by the default grepprg), the quickfix list would have the entry for /foo at line 123, your cursor would be there, and you can press zz yourself.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.