How to replace text with current filename in VIM?

Viewed 2898

I suppose my question in not that clear but let me try to explain it here.

Let's suppose I have opened a file named myfilename.java with the below content

public class test{
}

Now, what I want is to replace test with myfilename. Now to get the filename in vim I used :echo expand('%:r') which gave me myfilename.

Now, my question is how to do I use the above output and replace test with it and map it to a key for future use. What I need is may be something like:

:%s/test/above_output_from_command/g
2 Answers

For my application, I ended up using a keybound macro (not sure what the VIM) name for this is) that did the edit I want and simply inserted the filename where I wanted it:

:nmap <F5> 0d$:put =expand('%:p:t')^M0ipackage ^[$a;^[

In my case, I wanted to insert the name of the containint directory instead of the file, so I used:

:nmap <F5> 0d$:put =expand('%:p:h:t')^M0ipackage ^[$a;^[

The 0d$ deletes the contents of the current line, :put =expand('%:p:t')^M inserts the filename, and the remaining commands edit the line around the command to produce something like

package containing_directory;

on the current line.

Related