Create a file under the cursor in Vim
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping
--
Chapters
00:00 Create A File Under The Cursor In Vim
00:25 Accepted Answer Score 21
01:26 Answer 2 Score 2
02:50 Thank you
--
Full question
https://superuser.com/questions/277325/c...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#vim
#avk47
ACCEPTED ANSWER
Score 21
The first thing that comes to my mind is to use the touch
command
with the filename under the cursor as an argument:
:map <silent> <leader>cf :!touch <c-r><c-p><cr><cr>
But there is a pure Vim solution that is portable across platforms.
The built-in function writefile
writes the contents of a list to
a file, line by line. Naturally, when the input list is empty, it
creates an empty file. (See :help writefile()
for details.) We can
take advantage of this side-effect:
:map <silent> <leader>cf :call writefile([], expand("<cfile>"), "t")<cr>
Note that the filename extraction could be adjusted by using
a different expand
pattern (see :help expand()
).
By the way, if one would like not to create a file, but just to open
it for editing, one can define a simpler gf
-like mapping:
:map <leader>gf :e <cfile><cr>
where the :e
command can be replaced with :tabe
or a similar
command.
ANSWER 2
Score 2
I took the excellent answer by ib above and expanded it as follows. My goal was to use vim to create new markdown files as needed for a wiki (in this case a Gollum wiki)
I first tried:
map <silent> <leader>cf :call writefile([], expand("<cfile>"), "t")<cr>`
the above does work as stated in the answer. However, at first I thought it was not working because I did not actually see the file opening in vim. Using the second bit of code below will open a new file - this is more what I was looking for. So I combined them and tried:
map <leader>cf :e <cfile><cr>
but that does not work for a wiki because when you try to create a new file in the wiki using syntax like [[the-new-file]]
the wiki syntax does not allow for the extension of the file in the brackets. However, Vim needs to know the extension when creating a new file for this to work. In this case I used:
map <leader>cf :e <cfile>.md<cr>
so I could create new markdown files. There are ways to further customize this (for example by not hardcoding the extension) but the above works fine for my needs. If I ever need another extension (for example to save a .wiki file) I will probably just take the simple route and make another map like:
map <leader>cwf :e <cfile>.wiki<cr>
As a side benefit you can use the same command to open the already existing markdown file (the standard gf
command will not work here because the file extension is missing).