mcmlxxxvi
mcmlxxxvi

Reputation: 1409

Function to open a file and navigate to a specified line number

I have the output of recursive grep (actually ag) in a buffer, which is of the form filename:linenumber: ... [match] ..., and I want to be able to go to the occurrence (file and line number) currently under the cursor. This told me that I could execute normal-mode movements, so after extracting the file:line portion, I wrote this function:

function OpenFileNewTab(name)
    let l:pair=split(a:name, ":")
    execute "tabnew" get(l:pair, 0)
    execute "normal!" get(l:pair, 1) . "G"
endfunction

It is supposed to open the specified file in a tab and then do <lineno>G, like I am able to do manually, to go to the specified line number. However, the cursor just stays on line 1. What am I doing wrong?

This question, by title alone, would be an exact duplicate, but it talks locating symbols in other files, while I already have the locations at hand.

Edit: My mappings for grep / ag are as follows:

nnoremap <Leader>ag :execute "new \| read !ag --literal -w" "<C-r><C-w>" g:repo \| :set filetype=c<CR>
nnoremap <Leader>gf ^v2t:"zy :execute OpenFileNewTab("<C-r>z")<CR>

To get my grep / ag results, I put the cursor on the word I want to search and enter <leader>ag, then, in the new buffer, I put the cursor on a line and enter <leader>gf - it selects from the start up to the second colon and calls OpenFileNewTab.

Edit 2: I'm on Cygwin, if it is of any importance - I doubt it.

Upvotes: 1

Views: 967

Answers (3)

textral
textral

Reputation: 1049

I only found this (old) thread after I posted the exact same question on vi.stackexchange: https://vi.stackexchange.com/q/39557/44764. To help anyone who comes looking, I post the best answer to my question below as an alternative to the answers already given.

The gF command, like gf, opens the file in a new tab but additionally it also positions the cursor on the line after the colon. (I note the OP defines <leader>gf so maybe vim/neovim didn't auto-define gf or gF at the time this thread was originally created.)

Upvotes: 0

Luc Hermitte
Luc Hermitte

Reputation: 32926

Why don't you set &grepprg to call ag ?

" according to man ag
set grepprg=ag\ --vimgrep\ $*
set grepformat=%f:%l:%c:%m
" And then (not tested)
nnoremap <Leader>ag :grep -w <c-r><c-w><cr>

As others have said in the comments, you are just trying to emulate what the quickfix windows already provides. And, we are lucky vim can call grep, and it has a variation point to let us specify which grep program we wish to use: 'grepprg'.

Upvotes: 3

Amadan
Amadan

Reputation: 198324

Use file-line plugin. Pressing Enter on a line in the quicklist will normally open that file; file-line will make any filename of the form file:line:column (and several other formats) to open file and position to line and column.

Upvotes: 0

Related Questions