0

I'm new to vim language and I'd like to see a new tab opening when I hit the enter keyboard on a line containing only a path of a file.

When I create a map like this

nnoremap <buffer> <cr> :tabnew getline('.')<cr>

I get a new tab to open but with no content and with this title 2 getline('.')<cr>.

I guess my problem is to somehow expand getline('.').

Any ideas.

1

The :tabnew command takes a literal file name and not an expression. In order to pass it the contents of a variable or an expression, you need to assemble the command as a string and pass it to :execute.

This will work:

nnoremap <buffer> <cr> :execute 'tabnew '.getline('.')<cr>

You might want to also pass nnoremap a <silent> flag so that the Ex command line does not get printed when the mapping is executed:

nnoremap <buffer> <silent> <cr> :execute 'tabnew '.getline('.')<cr>

For this particular situation, there's already a native Vim key binding that does almost the same as what this does. In fact, you could argue it's even better than this mapping, since it recognizes a file name under the cursor even if there are more contents in the line around the filename, and it also does lookup in 'path' which is very useful to handle included or imported files (common in many programming languages.) The key binding is CTRL-W gf, which is analogous to gf, but opens the file under the cursor in a new tab.

You could map <cr> in the current buffer to open the file under the cursor in a new tab with:

nnoremap <buffer> <cr> <C-w>gf
2
  • Doesnt one of the gf combos open a tab? C-w C-f maybe? – D. Ben Knoble Dec 2 '20 at 14:15
  • 1
    Good call @Ben! I just updated the answer to include CTRL-W gf, explain how it's different (better) than the original mapping, and how to keep mapping <cr> to execute that command. Thanks! – filbranden Dec 2 '20 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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