Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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} 
like image 732
TomCaps Avatar asked Dec 17 '22 06:12

TomCaps


2 Answers

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>
like image 168
René Nyffenegger Avatar answered Dec 21 '22 10:12

René Nyffenegger


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

like image 43
Ves Avatar answered Dec 21 '22 10:12

Ves