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

Say in my C head file, I want to add another file that has not been 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 selected? I mean,

 :e {something that refers to what I selected} 
+4
source share
4 answers

The closest I can think of is creating a function:

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

Then you can select a word and enter :call W() + enter, which should open a new buffer.

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

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

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

EDIT 3 Finally, under :help gf you will 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> 
+6
source

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

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

  • y - cross out selected text in unwritten case
  • :e + SPACE - enter command line mode and start typing :edit
  • CTRL-R" - insert pulled text only

See :help c_CTRL-R :help registers .

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

+4
source

Assuming you selected the file name in visual mode:

  • Remove the selected file name by pressing y
  • Raise the command window by pressing q: while still in normal mode
  • Press i to switch to insert mode in the command window and enter e
  • Esc ape to normal mode and press p to insert the desired file name
  • 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.

+1
source

Most often, you just need to pull out the actual file name from the current cursor position. Vim has a function for determining plausible / valid file names ( isfname ), and you can use them without selecting anything by typing Cr Cf

An alternative to the currently selected word is Cr Cw .

As others have mentioned, you can also access any register using Cr <reg> (e.g. Cr " for the default register)

+1
source

Source: https://habr.com/ru/post/1386448/


All Articles