How to replace text with current filename in VIM?

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

Answers


You need to add \= to tell Vim you're trying to call a function:

:%s/test/\=expand('%:r')/g

See :help sub-replace-expression.


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.


Need Your Help

Using Recursion to compute the number of something to print

java recursion exponent

I learning recursion and there is an example which I solve writing the * character a certain amount of times.