TomCaps
TomCaps

Reputation: 2527

Is there a way to refer to the current selected text in a command in Vim?

Say in my C head file I wanna include another file which has not being created yet:

#include "AnotherFile.h" /*not being created yet*/

Now, I select the file in Visual Mode,
#include "AnotherFile.h"

How to create a new file with the name of what I've selected? I mean,

:e  {something that  refers to what I selected} 

Upvotes: 4

Views: 870

Answers (4)

sehe
sehe

Reputation: 393829

Most often, you'll want to just yank a valid filename from around the current cursor position. Vim has a feature to detect plausible/valid filenames (isfname) and you can use it without selecting anything, typing C-rC-f

Alternatively there is C-rC-w for the currently selected word.

As mentioned by others you can also refer to any register using C-r<reg> (so e.g. C-r" for the default register)

Upvotes: 1

Ves
Ves

Reputation: 1292

In Command-line mode CTRL-R followed by register "name" inserts the contents of specified register.

Assuming you have just selected the file name, press y :e SPACE CTRL + R" ENTER which means:

  • y -- yank selected text into unnamed register
  • :e + SPACE -- enter Command-line mode and start typing your :edit command
  • CTRL-R" -- insert just yanked text

See :help c_CTRL-R, :help registers.

BTW, CTRL-R does the same in insert mode too, I do use it often. See :help i_CTRL_R

Upvotes: 5

Thorsten Lorenz
Thorsten Lorenz

Reputation: 11847

Assuming you selected the filename while in visual mode:

  1. Yank the selected filename by pressing y
  2. Bring up the command window by pressing q: while still in normal mode
  3. Press i to go into insert mode inside the command window and type e
  4. Escape into normal mode and press p to paste the yanked filename
  5. Press Enter

Of course if you need to do this often, you should create a macro and map it to some easy to remember key combination.

Upvotes: 1

Ren&#233; Nyffenegger
Ren&#233; Nyffenegger

Reputation: 40603

The closest I can think of is to create a function:

function! W() range
  execute "e " .  getline("'<")[getpos("'<")[2]-1:getpos("'>")[2]] 
endfu

You can then select the word and type :call W() + enter, which should open the new buffer.

EDIT The function above does not work without errors if the buffer containing the #include is modified. In such case, the following function is suited better:

function! W() range
  let l:fileName = getline("'<")[getpos("'<")[2]-1:getpos("'>")[2]] 
  new      
  execute "w " . l:fileName
endfu

EDIT 2 You can also try to type :e <cfile> (see :help <cfile>).

EDIT 3 Finally, under :help gf you find hidden

If you do want to edit a new file, use: >
        :e <cfile>
To make gf always work like that: 
        :map gf :e <cfile><CR>

Upvotes: 6

Related Questions